@draht/tui 2026.9.5-1 → 2026.10.4-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 (167) hide show
  1. package/dist/alt-screen-search.d.ts +46 -0
  2. package/dist/alt-screen-search.d.ts.map +1 -0
  3. package/dist/alt-screen-search.js +282 -0
  4. package/dist/alt-screen-search.js.map +1 -0
  5. package/dist/autocomplete.d.ts.map +1 -1
  6. package/dist/autocomplete.js +45 -15
  7. package/dist/autocomplete.js.map +1 -1
  8. package/dist/colors.d.ts +73 -0
  9. package/dist/colors.d.ts.map +1 -0
  10. package/dist/colors.js +273 -0
  11. package/dist/colors.js.map +1 -0
  12. package/dist/components/alt-screen-flash.d.ts +13 -0
  13. package/dist/components/alt-screen-flash.d.ts.map +1 -0
  14. package/dist/components/alt-screen-flash.js +37 -0
  15. package/dist/components/alt-screen-flash.js.map +1 -0
  16. package/dist/components/box.d.ts +3 -1
  17. package/dist/components/box.d.ts.map +1 -1
  18. package/dist/components/box.js +43 -9
  19. package/dist/components/box.js.map +1 -1
  20. package/dist/components/cancellable-loader.js +3 -4
  21. package/dist/components/cancellable-loader.js.map +1 -1
  22. package/dist/components/editor.d.ts +6 -1
  23. package/dist/components/editor.d.ts.map +1 -1
  24. package/dist/components/editor.js +175 -70
  25. package/dist/components/editor.js.map +1 -1
  26. package/dist/components/h-stack.d.ts +7 -0
  27. package/dist/components/h-stack.d.ts.map +1 -0
  28. package/dist/components/h-stack.js +43 -0
  29. package/dist/components/h-stack.js.map +1 -0
  30. package/dist/components/image.js +8 -0
  31. package/dist/components/image.js.map +1 -1
  32. package/dist/components/input.d.ts +12 -1
  33. package/dist/components/input.d.ts.map +1 -1
  34. package/dist/components/input.js +57 -18
  35. package/dist/components/input.js.map +1 -1
  36. package/dist/components/loader.d.ts +2 -0
  37. package/dist/components/loader.d.ts.map +1 -1
  38. package/dist/components/loader.js +19 -10
  39. package/dist/components/loader.js.map +1 -1
  40. package/dist/components/markdown.d.ts +5 -0
  41. package/dist/components/markdown.d.ts.map +1 -1
  42. package/dist/components/markdown.js +148 -5
  43. package/dist/components/markdown.js.map +1 -1
  44. package/dist/components/mouse-region.d.ts +12 -0
  45. package/dist/components/mouse-region.d.ts.map +1 -0
  46. package/dist/components/mouse-region.js +21 -0
  47. package/dist/components/mouse-region.js.map +1 -0
  48. package/dist/components/scroll-view.d.ts +59 -0
  49. package/dist/components/scroll-view.d.ts.map +1 -0
  50. package/dist/components/scroll-view.js +195 -0
  51. package/dist/components/scroll-view.js.map +1 -0
  52. package/dist/components/select-list.d.ts +12 -1
  53. package/dist/components/select-list.d.ts.map +1 -1
  54. package/dist/components/select-list.js +72 -10
  55. package/dist/components/select-list.js.map +1 -1
  56. package/dist/components/settings-list.d.ts +13 -3
  57. package/dist/components/settings-list.d.ts.map +1 -1
  58. package/dist/components/settings-list.js +91 -13
  59. package/dist/components/settings-list.js.map +1 -1
  60. package/dist/components/spacer.js +1 -0
  61. package/dist/components/spacer.js.map +1 -1
  62. package/dist/components/stack.d.ts +32 -0
  63. package/dist/components/stack.d.ts.map +1 -0
  64. package/dist/components/stack.js +111 -0
  65. package/dist/components/stack.js.map +1 -0
  66. package/dist/components/text.js +8 -0
  67. package/dist/components/text.js.map +1 -1
  68. package/dist/components/truncated-text.js +3 -0
  69. package/dist/components/truncated-text.js.map +1 -1
  70. package/dist/components/v-stack.d.ts +8 -0
  71. package/dist/components/v-stack.d.ts.map +1 -0
  72. package/dist/components/v-stack.js +26 -0
  73. package/dist/components/v-stack.js.map +1 -0
  74. package/dist/fuzzy.d.ts.map +1 -1
  75. package/dist/fuzzy.js +23 -22
  76. package/dist/fuzzy.js.map +1 -1
  77. package/dist/index.d.ts +16 -4
  78. package/dist/index.d.ts.map +1 -1
  79. package/dist/index.js +18 -4
  80. package/dist/index.js.map +1 -1
  81. package/dist/keybindings.d.ts +84 -4
  82. package/dist/keybindings.d.ts.map +1 -1
  83. package/dist/keybindings.js +67 -6
  84. package/dist/keybindings.js.map +1 -1
  85. package/dist/kill-ring.js +1 -3
  86. package/dist/kill-ring.js.map +1 -1
  87. package/dist/latex.d.ts +10 -0
  88. package/dist/latex.d.ts.map +1 -0
  89. package/dist/latex.js +1378 -0
  90. package/dist/latex.js.map +1 -0
  91. package/dist/layout-node.d.ts +40 -0
  92. package/dist/layout-node.d.ts.map +1 -0
  93. package/dist/layout-node.js +6 -0
  94. package/dist/layout-node.js.map +1 -0
  95. package/dist/layout.d.ts +42 -0
  96. package/dist/layout.d.ts.map +1 -0
  97. package/dist/layout.js +344 -0
  98. package/dist/layout.js.map +1 -0
  99. package/dist/native-modifiers.d.ts +2 -1
  100. package/dist/native-modifiers.d.ts.map +1 -1
  101. package/dist/native-modifiers.js +3 -43
  102. package/dist/native-modifiers.js.map +1 -1
  103. package/dist/native-module-path.d.ts +7 -0
  104. package/dist/native-module-path.d.ts.map +1 -0
  105. package/dist/native-module-path.js +19 -0
  106. package/dist/native-module-path.js.map +1 -0
  107. package/dist/native-platform.d.ts +20 -0
  108. package/dist/native-platform.d.ts.map +1 -0
  109. package/dist/native-platform.js +42 -0
  110. package/dist/native-platform.js.map +1 -0
  111. package/dist/oklab.d.ts +43 -0
  112. package/dist/oklab.d.ts.map +1 -0
  113. package/dist/oklab.js +210 -0
  114. package/dist/oklab.js.map +1 -0
  115. package/dist/stdin-buffer.d.ts +1 -1
  116. package/dist/stdin-buffer.js +8 -5
  117. package/dist/stdin-buffer.js.map +1 -1
  118. package/dist/terminal-colors.d.ts +19 -2
  119. package/dist/terminal-colors.d.ts.map +1 -1
  120. package/dist/terminal-colors.js +12 -7
  121. package/dist/terminal-colors.js.map +1 -1
  122. package/dist/terminal-image.d.ts +26 -1
  123. package/dist/terminal-image.d.ts.map +1 -1
  124. package/dist/terminal-image.js +187 -13
  125. package/dist/terminal-image.js.map +1 -1
  126. package/dist/terminal.d.ts +4 -0
  127. package/dist/terminal.d.ts.map +1 -1
  128. package/dist/terminal.js +53 -63
  129. package/dist/terminal.js.map +1 -1
  130. package/dist/tui-alt-screen.d.ts +164 -0
  131. package/dist/tui-alt-screen.d.ts.map +1 -0
  132. package/dist/tui-alt-screen.js +1512 -0
  133. package/dist/tui-alt-screen.js.map +1 -0
  134. package/dist/tui-main-screen.d.ts +39 -0
  135. package/dist/tui-main-screen.d.ts.map +1 -0
  136. package/dist/tui-main-screen.js +594 -0
  137. package/dist/tui-main-screen.js.map +1 -0
  138. package/dist/tui.d.ts +178 -60
  139. package/dist/tui.d.ts.map +1 -1
  140. package/dist/tui.js +320 -715
  141. package/dist/tui.js.map +1 -1
  142. package/dist/undo-stack.js +1 -3
  143. package/dist/undo-stack.js.map +1 -1
  144. package/dist/utils.d.ts +16 -0
  145. package/dist/utils.d.ts.map +1 -1
  146. package/dist/utils.js +221 -73
  147. package/dist/utils.js.map +1 -1
  148. package/dist/wheel-scroll.d.ts +23 -0
  149. package/dist/wheel-scroll.d.ts.map +1 -0
  150. package/dist/wheel-scroll.js +73 -0
  151. package/dist/wheel-scroll.js.map +1 -0
  152. package/native/clipboard.h +208 -0
  153. package/native/darwin/build.sh +69 -0
  154. package/native/darwin/prebuilds/darwin-arm64/darwin-platform.node +0 -0
  155. package/native/darwin/prebuilds/darwin-x64/darwin-platform.node +0 -0
  156. package/native/darwin/src/darwin-platform.m +132 -0
  157. package/native/linux/build.sh +65 -0
  158. package/native/linux/prebuilds/linux-arm64/linux-platform-x11.node +0 -0
  159. package/native/linux/prebuilds/linux-x64/linux-platform-x11.node +0 -0
  160. package/native/linux/src/clipboard-worker.h +70 -0
  161. package/native/linux/src/linux-platform-x11.c +274 -0
  162. package/native/napi.h +91 -0
  163. package/native/win32/build.mjs +232 -0
  164. package/native/win32/prebuilds/win32-arm64/win32-platform.node +0 -0
  165. package/native/win32/prebuilds/win32-x64/win32-platform.node +0 -0
  166. package/native/win32/src/win32-platform.c +241 -0
  167. package/package.json +16 -2
package/dist/tui.js CHANGED
@@ -1,105 +1,61 @@
1
1
  /**
2
2
  * Minimal TUI implementation with differential rendering
3
3
  */
4
- import * as fs from "node:fs";
5
- import * as os from "node:os";
6
- import * as path from "node:path";
7
4
  import { performance } from "node:perf_hooks";
8
5
  import { isKeyRelease, matchesKey } from "./keys.js";
9
- import { isOsc11BackgroundColorResponse, parseOsc11BackgroundColor, parseTerminalColorSchemeReport, } from "./terminal-colors.js";
10
- import { deleteKittyImage, getCapabilities, isImageLine, setCellDimensions } from "./terminal-image.js";
6
+ import { parseOscColorResponse, parseTerminalColorSchemeReport, } from "./terminal-colors.js";
7
+ import { getCapabilities, isImageLine, setCellDimensions } from "./terminal-image.js";
11
8
  import { extractSegments, normalizeTerminalOutput, sliceByColumn, sliceWithWidth, visibleWidth } from "./utils.js";
12
- const KITTY_SEQUENCE_PREFIX = "\x1b_G";
13
- const MAX_RENDER_WRITE_CHARS = 1024 * 1024;
14
9
  /**
15
- * Streams terminal output in 1 MiB chunks so a full render never forms one string large enough to exceed V8's limit.
16
- *
17
- * `append()` fills the current chunk and flushes it when full. Oversized input is split at chunk boundaries, preserving
18
- * surrogate pairs so each write remains valid UTF-16. Callers append synchronized-output begin/end sequences themselves;
19
- * the final `flush()` writes any remainder, including the end sequence.
10
+ * Dispatch an event to a component and retain the exact target and coordinate
11
+ * transform. Containers use this when forwarding events to nested children.
20
12
  */
21
- class BoundedTerminalWriter {
22
- constructor(write) {
23
- this.buffer = "";
24
- this.writtenChars = 0;
25
- this.write = write;
26
- }
27
- /**
28
- * Append terminal data, flushing full chunks as needed. Callers must call `flush()` after the final append.
29
- * @param value Terminal data to write in order; oversized values are split without splitting surrogate pairs.
30
- */
31
- append(value) {
32
- let offset = 0;
33
- while (offset < value.length) {
34
- const capacity = MAX_RENDER_WRITE_CHARS - this.buffer.length;
35
- if (capacity === 0) {
36
- this.flush();
37
- continue;
38
- }
39
- let end = Math.min(value.length, offset + capacity);
40
- if (end < value.length &&
41
- value.charCodeAt(end - 1) >= 0xd800 &&
42
- value.charCodeAt(end - 1) <= 0xdbff &&
43
- value.charCodeAt(end) >= 0xdc00 &&
44
- value.charCodeAt(end) <= 0xdfff) {
45
- end--;
46
- }
47
- if (end === offset) {
48
- this.flush();
49
- continue;
50
- }
51
- this.buffer += value.slice(offset, end);
52
- offset = end;
53
- if (this.buffer.length === MAX_RENDER_WRITE_CHARS) {
54
- this.flush();
55
- }
56
- }
57
- }
58
- /** Write the current chunk, if any, and retain only its character count for debug output. */
59
- flush() {
60
- if (!this.buffer)
61
- return;
62
- this.write(this.buffer);
63
- this.writtenChars += this.buffer.length;
64
- this.buffer = "";
65
- }
66
- get length() {
67
- return this.writtenChars + this.buffer.length;
68
- }
69
- }
70
- function parseKittyImageHeader(line) {
71
- const sequenceStart = line.indexOf(KITTY_SEQUENCE_PREFIX);
72
- if (sequenceStart === -1)
13
+ export function dispatchMouseEvent(component, event) {
14
+ const result = component.handleMouse?.(event);
15
+ if (!result)
73
16
  return undefined;
74
- const paramsStart = sequenceStart + KITTY_SEQUENCE_PREFIX.length;
75
- const paramsEnd = line.indexOf(";", paramsStart);
76
- if (paramsEnd === -1)
77
- return undefined;
78
- const ids = [];
79
- let rows = 1;
80
- const params = line.slice(paramsStart, paramsEnd);
81
- for (const param of params.split(",")) {
82
- const [key, value] = param.split("=", 2);
83
- if (value === undefined)
84
- continue;
85
- const numberValue = Number(value);
86
- if (!Number.isInteger(numberValue) || numberValue <= 0 || numberValue > 0xffffffff)
87
- continue;
88
- if (key === "i") {
89
- ids.push(numberValue);
90
- }
91
- else if (key === "r") {
92
- rows = numberValue;
93
- }
17
+ if ("target" in result) {
18
+ // The component forwarded the event to a child it hosts. Like a delegating container, it routes
19
+ // keys to that child itself, so it keeps keyboard focus. Focusing the child directly would leave
20
+ // focus on a detached component once the host removes it, e.g. a closed settings submenu.
21
+ const forwarded = result;
22
+ return forwarded.focus && component.handleInput ? { ...forwarded, focusTarget: component } : forwarded;
94
23
  }
95
- return { ids, rows };
96
- }
97
- function extractKittyImageIds(line) {
98
- return parseKittyImageHeader(line)?.ids ?? [];
24
+ if (!result.handled && !result.capture && !result.focus)
25
+ return undefined;
26
+ return {
27
+ ...result,
28
+ handled: true,
29
+ ...(result.focus ? { focusTarget: component } : {}),
30
+ target: {
31
+ component,
32
+ originX: event.screenX - event.x,
33
+ originY: event.screenY - event.y,
34
+ width: event.width,
35
+ height: event.height,
36
+ },
37
+ };
99
38
  }
100
- function extractKittyImageRows(line) {
101
- return parseKittyImageHeader(line)?.rows ?? 1;
39
+ /** Recreate local coordinates for a previously dispatched mouse target. */
40
+ export function retargetMouseEvent(event, target) {
41
+ return {
42
+ ...event,
43
+ x: event.screenX - target.originX,
44
+ y: event.screenY - target.originY,
45
+ width: target.width,
46
+ height: target.height,
47
+ };
102
48
  }
49
+ const TERMINAL_PALETTE_SIZE = 16;
50
+ /** OSC 10 and 11 plus OSC 4 for every palette color. */
51
+ const TERMINAL_COLOR_REPLY_COUNT = 2 + TERMINAL_PALETTE_SIZE;
52
+ /**
53
+ * Default colors, palette colors 0-15, and a trailing primary device attributes (DA1) request.
54
+ * Every terminal answers DA1 and terminals answer in order, so the DA1 reply marks the end of
55
+ * the color replies, including for terminals that ignore the color queries.
56
+ */
57
+ const TERMINAL_COLOR_QUERY = `\x1b]10;?\x07\x1b]11;?\x07${Array.from({ length: TERMINAL_PALETTE_SIZE }, (_, index) => `\x1b]4;${index};?\x07`).join("")}\x1b[c`;
58
+ const DEVICE_ATTRIBUTES_RESPONSE_PATTERN = /^\x1b\[\?[\d;]*c$/;
103
59
  /** Type guard to check if a component implements Focusable */
104
60
  export function isFocusable(component) {
105
61
  return component !== null && "focused" in component;
@@ -125,16 +81,12 @@ function parseSizeValue(value, referenceSize) {
125
81
  }
126
82
  return undefined;
127
83
  }
128
- function isTermuxSession() {
129
- return Boolean(process.env.TERMUX_VERSION);
130
- }
131
84
  /**
132
85
  * Container - a component that contains other components
133
86
  */
134
87
  export class Container {
135
- constructor() {
136
- this.children = [];
137
- }
88
+ children = [];
89
+ mouseLayout;
138
90
  addChild(component) {
139
91
  this.children.push(component);
140
92
  }
@@ -152,55 +104,118 @@ export class Container {
152
104
  child.invalidate?.();
153
105
  }
154
106
  }
107
+ handleMouse(event) {
108
+ if (event.y < 0 || event.y >= event.height)
109
+ return undefined;
110
+ const mouseChildren = this.mouseLayout?.width === event.width
111
+ ? this.mouseLayout.children
112
+ : this.children.map((component) => ({ component, height: component.render(event.width).length }));
113
+ let childY = 0;
114
+ for (const { component: child, height: childHeight } of mouseChildren) {
115
+ if (event.y >= childY && event.y < childY + childHeight) {
116
+ const result = dispatchMouseEvent(child, {
117
+ ...event,
118
+ y: event.y - childY,
119
+ height: childHeight,
120
+ });
121
+ if (result?.focus && this.handleInput)
122
+ return { ...result, focusTarget: this };
123
+ return result;
124
+ }
125
+ childY += childHeight;
126
+ }
127
+ return undefined;
128
+ }
155
129
  render(width) {
156
130
  const lines = [];
131
+ const mouseChildren = [];
157
132
  for (const child of this.children) {
158
133
  const childLines = child.render(width);
134
+ mouseChildren.push({ component: child, height: childLines.length });
159
135
  for (const line of childLines) {
160
136
  lines.push(line);
161
137
  }
162
138
  }
139
+ this.mouseLayout = { width, children: mouseChildren };
163
140
  return lines;
164
141
  }
165
142
  }
166
143
  /**
167
144
  * TUI - Main class for managing terminal UI with differential rendering
168
145
  */
169
- export class TUI extends Container {
170
- static { this.MIN_RENDER_INTERVAL_MS = 16; }
146
+ const SEGMENT_RESET = "\x1b[0m\x1b]8;;\x07";
147
+ /** Composite overlay content into a terminal line at a fixed column. */
148
+ export function compositeTuiLine(baseLine, overlayLine, startCol, overlayWidth, totalWidth) {
149
+ if (isImageLine(baseLine))
150
+ return baseLine;
151
+ const afterStart = startCol + overlayWidth;
152
+ const base = extractSegments(baseLine, startCol, afterStart, totalWidth - afterStart, true);
153
+ const overlay = sliceWithWidth(overlayLine, 0, overlayWidth, true);
154
+ const beforePad = Math.max(0, startCol - base.beforeWidth);
155
+ const overlayPad = Math.max(0, overlayWidth - overlay.width);
156
+ const actualBeforeWidth = Math.max(startCol, base.beforeWidth);
157
+ const actualOverlayWidth = Math.max(overlayWidth, overlay.width);
158
+ const afterTarget = Math.max(0, totalWidth - actualBeforeWidth - actualOverlayWidth);
159
+ const afterPad = Math.max(0, afterTarget - base.afterWidth);
160
+ const result = base.before +
161
+ " ".repeat(beforePad) +
162
+ SEGMENT_RESET +
163
+ overlay.text +
164
+ " ".repeat(overlayPad) +
165
+ SEGMENT_RESET +
166
+ base.after +
167
+ " ".repeat(afterPad);
168
+ return visibleWidth(result) <= totalWidth ? result : sliceByColumn(result, 0, totalWidth, true);
169
+ }
170
+ export const VIEWPORT_TUI = Symbol.for("@draht/tui/viewport");
171
+ export function isViewportTUI(tui) {
172
+ return tui[VIEWPORT_TUI] === true;
173
+ }
174
+ export class TuiBase extends Container {
175
+ terminal;
176
+ focusedComponent = null;
177
+ inputListeners = new Set();
178
+ /** Global callback for debug key (Shift+Ctrl+D). Called before input is forwarded to focused component. */
179
+ onDebug;
180
+ renderRequested = false;
181
+ immediateRenderScheduled = false;
182
+ renderTimer;
183
+ lastRenderAt = 0;
184
+ static MIN_RENDER_INTERVAL_MS = 16;
185
+ showHardwareCursor = false;
186
+ clearOnShrink = false;
187
+ fullRedrawCount = 0;
188
+ stopped = false;
189
+ /**
190
+ * Color queries waiting for their DA1 reply, oldest first. Terminals answer in order, so color
191
+ * replies belong to the oldest one. Queries stay here after a timeout to collect late replies.
192
+ */
193
+ pendingTerminalColorQueries = [];
194
+ terminalColorSchemeListeners = new Set();
195
+ terminalColorSchemeNotificationsEnabled = false;
196
+ /** Directory for debug/crash logs. When undefined, debug logging is disabled and crash dumps fall back to the OS temp directory. */
197
+ logDirectory;
198
+ // Overlay stack for modal components rendered on top of base content
199
+ focusOrderCounter = 0;
200
+ overlayStack = [];
201
+ renderedOverlayLayouts = [];
202
+ get hasOverlayEntries() {
203
+ return this.overlayStack.length > 0;
204
+ }
205
+ overlayFocusRestore = { status: "inactive" };
171
206
  constructor(terminal, showHardwareCursor, logDirectory) {
172
207
  super();
173
- this.previousLines = [];
174
- this.previousKittyImageIds = new Set();
175
- this.previousWidth = 0;
176
- this.previousHeight = 0;
177
- this.focusedComponent = null;
178
- this.inputListeners = new Set();
179
- this.renderRequested = false;
180
- this.lastRenderAt = 0;
181
- this.cursorRow = 0; // Logical cursor row (end of rendered content)
182
- this.hardwareCursorRow = 0; // Actual terminal cursor row (may differ due to IME positioning)
183
- this.showHardwareCursor = process.env.PI_HARDWARE_CURSOR === "1";
184
- this.clearOnShrink = process.env.PI_CLEAR_ON_SHRINK === "1"; // Clear empty rows when content shrinks (default: off)
185
- this.maxLinesRendered = 0; // Track terminal's working area (max lines ever rendered)
186
- this.previousViewportTop = 0; // Track previous viewport top for resize-aware cursor moves
187
- this.fullRedrawCount = 0;
188
- this.stopped = false;
189
- this.pendingOsc11BackgroundReplies = 0;
190
- this.pendingOsc11BackgroundQueries = [];
191
- this.terminalColorSchemeListeners = new Set();
192
- this.terminalColorSchemeNotificationsEnabled = false;
193
- // Overlay stack for modal components rendered on top of base content
194
- this.focusOrderCounter = 0;
195
- this.overlayStack = [];
196
- this.overlayFocusRestore = { status: "inactive" };
197
208
  this.terminal = terminal;
198
- this.logDirectory =
199
- logDirectory ?? process.env.DRAHT_CODING_AGENT_DIR ?? path.join(os.homedir(), ".draht", "agent");
209
+ this.logDirectory = logDirectory;
200
210
  if (showHardwareCursor !== undefined) {
201
211
  this.showHardwareCursor = showHardwareCursor;
202
212
  }
203
213
  }
214
+ resetRenderState() { }
215
+ beforeTerminalStart() { }
216
+ afterTerminalStart() { }
217
+ beforeTerminalStop(_options) { }
218
+ afterTerminalStop(_options) { }
204
219
  get fullRedraws() {
205
220
  return this.fullRedrawCount;
206
221
  }
@@ -212,7 +227,7 @@ export class TUI extends Container {
212
227
  return;
213
228
  this.showHardwareCursor = enabled;
214
229
  if (!enabled) {
215
- this.terminal.hideCursor();
230
+ this.hideTerminalCursor();
216
231
  }
217
232
  this.requestRender();
218
233
  }
@@ -221,12 +236,15 @@ export class TUI extends Container {
221
236
  }
222
237
  /**
223
238
  * Set whether to trigger full re-render when content shrinks.
224
- * When true (default), empty rows are cleared when content shrinks.
225
- * When false, empty rows remain (reduces redraws on slower terminals).
239
+ * When true, empty rows are cleared when content shrinks.
240
+ * When false (default), empty rows remain (reduces redraws on slower terminals).
226
241
  */
227
242
  setClearOnShrink(enabled) {
228
243
  this.clearOnShrink = enabled;
229
244
  }
245
+ getFocusedComponent() {
246
+ return this.focusedComponent;
247
+ }
230
248
  setFocus(component) {
231
249
  this.setFocusInternal({ component, overlayFocusRestore: "clear" });
232
250
  }
@@ -327,8 +345,11 @@ export class TUI extends Container {
327
345
  }
328
346
  }
329
347
  }
348
+ getMountedRoots() {
349
+ return this.children;
350
+ }
330
351
  isComponentMounted(component) {
331
- return this.children.some((child) => this.containsComponent(child, component));
352
+ return this.getMountedRoots().some((child) => this.containsComponent(child, component));
332
353
  }
333
354
  containsComponent(root, target) {
334
355
  if (root === target)
@@ -354,7 +375,7 @@ export class TUI extends Container {
354
375
  if (!options?.nonCapturing && this.isOverlayVisible(entry)) {
355
376
  this.setFocus(component);
356
377
  }
357
- this.terminal.hideCursor();
378
+ this.hideTerminalCursor();
358
379
  this.requestRender();
359
380
  // Return handle for controlling this overlay
360
381
  return {
@@ -370,7 +391,7 @@ export class TUI extends Container {
370
391
  this.setFocus(topVisible?.component ?? entry.preFocus);
371
392
  }
372
393
  if (this.overlayStack.length === 0)
373
- this.terminal.hideCursor();
394
+ this.hideTerminalCursor();
374
395
  this.requestRender();
375
396
  }
376
397
  },
@@ -436,6 +457,11 @@ export class TUI extends Container {
436
457
  this.requestRender();
437
458
  },
438
459
  isFocused: () => this.focusedComponent === component,
460
+ getBounds: () => {
461
+ if (!this.overlayStack.includes(entry) || !this.isOverlayVisible(entry) || !entry.bounds)
462
+ return undefined;
463
+ return { ...entry.bounds };
464
+ },
439
465
  };
440
466
  }
441
467
  /** Hide the topmost overlay and restore previous focus. */
@@ -452,13 +478,58 @@ export class TUI extends Container {
452
478
  this.setFocus(topVisible?.component ?? overlay.preFocus);
453
479
  }
454
480
  if (this.overlayStack.length === 0)
455
- this.terminal.hideCursor();
481
+ this.hideTerminalCursor();
456
482
  this.requestRender();
457
483
  }
484
+ /** Hide the cursor while running. After stop(), the shell owns the cursor and it must stay visible. */
485
+ hideTerminalCursor() {
486
+ if (!this.stopped)
487
+ this.terminal.hideCursor();
488
+ }
458
489
  /** Check if there are any visible overlays */
459
490
  hasOverlay() {
460
491
  return this.overlayStack.some((o) => this.isOverlayVisible(o));
461
492
  }
493
+ /** Check if the focused component is a visible overlay */
494
+ isOverlayFocused() {
495
+ return this.overlayStack.some((entry) => entry.component === this.focusedComponent && this.isOverlayVisible(entry));
496
+ }
497
+ /** Keep overlay containers as keyboard focus owners when a nested control is clicked. */
498
+ resolveMouseFocusTarget(component) {
499
+ for (let index = this.overlayStack.length - 1; index >= 0; index--) {
500
+ const overlay = this.overlayStack[index];
501
+ if (this.isOverlayVisible(overlay) && this.containsComponent(overlay.component, component)) {
502
+ return overlay.component;
503
+ }
504
+ }
505
+ return component;
506
+ }
507
+ /** Dispatch to the visually topmost overlay under the pointer. */
508
+ dispatchMouseToOverlay(event) {
509
+ for (let index = this.renderedOverlayLayouts.length - 1; index >= 0; index--) {
510
+ const layout = this.renderedOverlayLayouts[index];
511
+ if (event.screenX < layout.col ||
512
+ event.screenX >= layout.col + layout.width ||
513
+ event.screenY < layout.row ||
514
+ event.screenY >= layout.row + layout.height) {
515
+ continue;
516
+ }
517
+ const result = dispatchMouseEvent(layout.entry.component, {
518
+ ...event,
519
+ x: event.screenX - layout.col,
520
+ y: event.screenY - layout.row,
521
+ width: layout.width,
522
+ height: layout.height,
523
+ });
524
+ return result
525
+ ? {
526
+ hit: true,
527
+ result: result.focus ? { ...result, focusTarget: layout.entry.component } : result,
528
+ }
529
+ : { hit: true };
530
+ }
531
+ return { hit: false };
532
+ }
462
533
  /** Check if an overlay entry is currently visible */
463
534
  isOverlayVisible(entry) {
464
535
  if (entry.hidden)
@@ -481,13 +552,16 @@ export class TUI extends Container {
481
552
  return topmost;
482
553
  }
483
554
  invalidate() {
484
- super.invalidate();
555
+ for (const root of this.getMountedRoots())
556
+ root.invalidate();
485
557
  for (const overlay of this.overlayStack)
486
- overlay.component.invalidate?.();
558
+ overlay.component.invalidate();
487
559
  }
488
560
  start() {
489
561
  this.stopped = false;
490
- this.terminal.start((data) => this.handleInput(data), () => this.requestRender());
562
+ this.beforeTerminalStart();
563
+ this.terminal.start((data) => this.handleTerminalInput(data), () => this.requestRender());
564
+ this.afterTerminalStart();
491
565
  this.terminal.hideCursor();
492
566
  if (this.terminalColorSchemeNotificationsEnabled) {
493
567
  this.terminal.write("\x1b[?2031h");
@@ -528,54 +602,29 @@ export class TUI extends Container {
528
602
  // Response format: CSI 6 ; height ; width t
529
603
  this.terminal.write("\x1b[16t");
530
604
  }
531
- stop() {
605
+ stop(options = {}) {
532
606
  this.stopped = true;
533
- if (this.renderTimer) {
534
- clearTimeout(this.renderTimer);
535
- this.renderTimer = undefined;
536
- }
607
+ this.cancelRenderTimer();
537
608
  if (this.terminalColorSchemeNotificationsEnabled) {
538
609
  this.terminal.write("\x1b[?2031l");
539
610
  }
540
- // Move cursor to the end of the content to prevent overwriting/artifacts on exit
541
- if (this.previousLines.length > 0) {
542
- // Overwrite the inverted cursor with a normal space to clear the artifact
543
- this.terminal.write(" ");
544
- const targetRow = this.previousLines.length; // Line after the last content
545
- const lineDiff = targetRow - this.hardwareCursorRow;
546
- if (lineDiff > 0) {
547
- this.terminal.write(`\x1b[${lineDiff}B`);
548
- }
549
- else if (lineDiff < 0) {
550
- this.terminal.write(`\x1b[${-lineDiff}A`);
551
- }
552
- this.terminal.write("\r\n");
553
- }
611
+ this.beforeTerminalStop(options);
554
612
  this.terminal.showCursor();
555
613
  this.terminal.stop();
614
+ this.afterTerminalStop(options);
615
+ }
616
+ renderNow(force = false) {
617
+ if (force)
618
+ this.resetRenderState();
619
+ this.renderRequested = false;
620
+ this.cancelRenderTimer();
621
+ this.lastRenderAt = performance.now();
622
+ this.doRender();
556
623
  }
557
624
  requestRender(force = false) {
558
625
  if (force) {
559
- this.previousLines = [];
560
- this.previousWidth = -1; // -1 triggers widthChanged, forcing a full clear
561
- this.previousHeight = -1; // -1 triggers heightChanged, forcing a full clear
562
- this.cursorRow = 0;
563
- this.hardwareCursorRow = 0;
564
- this.maxLinesRendered = 0;
565
- this.previousViewportTop = 0;
566
- if (this.renderTimer) {
567
- clearTimeout(this.renderTimer);
568
- this.renderTimer = undefined;
569
- }
570
- this.renderRequested = true;
571
- process.nextTick(() => {
572
- if (this.stopped || !this.renderRequested) {
573
- return;
574
- }
575
- this.renderRequested = false;
576
- this.lastRenderAt = performance.now();
577
- this.doRender();
578
- });
626
+ this.resetRenderState();
627
+ this.requestImmediateRender();
579
628
  return;
580
629
  }
581
630
  if (this.renderRequested)
@@ -583,12 +632,36 @@ export class TUI extends Container {
583
632
  this.renderRequested = true;
584
633
  process.nextTick(() => this.scheduleRender());
585
634
  }
635
+ requestImmediateRender() {
636
+ this.cancelRenderTimer();
637
+ this.renderRequested = true;
638
+ if (this.immediateRenderScheduled)
639
+ return;
640
+ this.immediateRenderScheduled = true;
641
+ process.nextTick(() => {
642
+ this.immediateRenderScheduled = false;
643
+ if (this.stopped || !this.renderRequested)
644
+ return;
645
+ // A previously queued scheduleRender() can create a timer before this
646
+ // callback runs. User input must preempt that throttled frame.
647
+ this.cancelRenderTimer();
648
+ this.renderRequested = false;
649
+ this.lastRenderAt = performance.now();
650
+ this.doRender();
651
+ });
652
+ }
653
+ cancelRenderTimer() {
654
+ if (!this.renderTimer)
655
+ return;
656
+ clearTimeout(this.renderTimer);
657
+ this.renderTimer = undefined;
658
+ }
586
659
  scheduleRender() {
587
660
  if (this.stopped || this.renderTimer || !this.renderRequested) {
588
661
  return;
589
662
  }
590
663
  const elapsed = performance.now() - this.lastRenderAt;
591
- const delay = Math.max(0, TUI.MIN_RENDER_INTERVAL_MS - elapsed);
664
+ const delay = Math.max(0, TuiBase.MIN_RENDER_INTERVAL_MS - elapsed);
592
665
  this.renderTimer = setTimeout(() => {
593
666
  this.renderTimer = undefined;
594
667
  if (this.stopped || !this.renderRequested) {
@@ -602,8 +675,8 @@ export class TUI extends Container {
602
675
  }
603
676
  }, delay);
604
677
  }
605
- handleInput(data) {
606
- if (this.consumeOsc11BackgroundResponse(data)) {
678
+ handleTerminalInput(data) {
679
+ if (this.consumeTerminalColorResponse(data)) {
607
680
  return;
608
681
  }
609
682
  if (this.consumeTerminalColorSchemeReport(data)) {
@@ -671,30 +744,55 @@ export class TUI extends Container {
671
744
  return;
672
745
  }
673
746
  this.focusedComponent.handleInput(data);
674
- this.requestRender();
747
+ // Keyboard input is latency-sensitive. Avoid the throttled timer path,
748
+ // where even setTimeout(0) can take a full 16 ms tick on Windows.
749
+ this.requestImmediateRender();
675
750
  }
676
751
  }
677
- consumeOsc11BackgroundResponse(data) {
678
- if (this.pendingOsc11BackgroundReplies <= 0) {
752
+ consumeTerminalColorResponse(data) {
753
+ const query = this.pendingTerminalColorQueries[0];
754
+ if (!query) {
679
755
  return false;
680
756
  }
681
- if (!isOsc11BackgroundColorResponse(data)) {
757
+ if (DEVICE_ATTRIBUTES_RESPONSE_PATTERN.test(data)) {
758
+ this.pendingTerminalColorQueries.shift();
759
+ this.completeTerminalColorQuery(query);
760
+ return true;
761
+ }
762
+ const response = parseOscColorResponse(data);
763
+ if (!response) {
682
764
  return false;
683
765
  }
684
- const rgb = parseOsc11BackgroundColor(data);
685
- this.pendingOsc11BackgroundReplies -= 1;
686
- const query = this.pendingOsc11BackgroundQueries.shift();
687
- if (query && !query.settled) {
688
- query.settled = true;
689
- if (query.timer) {
690
- clearTimeout(query.timer);
691
- query.timer = undefined;
692
- }
693
- query.resolve?.(rgb);
694
- query.resolve = undefined;
766
+ const { target, rgb } = response;
767
+ const key = String(target);
768
+ if (!query.deliver || query.replied.has(key)) {
769
+ return true;
770
+ }
771
+ query.replied.add(key);
772
+ if (target === "foreground") {
773
+ query.foreground = rgb;
774
+ }
775
+ else if (target === "background") {
776
+ query.background = rgb;
777
+ }
778
+ else if (target < TERMINAL_PALETTE_SIZE) {
779
+ query.palette[target] = rgb;
780
+ }
781
+ if (query.replied.size === TERMINAL_COLOR_REPLY_COUNT) {
782
+ this.completeTerminalColorQuery(query);
695
783
  }
696
784
  return true;
697
785
  }
786
+ terminalColorQueryResult(query) {
787
+ const palette = query.palette.every((color) => color !== undefined) ? query.palette : undefined;
788
+ return { foreground: query.foreground, background: query.background, palette };
789
+ }
790
+ completeTerminalColorQuery(query) {
791
+ const deliver = query.deliver;
792
+ query.deliver = undefined;
793
+ clearTimeout(query.timer);
794
+ deliver?.(this.terminalColorQueryResult(query));
795
+ }
698
796
  consumeTerminalColorSchemeReport(data) {
699
797
  const scheme = parseTerminalColorSchemeReport(data);
700
798
  if (!scheme) {
@@ -850,9 +948,13 @@ export class TUI extends Container {
850
948
  }
851
949
  /** Composite all overlays into content lines (sorted by focusOrder, higher = on top). */
852
950
  compositeOverlays(lines, termWidth, termHeight) {
853
- if (this.overlayStack.length === 0)
951
+ if (this.overlayStack.length === 0) {
952
+ this.renderedOverlayLayouts = [];
854
953
  return lines;
954
+ }
855
955
  const result = [...lines];
956
+ for (const entry of this.overlayStack)
957
+ entry.bounds = undefined;
856
958
  // Pre-render all visible overlays and calculate positions
857
959
  const rendered = [];
858
960
  let minLinesNeeded = result.length;
@@ -871,9 +973,17 @@ export class TUI extends Container {
871
973
  }
872
974
  // Get final row/col with actual overlay height
873
975
  const { row, col } = this.resolveOverlayLayout(options, overlayLines.length, termWidth, termHeight);
874
- rendered.push({ overlayLines, row, col, w: width });
976
+ entry.bounds = { row, col, width, height: overlayLines.length };
977
+ rendered.push({ entry, overlayLines, row, col, w: width });
875
978
  minLinesNeeded = Math.max(minLinesNeeded, row + overlayLines.length);
876
979
  }
980
+ this.renderedOverlayLayouts = rendered.map(({ entry, row, col, w, overlayLines }) => ({
981
+ entry,
982
+ row,
983
+ col,
984
+ width: w,
985
+ height: overlayLines.length,
986
+ }));
877
987
  // Pad to at least terminal height so overlays have screen-relative positions.
878
988
  // Excludes maxLinesRendered: the historical high-water mark caused self-reinforcing
879
989
  // inflation that pushed content into scrollback on terminal widen.
@@ -897,9 +1007,8 @@ export class TUI extends Container {
897
1007
  }
898
1008
  return result;
899
1009
  }
900
- static { this.SEGMENT_RESET = "\x1b[0m\x1b]8;;\x07"; }
901
1010
  applyLineResets(lines) {
902
- const reset = TUI.SEGMENT_RESET;
1011
+ const reset = SEGMENT_RESET;
903
1012
  for (let i = 0; i < lines.length; i++) {
904
1013
  const line = lines[i];
905
1014
  if (!isImageLine(line)) {
@@ -908,104 +1017,8 @@ export class TUI extends Container {
908
1017
  }
909
1018
  return lines;
910
1019
  }
911
- collectKittyImageIds(lines) {
912
- const ids = new Set();
913
- for (const line of lines) {
914
- for (const id of extractKittyImageIds(line)) {
915
- ids.add(id);
916
- }
917
- }
918
- return ids;
919
- }
920
- deleteKittyImages(ids) {
921
- let buffer = "";
922
- for (const id of ids) {
923
- buffer += deleteKittyImage(id);
924
- }
925
- return buffer;
926
- }
927
- getKittyImageReservedRows(lines, index, maxIndex = lines.length - 1) {
928
- const rows = extractKittyImageRows(lines[index] ?? "");
929
- if (rows <= 1)
930
- return 1;
931
- const maxRows = Math.min(rows, maxIndex - index + 1, lines.length - index);
932
- let reservedRows = 1;
933
- while (reservedRows < maxRows) {
934
- const line = lines[index + reservedRows] ?? "";
935
- if (isImageLine(line) || visibleWidth(line) > 0)
936
- break;
937
- reservedRows++;
938
- }
939
- return reservedRows;
940
- }
941
- expandChangedRangeForKittyImages(firstChanged, lastChanged, newLines) {
942
- let expandedFirstChanged = firstChanged;
943
- let expandedLastChanged = lastChanged;
944
- const expandForLines = (lines) => {
945
- for (let i = 0; i < lines.length; i++) {
946
- if (extractKittyImageIds(lines[i]).length === 0)
947
- continue;
948
- const blockEnd = i + this.getKittyImageReservedRows(lines, i) - 1;
949
- if (i >= firstChanged || (i <= lastChanged && blockEnd >= firstChanged)) {
950
- expandedFirstChanged = Math.min(expandedFirstChanged, i);
951
- expandedLastChanged = Math.max(expandedLastChanged, blockEnd);
952
- }
953
- }
954
- };
955
- expandForLines(this.previousLines);
956
- expandForLines(newLines);
957
- return { firstChanged: expandedFirstChanged, lastChanged: expandedLastChanged };
958
- }
959
- deleteChangedKittyImages(firstChanged, lastChanged) {
960
- if (firstChanged < 0 || lastChanged < firstChanged)
961
- return "";
962
- const ids = new Set();
963
- const maxLine = Math.min(lastChanged, this.previousLines.length - 1);
964
- for (let i = firstChanged; i <= maxLine; i++) {
965
- for (const id of extractKittyImageIds(this.previousLines[i] ?? "")) {
966
- ids.add(id);
967
- }
968
- }
969
- return this.deleteKittyImages(ids);
970
- }
971
- /** Splice overlay content into a base line at a specific column. Single-pass optimized. */
972
1020
  compositeLineAt(baseLine, overlayLine, startCol, overlayWidth, totalWidth) {
973
- if (isImageLine(baseLine))
974
- return baseLine;
975
- // Single pass through baseLine extracts both before and after segments
976
- const afterStart = startCol + overlayWidth;
977
- const base = extractSegments(baseLine, startCol, afterStart, totalWidth - afterStart, true);
978
- // Extract overlay with width tracking (strict=true to exclude wide chars at boundary)
979
- const overlay = sliceWithWidth(overlayLine, 0, overlayWidth, true);
980
- // Pad segments to target widths
981
- const beforePad = Math.max(0, startCol - base.beforeWidth);
982
- const overlayPad = Math.max(0, overlayWidth - overlay.width);
983
- const actualBeforeWidth = Math.max(startCol, base.beforeWidth);
984
- const actualOverlayWidth = Math.max(overlayWidth, overlay.width);
985
- const afterTarget = Math.max(0, totalWidth - actualBeforeWidth - actualOverlayWidth);
986
- const afterPad = Math.max(0, afterTarget - base.afterWidth);
987
- // Compose result
988
- const r = TUI.SEGMENT_RESET;
989
- const result = base.before +
990
- " ".repeat(beforePad) +
991
- r +
992
- overlay.text +
993
- " ".repeat(overlayPad) +
994
- r +
995
- base.after +
996
- " ".repeat(afterPad);
997
- // CRITICAL: Always verify and truncate to terminal width.
998
- // This is the final safeguard against width overflow which would crash the TUI.
999
- // Width tracking can drift from actual visible width due to:
1000
- // - Complex ANSI/OSC sequences (hyperlinks, colors)
1001
- // - Wide characters at segment boundaries
1002
- // - Edge cases in segment extraction
1003
- const resultWidth = visibleWidth(result);
1004
- if (resultWidth <= totalWidth) {
1005
- return result;
1006
- }
1007
- // Truncate with strict=true to ensure we don't exceed totalWidth
1008
- return sliceByColumn(result, 0, totalWidth, true);
1021
+ return compositeTuiLine(baseLine, overlayLine, startCol, overlayWidth, totalWidth);
1009
1022
  }
1010
1023
  /**
1011
1024
  * Find and extract cursor position from rendered lines.
@@ -1032,437 +1045,29 @@ export class TUI extends Container {
1032
1045
  }
1033
1046
  return null;
1034
1047
  }
1035
- doRender() {
1036
- if (this.stopped)
1037
- return;
1038
- const width = this.terminal.columns;
1039
- const height = this.terminal.rows;
1040
- const widthChanged = this.previousWidth !== 0 && this.previousWidth !== width;
1041
- const heightChanged = this.previousHeight !== 0 && this.previousHeight !== height;
1042
- const previousBufferLength = this.previousHeight > 0 ? this.previousViewportTop + this.previousHeight : height;
1043
- let prevViewportTop = heightChanged ? Math.max(0, previousBufferLength - height) : this.previousViewportTop;
1044
- let viewportTop = prevViewportTop;
1045
- let hardwareCursorRow = this.hardwareCursorRow;
1046
- const computeLineDiff = (targetRow) => {
1047
- const currentScreenRow = hardwareCursorRow - prevViewportTop;
1048
- const targetScreenRow = targetRow - viewportTop;
1049
- return targetScreenRow - currentScreenRow;
1050
- };
1051
- // Render all components to get new lines
1052
- let newLines = this.render(width);
1053
- // Composite overlays into the rendered lines (before differential compare)
1054
- if (this.overlayStack.length > 0) {
1055
- newLines = this.compositeOverlays(newLines, width, height);
1056
- }
1057
- // Extract cursor position before applying line resets (marker must be found first)
1058
- const cursorPos = this.extractCursorPosition(newLines, height);
1059
- newLines = this.applyLineResets(newLines);
1060
- // Helper to clear scrollback and viewport and render all new lines
1061
- const fullRender = (clear) => {
1062
- this.fullRedrawCount += 1;
1063
- const output = new BoundedTerminalWriter((data) => this.terminal.write(data));
1064
- output.append("\x1b[?2026h"); // Begin synchronized output
1065
- if (clear) {
1066
- output.append(this.deleteKittyImages(this.previousKittyImageIds));
1067
- output.append("\x1b[2J\x1b[H\x1b[3J"); // Clear screen, home, then clear scrollback
1068
- }
1069
- for (let i = 0; i < newLines.length; i++) {
1070
- if (i > 0)
1071
- output.append("\r\n");
1072
- const line = newLines[i];
1073
- const isImage = isImageLine(line);
1074
- const imageReservedRows = isImage ? this.getKittyImageReservedRows(newLines, i) : 1;
1075
- if (imageReservedRows > 1 && imageReservedRows <= height) {
1076
- for (let row = 1; row < imageReservedRows; row++) {
1077
- output.append("\r\n");
1078
- }
1079
- output.append(`\x1b[${imageReservedRows - 1}A`);
1080
- output.append(line);
1081
- output.append(`\x1b[${imageReservedRows - 1}B`);
1082
- i += imageReservedRows - 1;
1083
- continue;
1084
- }
1085
- output.append(line);
1086
- }
1087
- output.append("\x1b[?2026l"); // End synchronized output
1088
- output.flush();
1089
- this.cursorRow = Math.max(0, newLines.length - 1);
1090
- this.hardwareCursorRow = this.cursorRow;
1091
- // Reset max lines when clearing, otherwise track growth
1092
- if (clear) {
1093
- this.maxLinesRendered = newLines.length;
1094
- }
1095
- else {
1096
- this.maxLinesRendered = Math.max(this.maxLinesRendered, newLines.length);
1097
- }
1098
- const bufferLength = Math.max(height, newLines.length);
1099
- this.previousViewportTop = Math.max(0, bufferLength - height);
1100
- this.positionHardwareCursor(cursorPos, newLines.length);
1101
- this.previousLines = newLines;
1102
- this.previousKittyImageIds = this.collectKittyImageIds(newLines);
1103
- this.previousWidth = width;
1104
- this.previousHeight = height;
1105
- };
1106
- const debugRedraw = process.env.PI_DEBUG_REDRAW === "1";
1107
- const logRedraw = (reason) => {
1108
- if (!debugRedraw)
1109
- return;
1110
- const logPath = path.join(this.logDirectory, "pi-debug.log");
1111
- const msg = `[${new Date().toISOString()}] fullRender: ${reason} (prev=${this.previousLines.length}, new=${newLines.length}, height=${height})\n`;
1112
- fs.mkdirSync(path.dirname(logPath), { recursive: true });
1113
- fs.appendFileSync(logPath, msg);
1114
- };
1115
- // First render - just output everything without clearing (assumes clean screen)
1116
- if (this.previousLines.length === 0 && !widthChanged && !heightChanged) {
1117
- logRedraw("first render");
1118
- fullRender(false);
1119
- return;
1120
- }
1121
- // Width changes always need a full re-render because wrapping changes.
1122
- if (widthChanged) {
1123
- logRedraw(`terminal width changed (${this.previousWidth} -> ${width})`);
1124
- fullRender(true);
1125
- return;
1126
- }
1127
- // Height changes normally need a full re-render to keep the visible viewport aligned,
1128
- // but Termux changes height when the software keyboard shows or hides.
1129
- // In that environment, a full redraw causes the entire history to replay on every toggle.
1130
- if (heightChanged && !isTermuxSession()) {
1131
- logRedraw(`terminal height changed (${this.previousHeight} -> ${height})`);
1132
- fullRender(true);
1133
- return;
1134
- }
1135
- // Content shrunk below the working area and no overlays - re-render to clear empty rows
1136
- // (overlays need the padding, so only do this when no overlays are active)
1137
- // Configurable via setClearOnShrink() or PI_CLEAR_ON_SHRINK=0 env var
1138
- if (this.clearOnShrink && newLines.length < this.maxLinesRendered && this.overlayStack.length === 0) {
1139
- logRedraw(`clearOnShrink (maxLinesRendered=${this.maxLinesRendered})`);
1140
- fullRender(true);
1141
- return;
1142
- }
1143
- // Find first and last changed lines
1144
- let firstChanged = -1;
1145
- let lastChanged = -1;
1146
- const maxLines = Math.max(newLines.length, this.previousLines.length);
1147
- for (let i = 0; i < maxLines; i++) {
1148
- const oldLine = i < this.previousLines.length ? this.previousLines[i] : "";
1149
- const newLine = i < newLines.length ? newLines[i] : "";
1150
- if (oldLine !== newLine) {
1151
- if (firstChanged === -1) {
1152
- firstChanged = i;
1153
- }
1154
- lastChanged = i;
1155
- }
1156
- }
1157
- const appendedLines = newLines.length > this.previousLines.length;
1158
- if (appendedLines) {
1159
- if (firstChanged === -1) {
1160
- firstChanged = this.previousLines.length;
1161
- }
1162
- lastChanged = newLines.length - 1;
1163
- }
1164
- if (firstChanged !== -1) {
1165
- const expandedRange = this.expandChangedRangeForKittyImages(firstChanged, lastChanged, newLines);
1166
- firstChanged = expandedRange.firstChanged;
1167
- lastChanged = expandedRange.lastChanged;
1168
- }
1169
- const appendStart = appendedLines && firstChanged === this.previousLines.length && firstChanged > 0;
1170
- // No changes - but still need to update hardware cursor position if it moved
1171
- if (firstChanged === -1) {
1172
- this.positionHardwareCursor(cursorPos, newLines.length);
1173
- this.previousViewportTop = prevViewportTop;
1174
- this.previousHeight = height;
1175
- return;
1176
- }
1177
- // All changes are in deleted lines (nothing to render, just clear)
1178
- if (firstChanged >= newLines.length) {
1179
- if (this.previousLines.length > newLines.length) {
1180
- const output = new BoundedTerminalWriter((data) => this.terminal.write(data));
1181
- output.append("\x1b[?2026h");
1182
- output.append(this.deleteChangedKittyImages(firstChanged, lastChanged));
1183
- // Move to end of new content (clamp to 0 for empty content)
1184
- const targetRow = Math.max(0, newLines.length - 1);
1185
- if (targetRow < prevViewportTop) {
1186
- logRedraw(`deleted lines moved viewport up (${targetRow} < ${prevViewportTop})`);
1187
- fullRender(true);
1188
- return;
1189
- }
1190
- const lineDiff = computeLineDiff(targetRow);
1191
- if (lineDiff > 0)
1192
- output.append(`\x1b[${lineDiff}B`);
1193
- else if (lineDiff < 0)
1194
- output.append(`\x1b[${-lineDiff}A`);
1195
- output.append("\r");
1196
- // Clear extra lines without scrolling
1197
- const extraLines = this.previousLines.length - newLines.length;
1198
- if (extraLines > height) {
1199
- logRedraw(`extraLines > height (${extraLines} > ${height})`);
1200
- fullRender(true);
1201
- return;
1202
- }
1203
- const clearStartOffset = newLines.length === 0 ? 0 : 1;
1204
- if (extraLines > 0 && clearStartOffset > 0) {
1205
- output.append(`\x1b[${clearStartOffset}B`);
1206
- }
1207
- for (let i = 0; i < extraLines; i++) {
1208
- output.append("\r\x1b[2K");
1209
- if (i < extraLines - 1)
1210
- output.append("\x1b[1B");
1211
- }
1212
- const moveBack = Math.max(0, extraLines - 1 + clearStartOffset);
1213
- if (moveBack > 0) {
1214
- output.append(`\x1b[${moveBack}A`);
1215
- }
1216
- output.append("\x1b[?2026l");
1217
- output.flush();
1218
- this.cursorRow = targetRow;
1219
- this.hardwareCursorRow = targetRow;
1220
- }
1221
- this.positionHardwareCursor(cursorPos, newLines.length);
1222
- this.previousLines = newLines;
1223
- this.previousKittyImageIds = this.collectKittyImageIds(newLines);
1224
- this.previousWidth = width;
1225
- this.previousHeight = height;
1226
- this.previousViewportTop = prevViewportTop;
1227
- return;
1228
- }
1229
- // Differential rendering can only touch what was actually visible.
1230
- // If the first changed line is above the previous viewport, we need a full redraw.
1231
- if (firstChanged < prevViewportTop) {
1232
- logRedraw(`firstChanged < viewportTop (${firstChanged} < ${prevViewportTop})`);
1233
- fullRender(true);
1234
- return;
1235
- }
1236
- // Render from first changed line to end
1237
- // Keep updates wrapped in synchronized output while writing bounded chunks.
1238
- const output = new BoundedTerminalWriter((data) => this.terminal.write(data));
1239
- output.append("\x1b[?2026h"); // Begin synchronized output
1240
- output.append(this.deleteChangedKittyImages(firstChanged, lastChanged));
1241
- const prevViewportBottom = prevViewportTop + height - 1;
1242
- const moveTargetRow = appendStart ? firstChanged - 1 : firstChanged;
1243
- if (moveTargetRow > prevViewportBottom) {
1244
- const currentScreenRow = Math.max(0, Math.min(height - 1, hardwareCursorRow - prevViewportTop));
1245
- const moveToBottom = height - 1 - currentScreenRow;
1246
- if (moveToBottom > 0) {
1247
- output.append(`\x1b[${moveToBottom}B`);
1248
- }
1249
- const scroll = moveTargetRow - prevViewportBottom;
1250
- output.append("\r\n".repeat(scroll));
1251
- prevViewportTop += scroll;
1252
- viewportTop += scroll;
1253
- hardwareCursorRow = moveTargetRow;
1254
- }
1255
- // Move cursor to first changed line (use hardwareCursorRow for actual position)
1256
- const lineDiff = computeLineDiff(moveTargetRow);
1257
- if (lineDiff > 0) {
1258
- output.append(`\x1b[${lineDiff}B`); // Move down
1259
- }
1260
- else if (lineDiff < 0) {
1261
- output.append(`\x1b[${-lineDiff}A`); // Move up
1262
- }
1263
- output.append(appendStart ? "\r\n" : "\r"); // Move to column 0
1264
- // Only render changed lines (firstChanged to lastChanged), not all lines to end
1265
- // This reduces flicker when only a single line changes (e.g., spinner animation)
1266
- const renderEnd = Math.min(lastChanged, newLines.length - 1);
1267
- for (let i = firstChanged; i <= renderEnd; i++) {
1268
- if (i > firstChanged)
1269
- output.append("\r\n");
1270
- const line = newLines[i];
1271
- const isImage = isImageLine(line);
1272
- const imageReservedRows = isImage ? this.getKittyImageReservedRows(newLines, i, renderEnd) : 1;
1273
- if (imageReservedRows > 1) {
1274
- const imageStartScreenRow = i - viewportTop;
1275
- if (imageStartScreenRow < 0 || imageStartScreenRow + imageReservedRows > height) {
1276
- logRedraw(`kitty image pre-clear would scroll (${imageStartScreenRow} + ${imageReservedRows} > ${height})`);
1277
- fullRender(true);
1278
- return;
1279
- }
1280
- output.append("\x1b[2K");
1281
- for (let row = 1; row < imageReservedRows; row++) {
1282
- output.append("\r\n\x1b[2K");
1283
- }
1284
- output.append(`\x1b[${imageReservedRows - 1}A`);
1285
- output.append(line);
1286
- output.append(`\x1b[${imageReservedRows - 1}B`);
1287
- i += imageReservedRows - 1;
1288
- continue;
1289
- }
1290
- output.append("\x1b[2K"); // Clear current line
1291
- if (!isImage && visibleWidth(line) > width) {
1292
- // Log all lines to crash file for debugging
1293
- const crashLogPath = path.join(this.logDirectory, "pi-crash.log");
1294
- const crashData = [
1295
- `Crash at ${new Date().toISOString()}`,
1296
- `Terminal width: ${width}`,
1297
- `Line ${i} visible width: ${visibleWidth(line)}`,
1298
- "",
1299
- "=== All rendered lines ===",
1300
- ...newLines.map((l, idx) => `[${idx}] (w=${visibleWidth(l)}) ${l}`),
1301
- "",
1302
- ].join("\n");
1303
- fs.mkdirSync(path.dirname(crashLogPath), { recursive: true });
1304
- fs.writeFileSync(crashLogPath, crashData);
1305
- // Clean up terminal state before throwing
1306
- this.stop();
1307
- const errorMsg = [
1308
- `Rendered line ${i} exceeds terminal width (${visibleWidth(line)} > ${width}).`,
1309
- "",
1310
- "This is likely caused by a custom TUI component not truncating its output.",
1311
- "Use visibleWidth() to measure and truncateToWidth() to truncate lines.",
1312
- "",
1313
- `Debug log written to: ${crashLogPath}`,
1314
- ].join("\n");
1315
- throw new Error(errorMsg);
1316
- }
1317
- output.append(line);
1318
- }
1319
- // Track where cursor ended up after rendering
1320
- let finalCursorRow = renderEnd;
1321
- // If we had more lines before, clear them and move cursor back
1322
- if (this.previousLines.length > newLines.length) {
1323
- // Move to end of new content first if we stopped before it
1324
- if (renderEnd < newLines.length - 1) {
1325
- const moveDown = newLines.length - 1 - renderEnd;
1326
- output.append(`\x1b[${moveDown}B`);
1327
- finalCursorRow = newLines.length - 1;
1328
- }
1329
- const extraLines = this.previousLines.length - newLines.length;
1330
- for (let i = newLines.length; i < this.previousLines.length; i++) {
1331
- output.append("\r\n\x1b[2K");
1332
- }
1333
- // Move cursor back to end of new content
1334
- output.append(`\x1b[${extraLines}A`);
1335
- }
1336
- output.append("\x1b[?2026l"); // End synchronized output
1337
- if (process.env.PI_TUI_DEBUG === "1") {
1338
- const debugDir = "/tmp/tui";
1339
- fs.mkdirSync(debugDir, { recursive: true });
1340
- const debugPath = path.join(debugDir, `render-${Date.now()}-${Math.random().toString(36).slice(2)}.log`);
1341
- const debugData = [
1342
- `firstChanged: ${firstChanged}`,
1343
- `viewportTop: ${viewportTop}`,
1344
- `cursorRow: ${this.cursorRow}`,
1345
- `height: ${height}`,
1346
- `lineDiff: ${lineDiff}`,
1347
- `hardwareCursorRow: ${hardwareCursorRow}`,
1348
- `renderEnd: ${renderEnd}`,
1349
- `finalCursorRow: ${finalCursorRow}`,
1350
- `cursorPos: ${JSON.stringify(cursorPos)}`,
1351
- `newLines.length: ${newLines.length}`,
1352
- `previousLines.length: ${this.previousLines.length}`,
1353
- "",
1354
- "=== newLines ===",
1355
- JSON.stringify(newLines, null, 2),
1356
- "",
1357
- "=== previousLines ===",
1358
- JSON.stringify(this.previousLines, null, 2),
1359
- "",
1360
- "=== buffer ===",
1361
- `[${output.length} chars written in bounded chunks]`,
1362
- ].join("\n");
1363
- fs.writeFileSync(debugPath, debugData);
1364
- }
1365
- output.flush();
1366
- // Track cursor position for next render
1367
- // cursorRow tracks end of content (for viewport calculation)
1368
- // hardwareCursorRow tracks actual terminal cursor position (for movement)
1369
- this.cursorRow = Math.max(0, newLines.length - 1);
1370
- this.hardwareCursorRow = finalCursorRow;
1371
- // Track terminal's working area (grows but doesn't shrink unless cleared)
1372
- this.maxLinesRendered = Math.max(this.maxLinesRendered, newLines.length);
1373
- this.previousViewportTop = Math.max(prevViewportTop, finalCursorRow - height + 1);
1374
- // Position hardware cursor for IME
1375
- this.positionHardwareCursor(cursorPos, newLines.length);
1376
- this.previousLines = newLines;
1377
- this.previousKittyImageIds = this.collectKittyImageIds(newLines);
1378
- this.previousWidth = width;
1379
- this.previousHeight = height;
1380
- }
1381
1048
  /**
1382
- * Position the hardware cursor for IME candidate window.
1383
- * @param cursorPos The cursor position extracted from rendered output, or null
1384
- * @param totalLines Total number of rendered lines
1049
+ * Query the terminal's theme colors: the default foreground (OSC 10), the default background
1050
+ * (OSC 11), and ANSI colors 0-15 (OSC 4), followed by a DA1 request that marks the end of the
1051
+ * replies. Resolves when the DA1 reply or all color replies arrive, or when the timeout expires.
1052
+ * Colors the terminal did not report are undefined; the palette is only set when all 16 arrived.
1053
+ * @param timeoutMs Query timeout in milliseconds, for terminals that do not answer DA1 either.
1054
+ * @param onLateReply Receives the replies if the query completes after the timeout, e.g. over slow links.
1385
1055
  */
1386
- positionHardwareCursor(cursorPos, totalLines) {
1387
- if (!cursorPos || totalLines <= 0) {
1388
- this.terminal.hideCursor();
1389
- return;
1390
- }
1391
- // Clamp cursor position to valid range
1392
- const targetRow = Math.max(0, Math.min(cursorPos.row, totalLines - 1));
1393
- const targetCol = Math.max(0, cursorPos.col);
1394
- // Move cursor from current position to target
1395
- const rowDelta = targetRow - this.hardwareCursorRow;
1396
- let buffer = "";
1397
- if (rowDelta > 0) {
1398
- buffer += `\x1b[${rowDelta}B`; // Move down
1399
- }
1400
- else if (rowDelta < 0) {
1401
- buffer += `\x1b[${-rowDelta}A`; // Move up
1402
- }
1403
- // Move to absolute column (1-indexed)
1404
- buffer += `\x1b[${targetCol + 1}G`;
1405
- if (buffer) {
1406
- this.terminal.write(buffer);
1407
- }
1408
- this.hardwareCursorRow = targetRow;
1409
- if (this.showHardwareCursor) {
1410
- this.terminal.showCursor();
1411
- }
1412
- else {
1413
- this.terminal.hideCursor();
1414
- }
1415
- }
1416
- /**
1417
- * Query the terminal's default background color with OSC 11 (`ESC ] 11 ; ? BEL`).
1418
- * @param timeoutMs Query timeout in milliseconds.
1419
- * @returns Promise containing the parsed RGB color, or undefined if it times out or fails to parse.
1420
- */
1421
- queryTerminalBackgroundColor({ timeoutMs }) {
1056
+ queryTerminalColors({ timeoutMs, onLateReply, }) {
1422
1057
  return new Promise((resolve) => {
1423
1058
  const query = {
1424
- settled: false,
1425
- resolve,
1059
+ palette: Array.from({ length: TERMINAL_PALETTE_SIZE }, () => undefined),
1060
+ replied: new Set(),
1061
+ deliver: resolve,
1426
1062
  timer: undefined,
1427
1063
  };
1064
+ // Resolve with the replies so far, and keep collecting late replies for `onLateReply`.
1428
1065
  query.timer = setTimeout(() => {
1429
- if (query.settled) {
1430
- return;
1431
- }
1432
- query.settled = true;
1433
- query.timer = undefined;
1434
- query.resolve?.(undefined);
1435
- query.resolve = undefined;
1066
+ query.deliver = onLateReply;
1067
+ resolve(this.terminalColorQueryResult(query));
1436
1068
  }, timeoutMs);
1437
- this.pendingOsc11BackgroundQueries.push(query);
1438
- this.pendingOsc11BackgroundReplies += 1;
1439
- this.terminal.write("\x1b]11;?\x07");
1440
- });
1441
- }
1442
- /**
1443
- * Query the terminal's color-scheme preference with DSR (`CSI ? 996 n`).
1444
- * Terminals that support the color palette notification protocol reply with
1445
- * `CSI ? 997 ; 1 n` for dark or `CSI ? 997 ; 2 n` for light.
1446
- */
1447
- queryTerminalColorScheme({ timeoutMs }) {
1448
- return new Promise((resolve) => {
1449
- let settled = false;
1450
- let timer;
1451
- let unsubscribe = () => { };
1452
- const settle = (scheme) => {
1453
- if (settled)
1454
- return;
1455
- settled = true;
1456
- if (timer) {
1457
- clearTimeout(timer);
1458
- timer = undefined;
1459
- }
1460
- unsubscribe();
1461
- resolve(scheme);
1462
- };
1463
- unsubscribe = this.onTerminalColorSchemeChange(settle);
1464
- timer = setTimeout(() => settle(undefined), timeoutMs);
1465
- this.terminal.write("\x1b[?996n");
1069
+ this.pendingTerminalColorQueries.push(query);
1070
+ this.terminal.write(TERMINAL_COLOR_QUERY);
1466
1071
  });
1467
1072
  }
1468
1073
  }