@chengchenccc/tui 0.1.1-rc.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (226) hide show
  1. package/dist/autocomplete.d.ts +56 -0
  2. package/dist/autocomplete.d.ts.map +1 -0
  3. package/dist/autocomplete.js +647 -0
  4. package/dist/components/box.d.ts +22 -0
  5. package/dist/components/box.d.ts.map +1 -0
  6. package/dist/components/box.js +103 -0
  7. package/dist/components/card.d.ts +33 -0
  8. package/dist/components/card.d.ts.map +1 -0
  9. package/dist/components/card.js +49 -0
  10. package/dist/components/editor.d.ts +257 -0
  11. package/dist/components/editor.d.ts.map +1 -0
  12. package/dist/components/editor.js +1980 -0
  13. package/dist/components/input.d.ts +37 -0
  14. package/dist/components/input.d.ts.map +1 -0
  15. package/dist/components/input.js +389 -0
  16. package/dist/components/loader.d.ts +33 -0
  17. package/dist/components/loader.d.ts.map +1 -0
  18. package/dist/components/loader.js +100 -0
  19. package/dist/components/markdown.d.ts +108 -0
  20. package/dist/components/markdown.d.ts.map +1 -0
  21. package/dist/components/markdown.js +847 -0
  22. package/dist/components/markdown.test.d.ts +2 -0
  23. package/dist/components/markdown.test.d.ts.map +1 -0
  24. package/dist/components/markdown.test.js +81 -0
  25. package/dist/components/output-block.d.ts +44 -0
  26. package/dist/components/output-block.d.ts.map +1 -0
  27. package/dist/components/output-block.js +131 -0
  28. package/dist/components/select-list.d.ts +50 -0
  29. package/dist/components/select-list.d.ts.map +1 -0
  30. package/dist/components/select-list.js +166 -0
  31. package/dist/components/spacer.d.ts +12 -0
  32. package/dist/components/spacer.d.ts.map +1 -0
  33. package/dist/components/spacer.js +22 -0
  34. package/dist/components/statusline.d.ts +30 -0
  35. package/dist/components/statusline.d.ts.map +1 -0
  36. package/dist/components/statusline.js +46 -0
  37. package/dist/components/text.d.ts +19 -0
  38. package/dist/components/text.d.ts.map +1 -0
  39. package/dist/components/text.js +90 -0
  40. package/dist/components/truncated-text.d.ts +13 -0
  41. package/dist/components/truncated-text.d.ts.map +1 -0
  42. package/dist/components/truncated-text.js +50 -0
  43. package/dist/editor-component.d.ts +39 -0
  44. package/dist/editor-component.d.ts.map +1 -0
  45. package/dist/editor-component.js +1 -0
  46. package/dist/fuzzy.d.ts +16 -0
  47. package/dist/fuzzy.d.ts.map +1 -0
  48. package/dist/fuzzy.js +109 -0
  49. package/dist/index.d.ts +25 -0
  50. package/dist/index.d.ts.map +1 -0
  51. package/dist/index.js +36 -0
  52. package/dist/keybindings.d.ts +193 -0
  53. package/dist/keybindings.d.ts.map +1 -0
  54. package/dist/keybindings.js +191 -0
  55. package/dist/keys.d.ts +184 -0
  56. package/dist/keys.d.ts.map +1 -0
  57. package/dist/keys.js +1191 -0
  58. package/dist/kill-ring.d.ts +28 -0
  59. package/dist/kill-ring.d.ts.map +1 -0
  60. package/dist/kill-ring.js +43 -0
  61. package/dist/mermaid.d.ts +23 -0
  62. package/dist/mermaid.d.ts.map +1 -0
  63. package/dist/mermaid.js +77 -0
  64. package/dist/mouse.d.ts +40 -0
  65. package/dist/mouse.d.ts.map +1 -0
  66. package/dist/mouse.js +39 -0
  67. package/dist/mouse.test.d.ts +2 -0
  68. package/dist/mouse.test.d.ts.map +1 -0
  69. package/dist/mouse.test.js +36 -0
  70. package/dist/native-modifiers.d.ts +3 -0
  71. package/dist/native-modifiers.d.ts.map +1 -0
  72. package/dist/native-modifiers.js +52 -0
  73. package/dist/stdin-buffer.d.ts +50 -0
  74. package/dist/stdin-buffer.d.ts.map +1 -0
  75. package/dist/stdin-buffer.js +360 -0
  76. package/dist/terminal-colors.d.ts +10 -0
  77. package/dist/terminal-colors.d.ts.map +1 -0
  78. package/dist/terminal-colors.js +58 -0
  79. package/dist/terminal-image.d.ts +90 -0
  80. package/dist/terminal-image.d.ts.map +1 -0
  81. package/dist/terminal-image.js +375 -0
  82. package/dist/terminal.d.ts +110 -0
  83. package/dist/terminal.d.ts.map +1 -0
  84. package/dist/terminal.js +432 -0
  85. package/dist/tui-scrollback.test.d.ts +2 -0
  86. package/dist/tui-scrollback.test.d.ts.map +1 -0
  87. package/dist/tui-scrollback.test.js +51 -0
  88. package/dist/tui.d.ts +330 -0
  89. package/dist/tui.d.ts.map +1 -0
  90. package/dist/tui.js +1568 -0
  91. package/dist/undo-stack.d.ts +17 -0
  92. package/dist/undo-stack.d.ts.map +1 -0
  93. package/dist/undo-stack.js +24 -0
  94. package/dist/utils.d.ts +85 -0
  95. package/dist/utils.d.ts.map +1 -0
  96. package/dist/utils.js +1066 -0
  97. package/dist/vendor/mermaid-ascii/ascii/ansi.d.ts +42 -0
  98. package/dist/vendor/mermaid-ascii/ascii/ansi.d.ts.map +1 -0
  99. package/dist/vendor/mermaid-ascii/ascii/ansi.js +361 -0
  100. package/dist/vendor/mermaid-ascii/ascii/canvas.d.ts +90 -0
  101. package/dist/vendor/mermaid-ascii/ascii/canvas.d.ts.map +1 -0
  102. package/dist/vendor/mermaid-ascii/ascii/canvas.js +414 -0
  103. package/dist/vendor/mermaid-ascii/ascii/class-diagram.d.ts +8 -0
  104. package/dist/vendor/mermaid-ascii/ascii/class-diagram.d.ts.map +1 -0
  105. package/dist/vendor/mermaid-ascii/ascii/class-diagram.js +623 -0
  106. package/dist/vendor/mermaid-ascii/ascii/converter.d.ts +13 -0
  107. package/dist/vendor/mermaid-ascii/ascii/converter.d.ts.map +1 -0
  108. package/dist/vendor/mermaid-ascii/ascii/converter.js +233 -0
  109. package/dist/vendor/mermaid-ascii/ascii/draw.d.ts +67 -0
  110. package/dist/vendor/mermaid-ascii/ascii/draw.d.ts.map +1 -0
  111. package/dist/vendor/mermaid-ascii/ascii/draw.js +1313 -0
  112. package/dist/vendor/mermaid-ascii/ascii/edge-bundling.d.ts +49 -0
  113. package/dist/vendor/mermaid-ascii/ascii/edge-bundling.d.ts.map +1 -0
  114. package/dist/vendor/mermaid-ascii/ascii/edge-bundling.js +289 -0
  115. package/dist/vendor/mermaid-ascii/ascii/edge-routing.d.ts +44 -0
  116. package/dist/vendor/mermaid-ascii/ascii/edge-routing.d.ts.map +1 -0
  117. package/dist/vendor/mermaid-ascii/ascii/edge-routing.js +302 -0
  118. package/dist/vendor/mermaid-ascii/ascii/er-diagram.d.ts +8 -0
  119. package/dist/vendor/mermaid-ascii/ascii/er-diagram.d.ts.map +1 -0
  120. package/dist/vendor/mermaid-ascii/ascii/er-diagram.js +380 -0
  121. package/dist/vendor/mermaid-ascii/ascii/grid.d.ts +57 -0
  122. package/dist/vendor/mermaid-ascii/ascii/grid.d.ts.map +1 -0
  123. package/dist/vendor/mermaid-ascii/ascii/grid.js +516 -0
  124. package/dist/vendor/mermaid-ascii/ascii/index.d.ts +66 -0
  125. package/dist/vendor/mermaid-ascii/ascii/index.d.ts.map +1 -0
  126. package/dist/vendor/mermaid-ascii/ascii/index.js +133 -0
  127. package/dist/vendor/mermaid-ascii/ascii/multiline-utils.d.ts +28 -0
  128. package/dist/vendor/mermaid-ascii/ascii/multiline-utils.d.ts.map +1 -0
  129. package/dist/vendor/mermaid-ascii/ascii/multiline-utils.js +60 -0
  130. package/dist/vendor/mermaid-ascii/ascii/pathfinder.d.ts +18 -0
  131. package/dist/vendor/mermaid-ascii/ascii/pathfinder.d.ts.map +1 -0
  132. package/dist/vendor/mermaid-ascii/ascii/pathfinder.js +224 -0
  133. package/dist/vendor/mermaid-ascii/ascii/sequence.d.ts +8 -0
  134. package/dist/vendor/mermaid-ascii/ascii/sequence.d.ts.map +1 -0
  135. package/dist/vendor/mermaid-ascii/ascii/sequence.js +416 -0
  136. package/dist/vendor/mermaid-ascii/ascii/shapes/circle.d.ts +12 -0
  137. package/dist/vendor/mermaid-ascii/ascii/shapes/circle.d.ts.map +1 -0
  138. package/dist/vendor/mermaid-ascii/ascii/shapes/circle.js +22 -0
  139. package/dist/vendor/mermaid-ascii/ascii/shapes/corners.d.ts +35 -0
  140. package/dist/vendor/mermaid-ascii/ascii/shapes/corners.d.ts.map +1 -0
  141. package/dist/vendor/mermaid-ascii/ascii/shapes/corners.js +91 -0
  142. package/dist/vendor/mermaid-ascii/ascii/shapes/diamond.d.ts +12 -0
  143. package/dist/vendor/mermaid-ascii/ascii/shapes/diamond.d.ts.map +1 -0
  144. package/dist/vendor/mermaid-ascii/ascii/shapes/diamond.js +22 -0
  145. package/dist/vendor/mermaid-ascii/ascii/shapes/hexagon.d.ts +12 -0
  146. package/dist/vendor/mermaid-ascii/ascii/shapes/hexagon.d.ts.map +1 -0
  147. package/dist/vendor/mermaid-ascii/ascii/shapes/hexagon.js +22 -0
  148. package/dist/vendor/mermaid-ascii/ascii/shapes/index.d.ts +27 -0
  149. package/dist/vendor/mermaid-ascii/ascii/shapes/index.d.ts.map +1 -0
  150. package/dist/vendor/mermaid-ascii/ascii/shapes/index.js +66 -0
  151. package/dist/vendor/mermaid-ascii/ascii/shapes/rectangle.d.ts +32 -0
  152. package/dist/vendor/mermaid-ascii/ascii/shapes/rectangle.d.ts.map +1 -0
  153. package/dist/vendor/mermaid-ascii/ascii/shapes/rectangle.js +149 -0
  154. package/dist/vendor/mermaid-ascii/ascii/shapes/rounded.d.ts +12 -0
  155. package/dist/vendor/mermaid-ascii/ascii/shapes/rounded.d.ts.map +1 -0
  156. package/dist/vendor/mermaid-ascii/ascii/shapes/rounded.js +22 -0
  157. package/dist/vendor/mermaid-ascii/ascii/shapes/special.d.ts +60 -0
  158. package/dist/vendor/mermaid-ascii/ascii/shapes/special.d.ts.map +1 -0
  159. package/dist/vendor/mermaid-ascii/ascii/shapes/special.js +253 -0
  160. package/dist/vendor/mermaid-ascii/ascii/shapes/stadium.d.ts +18 -0
  161. package/dist/vendor/mermaid-ascii/ascii/shapes/stadium.d.ts.map +1 -0
  162. package/dist/vendor/mermaid-ascii/ascii/shapes/stadium.js +103 -0
  163. package/dist/vendor/mermaid-ascii/ascii/shapes/state.d.ts +31 -0
  164. package/dist/vendor/mermaid-ascii/ascii/shapes/state.d.ts.map +1 -0
  165. package/dist/vendor/mermaid-ascii/ascii/shapes/state.js +167 -0
  166. package/dist/vendor/mermaid-ascii/ascii/shapes/types.d.ts +56 -0
  167. package/dist/vendor/mermaid-ascii/ascii/shapes/types.d.ts.map +1 -0
  168. package/dist/vendor/mermaid-ascii/ascii/shapes/types.js +4 -0
  169. package/dist/vendor/mermaid-ascii/ascii/types.d.ts +207 -0
  170. package/dist/vendor/mermaid-ascii/ascii/types.d.ts.map +1 -0
  171. package/dist/vendor/mermaid-ascii/ascii/types.js +39 -0
  172. package/dist/vendor/mermaid-ascii/ascii/validate.d.ts +52 -0
  173. package/dist/vendor/mermaid-ascii/ascii/validate.d.ts.map +1 -0
  174. package/dist/vendor/mermaid-ascii/ascii/validate.js +97 -0
  175. package/dist/vendor/mermaid-ascii/ascii/xychart.d.ts +3 -0
  176. package/dist/vendor/mermaid-ascii/ascii/xychart.d.ts.map +1 -0
  177. package/dist/vendor/mermaid-ascii/ascii/xychart.js +719 -0
  178. package/dist/vendor/mermaid-ascii/class/parser.d.ts +7 -0
  179. package/dist/vendor/mermaid-ascii/class/parser.d.ts.map +1 -0
  180. package/dist/vendor/mermaid-ascii/class/parser.js +265 -0
  181. package/dist/vendor/mermaid-ascii/class/types.d.ts +103 -0
  182. package/dist/vendor/mermaid-ascii/class/types.d.ts.map +1 -0
  183. package/dist/vendor/mermaid-ascii/class/types.js +7 -0
  184. package/dist/vendor/mermaid-ascii/er/parser.d.ts +7 -0
  185. package/dist/vendor/mermaid-ascii/er/parser.d.ts.map +1 -0
  186. package/dist/vendor/mermaid-ascii/er/parser.js +162 -0
  187. package/dist/vendor/mermaid-ascii/er/types.d.ts +77 -0
  188. package/dist/vendor/mermaid-ascii/er/types.d.ts.map +1 -0
  189. package/dist/vendor/mermaid-ascii/er/types.js +7 -0
  190. package/dist/vendor/mermaid-ascii/index.d.ts +2 -0
  191. package/dist/vendor/mermaid-ascii/index.d.ts.map +1 -0
  192. package/dist/vendor/mermaid-ascii/index.js +13 -0
  193. package/dist/vendor/mermaid-ascii/multiline-utils.d.ts +10 -0
  194. package/dist/vendor/mermaid-ascii/multiline-utils.d.ts.map +1 -0
  195. package/dist/vendor/mermaid-ascii/multiline-utils.js +29 -0
  196. package/dist/vendor/mermaid-ascii/parser.d.ts +8 -0
  197. package/dist/vendor/mermaid-ascii/parser.d.ts.map +1 -0
  198. package/dist/vendor/mermaid-ascii/parser.js +558 -0
  199. package/dist/vendor/mermaid-ascii/sequence/parser.d.ts +7 -0
  200. package/dist/vendor/mermaid-ascii/sequence/parser.d.ts.map +1 -0
  201. package/dist/vendor/mermaid-ascii/sequence/parser.js +182 -0
  202. package/dist/vendor/mermaid-ascii/sequence/types.d.ts +131 -0
  203. package/dist/vendor/mermaid-ascii/sequence/types.d.ts.map +1 -0
  204. package/dist/vendor/mermaid-ascii/sequence/types.js +7 -0
  205. package/dist/vendor/mermaid-ascii/text-metrics.d.ts +24 -0
  206. package/dist/vendor/mermaid-ascii/text-metrics.d.ts.map +1 -0
  207. package/dist/vendor/mermaid-ascii/text-metrics.js +69 -0
  208. package/dist/vendor/mermaid-ascii/types.d.ts +115 -0
  209. package/dist/vendor/mermaid-ascii/types.d.ts.map +1 -0
  210. package/dist/vendor/mermaid-ascii/types.js +4 -0
  211. package/dist/vendor/mermaid-ascii/xychart/colors.d.ts +26 -0
  212. package/dist/vendor/mermaid-ascii/xychart/colors.d.ts.map +1 -0
  213. package/dist/vendor/mermaid-ascii/xychart/colors.js +145 -0
  214. package/dist/vendor/mermaid-ascii/xychart/parser.d.ts +7 -0
  215. package/dist/vendor/mermaid-ascii/xychart/parser.d.ts.map +1 -0
  216. package/dist/vendor/mermaid-ascii/xychart/parser.js +105 -0
  217. package/dist/vendor/mermaid-ascii/xychart/types.d.ts +146 -0
  218. package/dist/vendor/mermaid-ascii/xychart/types.d.ts.map +1 -0
  219. package/dist/vendor/mermaid-ascii/xychart/types.js +8 -0
  220. package/dist/virtual-terminal.d.ts +80 -0
  221. package/dist/virtual-terminal.d.ts.map +1 -0
  222. package/dist/virtual-terminal.js +284 -0
  223. package/dist/word-navigation.d.ts +25 -0
  224. package/dist/word-navigation.d.ts.map +1 -0
  225. package/dist/word-navigation.js +97 -0
  226. package/package.json +38 -0
package/dist/tui.js ADDED
@@ -0,0 +1,1568 @@
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 { isOsc11BackgroundColorResponse, parseOsc11BackgroundColor, parseTerminalColorSchemeReport, } from "./terminal-colors.js";
10
+ import { deleteKittyImage, getCapabilities, isImageLine, setCellDimensions, } from "./terminal-image.js";
11
+ import { extractSegments, normalizeTerminalOutput, sliceByColumn, sliceWithWidth, visibleWidth, } from "./utils.js";
12
+ const KITTY_SEQUENCE_PREFIX = "\x1b_G";
13
+ function parseKittyImageHeader(line) {
14
+ const sequenceStart = line.indexOf(KITTY_SEQUENCE_PREFIX);
15
+ if (sequenceStart === -1)
16
+ return undefined;
17
+ const paramsStart = sequenceStart + KITTY_SEQUENCE_PREFIX.length;
18
+ const paramsEnd = line.indexOf(";", paramsStart);
19
+ if (paramsEnd === -1)
20
+ return undefined;
21
+ const ids = [];
22
+ let rows = 1;
23
+ const params = line.slice(paramsStart, paramsEnd);
24
+ for (const param of params.split(",")) {
25
+ const [key, value] = param.split("=", 2);
26
+ if (value === undefined)
27
+ continue;
28
+ const numberValue = Number(value);
29
+ if (!Number.isInteger(numberValue) || numberValue <= 0 || numberValue > 0xffffffff)
30
+ continue;
31
+ if (key === "i") {
32
+ ids.push(numberValue);
33
+ }
34
+ else if (key === "r") {
35
+ rows = numberValue;
36
+ }
37
+ }
38
+ return { ids, rows };
39
+ }
40
+ function extractKittyImageIds(line) {
41
+ return parseKittyImageHeader(line)?.ids ?? [];
42
+ }
43
+ function extractKittyImageRows(line) {
44
+ return parseKittyImageHeader(line)?.rows ?? 1;
45
+ }
46
+ /** Type guard to check if a component implements Focusable */
47
+ export function isFocusable(component) {
48
+ return component !== null && "focused" in component;
49
+ }
50
+ /**
51
+ * Cursor position marker - APC (Application Program Command) sequence.
52
+ * This is a zero-width escape sequence that terminals ignore.
53
+ * Components emit this at the cursor position when focused.
54
+ * TUI finds and strips this marker, then positions the hardware cursor there.
55
+ */
56
+ export const CURSOR_MARKER = "\x1b_pi:c\x07";
57
+ export { visibleWidth };
58
+ /** Parse a SizeValue into absolute value given a reference size */
59
+ function parseSizeValue(value, referenceSize) {
60
+ if (value === undefined)
61
+ return undefined;
62
+ if (typeof value === "number")
63
+ return value;
64
+ // Parse percentage string like "50%"
65
+ const match = value.match(/^(\d+(?:\.\d+)?)%$/);
66
+ if (match) {
67
+ return Math.floor((referenceSize * parseFloat(match[1])) / 100);
68
+ }
69
+ return undefined;
70
+ }
71
+ function isTermuxSession() {
72
+ return Boolean(process.env.TERMUX_VERSION);
73
+ }
74
+ /**
75
+ * Container - a component that contains other components
76
+ */
77
+ export class Container {
78
+ children = [];
79
+ addChild(component) {
80
+ this.children.push(component);
81
+ }
82
+ removeChild(component) {
83
+ const index = this.children.indexOf(component);
84
+ if (index !== -1) {
85
+ this.children.splice(index, 1);
86
+ }
87
+ }
88
+ clear() {
89
+ this.children = [];
90
+ }
91
+ invalidate() {
92
+ for (const child of this.children) {
93
+ child.invalidate?.();
94
+ }
95
+ }
96
+ render(width) {
97
+ const lines = [];
98
+ for (const child of this.children) {
99
+ const childLines = child.render(width);
100
+ for (const line of childLines) {
101
+ lines.push(line);
102
+ }
103
+ }
104
+ return lines;
105
+ }
106
+ }
107
+ export function setNativeScrollbackCommittedRows(component, rows) {
108
+ component.setNativeScrollbackCommittedRows?.(rows);
109
+ }
110
+ export function getNativeScrollbackLiveRegionStart(component) {
111
+ return component.getNativeScrollbackLiveRegionStart?.();
112
+ }
113
+ export function getRenderStablePrefixRows(component) {
114
+ return component.getRenderStablePrefixRows?.();
115
+ }
116
+ export function prepareNativeScrollbackReplay(component) {
117
+ component.prepareNativeScrollbackReplay?.();
118
+ }
119
+ /**
120
+ * TUI - Main class for managing terminal UI with differential rendering
121
+ */
122
+ export class TUI extends Container {
123
+ terminal;
124
+ previousLines = [];
125
+ previousKittyImageIds = new Set();
126
+ previousWidth = 0;
127
+ previousHeight = 0;
128
+ focusedComponent = null;
129
+ inputListeners = new Set();
130
+ /** Global callback for debug key (Shift+Ctrl+D). Called before input is forwarded to focused component. */
131
+ onDebug;
132
+ renderRequested = false;
133
+ renderTimer;
134
+ lastRenderAt = 0;
135
+ static MIN_RENDER_INTERVAL_MS = 16;
136
+ cursorRow = 0; // Logical cursor row (end of rendered content)
137
+ hardwareCursorRow = 0; // Actual terminal cursor row (may differ due to IME positioning)
138
+ showHardwareCursor = process.env.PI_HARDWARE_CURSOR === "1";
139
+ clearOnShrink = process.env.PI_CLEAR_ON_SHRINK === "1"; // Clear empty rows when content shrinks (default: off)
140
+ maxLinesRendered = 0; // Track terminal's working area (max lines ever rendered)
141
+ previousViewportTop = 0; // Track previous viewport top for resize-aware cursor moves
142
+ committedRows = 0; // Rows already handed to native scrollback (never repainted)
143
+ frameProvider;
144
+ providerViewportTop = 0;
145
+ providerWindow = [];
146
+ acceptedHistoryBatchId = 0;
147
+ providerForceRepaint = false;
148
+ fullRedrawCount = 0;
149
+ stopped = false;
150
+ pendingOsc11BackgroundReplies = 0;
151
+ pendingOsc11BackgroundQueries = [];
152
+ terminalColorSchemeListeners = new Set();
153
+ terminalColorSchemeNotificationsEnabled = false;
154
+ // Overlay stack for modal components rendered on top of base content
155
+ focusOrderCounter = 0;
156
+ overlayStack = [];
157
+ overlayFocusRestore = {
158
+ status: "inactive",
159
+ };
160
+ constructor(terminal, showHardwareCursor) {
161
+ super();
162
+ this.terminal = terminal;
163
+ if (showHardwareCursor !== undefined) {
164
+ this.showHardwareCursor = showHardwareCursor;
165
+ }
166
+ }
167
+ get fullRedraws() {
168
+ return this.fullRedrawCount;
169
+ }
170
+ getShowHardwareCursor() {
171
+ return this.showHardwareCursor;
172
+ }
173
+ setShowHardwareCursor(enabled) {
174
+ if (this.showHardwareCursor === enabled)
175
+ return;
176
+ this.showHardwareCursor = enabled;
177
+ if (!enabled) {
178
+ this.terminal.hideCursor();
179
+ }
180
+ this.requestRender();
181
+ }
182
+ getClearOnShrink() {
183
+ return this.clearOnShrink;
184
+ }
185
+ /**
186
+ * Set whether to trigger full re-render when content shrinks.
187
+ * When true (default), empty rows are cleared when content shrinks.
188
+ * When false, empty rows remain (reduces redraws on slower terminals).
189
+ */
190
+ setClearOnShrink(enabled) {
191
+ this.clearOnShrink = enabled;
192
+ }
193
+ /** Provide a frame provider (omp TerminalFrameProvider pipeline). */
194
+ setFrameProvider(provider) {
195
+ this.frameProvider = provider;
196
+ }
197
+ setFocus(component) {
198
+ this.setFocusInternal({ component, overlayFocusRestore: "clear" });
199
+ }
200
+ setFocusInternal({ component, overlayFocusRestore, }) {
201
+ const previousFocus = this.focusedComponent;
202
+ let nextFocus = component;
203
+ const previousFocusedOverlay = previousFocus
204
+ ? this.overlayStack.find((entry) => entry.component === previousFocus && this.isOverlayVisible(entry))
205
+ : undefined;
206
+ const nextFocusIsOverlay = nextFocus
207
+ ? this.overlayStack.some((entry) => entry.component === nextFocus)
208
+ : false;
209
+ const restoreState = this.getVisibleOverlayFocusRestore();
210
+ if (nextFocus && !nextFocusIsOverlay) {
211
+ if (restoreState.status === "blocked" && restoreState.blockedBy === previousFocus) {
212
+ if (restoreState.resume.status === "focus-target" ||
213
+ !this.isComponentMounted(restoreState.blockedBy)) {
214
+ nextFocus = this.resolveBlockedOverlayFocusResume(restoreState);
215
+ }
216
+ else {
217
+ this.overlayFocusRestore = {
218
+ status: "blocked",
219
+ overlay: restoreState.overlay,
220
+ blockedBy: nextFocus,
221
+ resume: restoreState.resume,
222
+ };
223
+ }
224
+ }
225
+ else if (previousFocusedOverlay &&
226
+ restoreState.status !== "inactive" &&
227
+ restoreState.overlay === previousFocusedOverlay &&
228
+ !this.isOverlayFocusAncestor(previousFocusedOverlay, nextFocus)) {
229
+ this.overlayFocusRestore = {
230
+ status: "blocked",
231
+ overlay: previousFocusedOverlay,
232
+ blockedBy: nextFocus,
233
+ resume: { status: "restore-overlay" },
234
+ };
235
+ }
236
+ }
237
+ else if (nextFocus === null) {
238
+ if (restoreState.status === "blocked" && restoreState.blockedBy === previousFocus) {
239
+ nextFocus = this.resolveBlockedOverlayFocusResume(restoreState);
240
+ }
241
+ else if (overlayFocusRestore === "clear") {
242
+ this.clearOverlayFocusRestore();
243
+ }
244
+ }
245
+ if (isFocusable(this.focusedComponent)) {
246
+ this.focusedComponent.focused = false;
247
+ }
248
+ this.focusedComponent = nextFocus;
249
+ if (isFocusable(nextFocus)) {
250
+ nextFocus.focused = true;
251
+ }
252
+ const focusedOverlay = nextFocus
253
+ ? this.overlayStack.find((entry) => entry.component === nextFocus && this.isOverlayVisible(entry))
254
+ : undefined;
255
+ if (focusedOverlay) {
256
+ this.overlayFocusRestore = {
257
+ status: "eligible",
258
+ overlay: focusedOverlay,
259
+ };
260
+ }
261
+ }
262
+ clearOverlayFocusRestore() {
263
+ this.overlayFocusRestore = { status: "inactive" };
264
+ }
265
+ clearOverlayFocusRestoreFor(overlay) {
266
+ if (this.overlayFocusRestore.status !== "inactive" &&
267
+ this.overlayFocusRestore.overlay === overlay) {
268
+ this.clearOverlayFocusRestore();
269
+ }
270
+ }
271
+ resolveBlockedOverlayFocusResume(restoreState) {
272
+ if (restoreState.resume.status === "restore-overlay")
273
+ return restoreState.overlay.component;
274
+ this.clearOverlayFocusRestore();
275
+ return restoreState.resume.target;
276
+ }
277
+ getVisibleOverlayFocusRestore() {
278
+ const restoreState = this.overlayFocusRestore;
279
+ if (restoreState.status === "inactive")
280
+ return restoreState;
281
+ if (!this.overlayStack.includes(restoreState.overlay) ||
282
+ !this.isOverlayVisible(restoreState.overlay)) {
283
+ return { status: "inactive" };
284
+ }
285
+ return restoreState;
286
+ }
287
+ isOverlayFocusAncestor(entry, component) {
288
+ const visited = new Set();
289
+ let current = entry.preFocus;
290
+ while (current && !visited.has(current)) {
291
+ visited.add(current);
292
+ if (current === component)
293
+ return true;
294
+ current =
295
+ this.overlayStack.find((overlay) => overlay.component === current)?.preFocus ?? null;
296
+ }
297
+ return false;
298
+ }
299
+ retargetOverlayPreFocus(removed) {
300
+ for (const overlay of this.overlayStack) {
301
+ if (overlay !== removed && overlay.preFocus === removed.component) {
302
+ overlay.preFocus = removed.preFocus;
303
+ }
304
+ }
305
+ }
306
+ isComponentMounted(component) {
307
+ return this.children.some((child) => this.containsComponent(child, component));
308
+ }
309
+ containsComponent(root, target) {
310
+ if (root === target)
311
+ return true;
312
+ if (!(root instanceof Container))
313
+ return false;
314
+ return root.children.some((child) => this.containsComponent(child, target));
315
+ }
316
+ /**
317
+ * Show an overlay component with configurable positioning and sizing.
318
+ * Returns a handle to control the overlay's visibility.
319
+ */
320
+ showOverlay(component, options) {
321
+ const entry = {
322
+ component,
323
+ ...(options === undefined ? {} : { options }),
324
+ preFocus: this.focusedComponent,
325
+ hidden: false,
326
+ focusOrder: ++this.focusOrderCounter,
327
+ };
328
+ this.overlayStack.push(entry);
329
+ // Only focus if overlay is actually visible
330
+ if (!options?.nonCapturing && this.isOverlayVisible(entry)) {
331
+ this.setFocus(component);
332
+ }
333
+ this.terminal.hideCursor();
334
+ this.requestRender();
335
+ // Return handle for controlling this overlay
336
+ return {
337
+ hide: () => {
338
+ const index = this.overlayStack.indexOf(entry);
339
+ if (index !== -1) {
340
+ this.clearOverlayFocusRestoreFor(entry);
341
+ this.retargetOverlayPreFocus(entry);
342
+ this.overlayStack.splice(index, 1);
343
+ // Restore focus if this overlay had focus
344
+ if (this.focusedComponent === component) {
345
+ const topVisible = this.getTopmostVisibleOverlay();
346
+ this.setFocus(topVisible?.component ?? entry.preFocus);
347
+ }
348
+ if (this.overlayStack.length === 0)
349
+ this.terminal.hideCursor();
350
+ this.requestRender();
351
+ }
352
+ },
353
+ setHidden: (hidden) => {
354
+ if (entry.hidden === hidden)
355
+ return;
356
+ entry.hidden = hidden;
357
+ // Update focus when hiding/showing
358
+ if (hidden) {
359
+ this.clearOverlayFocusRestoreFor(entry);
360
+ // If this overlay had focus, move focus to next visible or preFocus
361
+ if (this.focusedComponent === component) {
362
+ const topVisible = this.getTopmostVisibleOverlay();
363
+ this.setFocus(topVisible?.component ?? entry.preFocus);
364
+ }
365
+ }
366
+ else {
367
+ // Restore focus to this overlay when showing (if it's actually visible)
368
+ if (!options?.nonCapturing && this.isOverlayVisible(entry)) {
369
+ entry.focusOrder = ++this.focusOrderCounter;
370
+ this.setFocus(component);
371
+ }
372
+ }
373
+ this.requestRender();
374
+ },
375
+ isHidden: () => entry.hidden,
376
+ focus: () => {
377
+ if (!this.overlayStack.includes(entry) || !this.isOverlayVisible(entry))
378
+ return;
379
+ entry.focusOrder = ++this.focusOrderCounter;
380
+ this.setFocus(component);
381
+ this.requestRender();
382
+ },
383
+ unfocus: (unfocusOptions) => {
384
+ const isFocused = this.focusedComponent === component;
385
+ const restoreState = this.overlayFocusRestore;
386
+ const hasPendingRestore = restoreState.status !== "inactive" && restoreState.overlay === entry;
387
+ if (!isFocused && !hasPendingRestore)
388
+ return;
389
+ if (restoreState.status === "blocked" &&
390
+ restoreState.overlay === entry &&
391
+ this.focusedComponent === restoreState.blockedBy) {
392
+ if (unfocusOptions) {
393
+ this.overlayFocusRestore = {
394
+ status: "blocked",
395
+ overlay: entry,
396
+ blockedBy: restoreState.blockedBy,
397
+ resume: { status: "focus-target", target: unfocusOptions.target },
398
+ };
399
+ }
400
+ else {
401
+ this.clearOverlayFocusRestore();
402
+ }
403
+ this.requestRender();
404
+ return;
405
+ }
406
+ this.clearOverlayFocusRestoreFor(entry);
407
+ if (isFocused || unfocusOptions) {
408
+ const topVisible = this.getTopmostVisibleOverlay();
409
+ const fallbackTarget = topVisible && topVisible !== entry ? topVisible.component : entry.preFocus;
410
+ this.setFocus(unfocusOptions ? unfocusOptions.target : fallbackTarget);
411
+ }
412
+ this.requestRender();
413
+ },
414
+ isFocused: () => this.focusedComponent === component,
415
+ };
416
+ }
417
+ /** Hide the topmost overlay and restore previous focus. */
418
+ hideOverlay() {
419
+ const overlay = this.overlayStack[this.overlayStack.length - 1];
420
+ if (!overlay)
421
+ return;
422
+ this.clearOverlayFocusRestoreFor(overlay);
423
+ this.retargetOverlayPreFocus(overlay);
424
+ this.overlayStack.pop();
425
+ if (this.focusedComponent === overlay.component) {
426
+ // Find topmost visible overlay, or fall back to preFocus
427
+ const topVisible = this.getTopmostVisibleOverlay();
428
+ this.setFocus(topVisible?.component ?? overlay.preFocus);
429
+ }
430
+ if (this.overlayStack.length === 0)
431
+ this.terminal.hideCursor();
432
+ this.requestRender();
433
+ }
434
+ /** Check if there are any visible overlays */
435
+ hasOverlay() {
436
+ return this.overlayStack.some((o) => this.isOverlayVisible(o));
437
+ }
438
+ /** Check if an overlay entry is currently visible */
439
+ isOverlayVisible(entry) {
440
+ if (entry.hidden)
441
+ return false;
442
+ if (entry.options?.visible) {
443
+ return entry.options.visible(this.terminal.columns, this.terminal.rows);
444
+ }
445
+ return true;
446
+ }
447
+ /** Find the visual-frontmost visible capturing overlay, if any */
448
+ getTopmostVisibleOverlay() {
449
+ let topmost;
450
+ for (const overlay of this.overlayStack) {
451
+ if (overlay.options?.nonCapturing || !this.isOverlayVisible(overlay))
452
+ continue;
453
+ if (!topmost || overlay.focusOrder > topmost.focusOrder) {
454
+ topmost = overlay;
455
+ }
456
+ }
457
+ return topmost;
458
+ }
459
+ invalidate() {
460
+ super.invalidate();
461
+ for (const overlay of this.overlayStack)
462
+ overlay.component.invalidate?.();
463
+ }
464
+ start() {
465
+ this.stopped = false;
466
+ this.terminal.start((data) => this.handleInput(data), () => this.requestRender());
467
+ this.terminal.hideCursor();
468
+ if (this.terminalColorSchemeNotificationsEnabled) {
469
+ this.terminal.write("\x1b[?2031h");
470
+ }
471
+ this.queryCellSize();
472
+ this.requestRender();
473
+ }
474
+ addInputListener(listener) {
475
+ this.inputListeners.add(listener);
476
+ return () => {
477
+ this.inputListeners.delete(listener);
478
+ };
479
+ }
480
+ removeInputListener(listener) {
481
+ this.inputListeners.delete(listener);
482
+ }
483
+ onTerminalColorSchemeChange(listener) {
484
+ this.terminalColorSchemeListeners.add(listener);
485
+ return () => {
486
+ this.terminalColorSchemeListeners.delete(listener);
487
+ };
488
+ }
489
+ setTerminalColorSchemeNotifications(enabled) {
490
+ if (this.terminalColorSchemeNotificationsEnabled === enabled) {
491
+ return;
492
+ }
493
+ this.terminalColorSchemeNotificationsEnabled = enabled;
494
+ if (!this.stopped) {
495
+ this.terminal.write(enabled ? "\x1b[?2031h" : "\x1b[?2031l");
496
+ }
497
+ }
498
+ queryCellSize() {
499
+ // Only query if terminal supports images (cell size is only used for image rendering)
500
+ if (!getCapabilities().images) {
501
+ return;
502
+ }
503
+ // Query terminal for cell size in pixels: CSI 16 t
504
+ // Response format: CSI 6 ; height ; width t
505
+ this.terminal.write("\x1b[16t");
506
+ }
507
+ stop() {
508
+ this.stopped = true;
509
+ // Graceful shutdown: let root components flush any pending history.
510
+ for (const child of this.children) {
511
+ child.beginHistoryFlush?.();
512
+ }
513
+ if (this.renderTimer) {
514
+ clearTimeout(this.renderTimer);
515
+ this.renderTimer = undefined;
516
+ }
517
+ if (this.terminalColorSchemeNotificationsEnabled) {
518
+ this.terminal.write("\x1b[?2031l");
519
+ }
520
+ // Move cursor to the end of the content to prevent overwriting/artifacts on exit
521
+ if (this.previousLines.length > 0) {
522
+ const targetRow = this.previousLines.length; // Line after the last content
523
+ const lineDiff = targetRow - this.hardwareCursorRow;
524
+ if (lineDiff > 0) {
525
+ this.terminal.write(`\x1b[${lineDiff}B`);
526
+ }
527
+ else if (lineDiff < 0) {
528
+ this.terminal.write(`\x1b[${-lineDiff}A`);
529
+ }
530
+ this.terminal.write("\r\n");
531
+ }
532
+ this.terminal.showCursor();
533
+ this.terminal.stop();
534
+ }
535
+ requestRender(force = false) {
536
+ if (force) {
537
+ this.previousLines = [];
538
+ this.previousWidth = -1; // -1 triggers widthChanged, forcing a full clear
539
+ this.previousHeight = -1; // -1 triggers heightChanged, forcing a full clear
540
+ this.cursorRow = 0;
541
+ this.hardwareCursorRow = 0;
542
+ this.maxLinesRendered = 0;
543
+ this.previousViewportTop = 0;
544
+ if (this.renderTimer) {
545
+ clearTimeout(this.renderTimer);
546
+ this.renderTimer = undefined;
547
+ }
548
+ this.renderRequested = true;
549
+ process.nextTick(() => {
550
+ if (this.stopped || !this.renderRequested) {
551
+ return;
552
+ }
553
+ this.renderRequested = false;
554
+ this.lastRenderAt = performance.now();
555
+ this.doRender();
556
+ });
557
+ return;
558
+ }
559
+ if (this.renderRequested)
560
+ return;
561
+ this.renderRequested = true;
562
+ process.nextTick(() => this.scheduleRender());
563
+ }
564
+ scheduleRender() {
565
+ if (this.stopped || this.renderTimer || !this.renderRequested) {
566
+ return;
567
+ }
568
+ const elapsed = performance.now() - this.lastRenderAt;
569
+ const delay = Math.max(0, TUI.MIN_RENDER_INTERVAL_MS - elapsed);
570
+ this.renderTimer = setTimeout(() => {
571
+ this.renderTimer = undefined;
572
+ if (this.stopped || !this.renderRequested) {
573
+ return;
574
+ }
575
+ this.renderRequested = false;
576
+ this.lastRenderAt = performance.now();
577
+ this.doRender();
578
+ if (this.renderRequested) {
579
+ this.scheduleRender();
580
+ }
581
+ }, delay);
582
+ }
583
+ handleInput(data) {
584
+ if (this.consumeOsc11BackgroundResponse(data)) {
585
+ return;
586
+ }
587
+ if (this.consumeTerminalColorSchemeReport(data)) {
588
+ return;
589
+ }
590
+ if (this.inputListeners.size > 0) {
591
+ let current = data;
592
+ for (const listener of this.inputListeners) {
593
+ const result = listener(current);
594
+ if (result?.consume) {
595
+ return;
596
+ }
597
+ if (result?.data !== undefined) {
598
+ current = result.data;
599
+ }
600
+ }
601
+ if (current.length === 0) {
602
+ return;
603
+ }
604
+ data = current;
605
+ }
606
+ // Consume terminal cell size responses without blocking unrelated input.
607
+ if (this.consumeCellSizeResponse(data)) {
608
+ return;
609
+ }
610
+ // Global debug key handler (Shift+Ctrl+D)
611
+ if (matchesKey(data, "shift+ctrl+d") && this.onDebug) {
612
+ this.onDebug();
613
+ return;
614
+ }
615
+ // If focused component is an overlay, verify it's still visible
616
+ // (visibility can change due to terminal resize or visible() callback)
617
+ const focusedOverlay = this.overlayStack.find((o) => o.component === this.focusedComponent);
618
+ if (focusedOverlay && !this.isOverlayVisible(focusedOverlay)) {
619
+ // Focused overlay is no longer visible, redirect to topmost visible overlay
620
+ const topVisible = this.getTopmostVisibleOverlay();
621
+ if (topVisible) {
622
+ this.setFocus(topVisible.component);
623
+ }
624
+ else {
625
+ this.setFocusInternal({
626
+ component: focusedOverlay.preFocus,
627
+ overlayFocusRestore: "preserve",
628
+ });
629
+ }
630
+ }
631
+ const focusIsOverlay = this.overlayStack.some((o) => o.component === this.focusedComponent);
632
+ if (!focusIsOverlay) {
633
+ const restoreState = this.getVisibleOverlayFocusRestore();
634
+ if (restoreState.status === "eligible") {
635
+ this.setFocus(restoreState.overlay.component);
636
+ }
637
+ else if (restoreState.status === "blocked" &&
638
+ restoreState.blockedBy !== this.focusedComponent) {
639
+ if (restoreState.resume.status === "restore-overlay") {
640
+ this.setFocus(restoreState.overlay.component);
641
+ }
642
+ else {
643
+ this.clearOverlayFocusRestore();
644
+ this.setFocus(restoreState.resume.target);
645
+ }
646
+ }
647
+ }
648
+ // Pass input to focused component (including Ctrl+C)
649
+ // The focused component can decide how to handle Ctrl+C
650
+ if (this.focusedComponent?.handleInput) {
651
+ // Filter out key release events unless component opts in
652
+ if (isKeyRelease(data) && !this.focusedComponent.wantsKeyRelease) {
653
+ return;
654
+ }
655
+ this.focusedComponent.handleInput(data);
656
+ this.requestRender();
657
+ }
658
+ }
659
+ consumeOsc11BackgroundResponse(data) {
660
+ if (this.pendingOsc11BackgroundReplies <= 0) {
661
+ return false;
662
+ }
663
+ if (!isOsc11BackgroundColorResponse(data)) {
664
+ return false;
665
+ }
666
+ const rgb = parseOsc11BackgroundColor(data);
667
+ this.pendingOsc11BackgroundReplies -= 1;
668
+ const query = this.pendingOsc11BackgroundQueries.shift();
669
+ if (query && !query.settled) {
670
+ query.settled = true;
671
+ if (query.timer) {
672
+ clearTimeout(query.timer);
673
+ query.timer = undefined;
674
+ }
675
+ query.resolve?.(rgb);
676
+ query.resolve = undefined;
677
+ }
678
+ return true;
679
+ }
680
+ consumeTerminalColorSchemeReport(data) {
681
+ const scheme = parseTerminalColorSchemeReport(data);
682
+ if (!scheme) {
683
+ return false;
684
+ }
685
+ for (const listener of this.terminalColorSchemeListeners) {
686
+ listener(scheme);
687
+ }
688
+ return true;
689
+ }
690
+ consumeCellSizeResponse(data) {
691
+ // Response format: ESC [ 6 ; height ; width t
692
+ const match = data.match(/^\x1b\[6;(\d+);(\d+)t$/);
693
+ if (!match) {
694
+ return false;
695
+ }
696
+ const heightPx = parseInt(match[1], 10);
697
+ const widthPx = parseInt(match[2], 10);
698
+ if (heightPx <= 0 || widthPx <= 0) {
699
+ return true;
700
+ }
701
+ setCellDimensions({ widthPx, heightPx });
702
+ // Invalidate all components so images re-render with correct dimensions.
703
+ this.invalidate();
704
+ this.requestRender();
705
+ return true;
706
+ }
707
+ /**
708
+ * Resolve overlay layout from options.
709
+ * Returns { width, row, col, maxHeight } for rendering.
710
+ */
711
+ resolveOverlayLayout(options, overlayHeight, termWidth, termHeight) {
712
+ const opt = options ?? {};
713
+ // Parse margin (clamp to non-negative)
714
+ const margin = typeof opt.margin === "number"
715
+ ? {
716
+ top: opt.margin,
717
+ right: opt.margin,
718
+ bottom: opt.margin,
719
+ left: opt.margin,
720
+ }
721
+ : (opt.margin ?? {});
722
+ const marginTop = Math.max(0, margin.top ?? 0);
723
+ const marginRight = Math.max(0, margin.right ?? 0);
724
+ const marginBottom = Math.max(0, margin.bottom ?? 0);
725
+ const marginLeft = Math.max(0, margin.left ?? 0);
726
+ // Available space after margins
727
+ const availWidth = Math.max(1, termWidth - marginLeft - marginRight);
728
+ const availHeight = Math.max(1, termHeight - marginTop - marginBottom);
729
+ // === Resolve width ===
730
+ let width = parseSizeValue(opt.width, termWidth) ?? Math.min(80, availWidth);
731
+ // Apply minWidth
732
+ if (opt.minWidth !== undefined) {
733
+ width = Math.max(width, opt.minWidth);
734
+ }
735
+ // Clamp to available space
736
+ width = Math.max(1, Math.min(width, availWidth));
737
+ // === Resolve maxHeight ===
738
+ let maxHeight = parseSizeValue(opt.maxHeight, termHeight);
739
+ // Clamp to available space
740
+ if (maxHeight !== undefined) {
741
+ maxHeight = Math.max(1, Math.min(maxHeight, availHeight));
742
+ }
743
+ // Effective overlay height (may be clamped by maxHeight)
744
+ const effectiveHeight = maxHeight !== undefined ? Math.min(overlayHeight, maxHeight) : overlayHeight;
745
+ // === Resolve position ===
746
+ let row;
747
+ let col;
748
+ if (opt.row !== undefined) {
749
+ if (typeof opt.row === "string") {
750
+ // Percentage: 0% = top, 100% = bottom (overlay stays within bounds)
751
+ const match = opt.row.match(/^(\d+(?:\.\d+)?)%$/);
752
+ if (match) {
753
+ const maxRow = Math.max(0, availHeight - effectiveHeight);
754
+ const percent = parseFloat(match[1]) / 100;
755
+ row = marginTop + Math.floor(maxRow * percent);
756
+ }
757
+ else {
758
+ // Invalid format, fall back to center
759
+ row = this.resolveAnchorRow("center", effectiveHeight, availHeight, marginTop);
760
+ }
761
+ }
762
+ else {
763
+ // Absolute row position
764
+ row = opt.row;
765
+ }
766
+ }
767
+ else {
768
+ // Anchor-based (default: center)
769
+ const anchor = opt.anchor ?? "center";
770
+ row = this.resolveAnchorRow(anchor, effectiveHeight, availHeight, marginTop);
771
+ }
772
+ if (opt.col !== undefined) {
773
+ if (typeof opt.col === "string") {
774
+ // Percentage: 0% = left, 100% = right (overlay stays within bounds)
775
+ const match = opt.col.match(/^(\d+(?:\.\d+)?)%$/);
776
+ if (match) {
777
+ const maxCol = Math.max(0, availWidth - width);
778
+ const percent = parseFloat(match[1]) / 100;
779
+ col = marginLeft + Math.floor(maxCol * percent);
780
+ }
781
+ else {
782
+ // Invalid format, fall back to center
783
+ col = this.resolveAnchorCol("center", width, availWidth, marginLeft);
784
+ }
785
+ }
786
+ else {
787
+ // Absolute column position
788
+ col = opt.col;
789
+ }
790
+ }
791
+ else {
792
+ // Anchor-based (default: center)
793
+ const anchor = opt.anchor ?? "center";
794
+ col = this.resolveAnchorCol(anchor, width, availWidth, marginLeft);
795
+ }
796
+ // Apply offsets
797
+ if (opt.offsetY !== undefined)
798
+ row += opt.offsetY;
799
+ if (opt.offsetX !== undefined)
800
+ col += opt.offsetX;
801
+ // Clamp to terminal bounds (respecting margins)
802
+ row = Math.max(marginTop, Math.min(row, termHeight - marginBottom - effectiveHeight));
803
+ col = Math.max(marginLeft, Math.min(col, termWidth - marginRight - width));
804
+ return { width, row, col, maxHeight };
805
+ }
806
+ resolveAnchorRow(anchor, height, availHeight, marginTop) {
807
+ switch (anchor) {
808
+ case "top-left":
809
+ case "top-center":
810
+ case "top-right":
811
+ return marginTop;
812
+ case "bottom-left":
813
+ case "bottom-center":
814
+ case "bottom-right":
815
+ return marginTop + availHeight - height;
816
+ case "left-center":
817
+ case "center":
818
+ case "right-center":
819
+ return marginTop + Math.floor((availHeight - height) / 2);
820
+ }
821
+ }
822
+ resolveAnchorCol(anchor, width, availWidth, marginLeft) {
823
+ switch (anchor) {
824
+ case "top-left":
825
+ case "left-center":
826
+ case "bottom-left":
827
+ return marginLeft;
828
+ case "top-right":
829
+ case "right-center":
830
+ case "bottom-right":
831
+ return marginLeft + availWidth - width;
832
+ case "top-center":
833
+ case "center":
834
+ case "bottom-center":
835
+ return marginLeft + Math.floor((availWidth - width) / 2);
836
+ }
837
+ }
838
+ /** Composite all overlays into content lines (sorted by focusOrder, higher = on top). */
839
+ compositeOverlays(lines, termWidth, termHeight) {
840
+ if (this.overlayStack.length === 0)
841
+ return lines;
842
+ const result = [...lines];
843
+ // Pre-render all visible overlays and calculate positions
844
+ const rendered = [];
845
+ let minLinesNeeded = result.length;
846
+ const visibleEntries = this.overlayStack.filter((e) => this.isOverlayVisible(e));
847
+ visibleEntries.sort((a, b) => a.focusOrder - b.focusOrder);
848
+ for (const entry of visibleEntries) {
849
+ const { component, options } = entry;
850
+ // Get layout with height=0 first to determine width and maxHeight
851
+ // (width and maxHeight don't depend on overlay height)
852
+ const { width, maxHeight } = this.resolveOverlayLayout(options, 0, termWidth, termHeight);
853
+ // Render component at calculated width
854
+ let overlayLines = component.render(width);
855
+ // Apply maxHeight if specified
856
+ if (maxHeight !== undefined && overlayLines.length > maxHeight) {
857
+ overlayLines = overlayLines.slice(0, maxHeight);
858
+ }
859
+ // Get final row/col with actual overlay height
860
+ const { row, col } = this.resolveOverlayLayout(options, overlayLines.length, termWidth, termHeight);
861
+ rendered.push({ overlayLines, row, col, w: width });
862
+ minLinesNeeded = Math.max(minLinesNeeded, row + overlayLines.length);
863
+ }
864
+ // Pad to at least terminal height so overlays have screen-relative positions.
865
+ // Excludes maxLinesRendered: the historical high-water mark caused self-reinforcing
866
+ // inflation that pushed content into scrollback on terminal widen.
867
+ const workingHeight = Math.max(result.length, termHeight, minLinesNeeded);
868
+ // Extend result with empty lines if content is too short for overlay placement or working area
869
+ while (result.length < workingHeight) {
870
+ result.push("");
871
+ }
872
+ const viewportStart = Math.max(0, workingHeight - termHeight);
873
+ // Composite each overlay
874
+ for (const { overlayLines, row, col, w } of rendered) {
875
+ for (let i = 0; i < overlayLines.length; i++) {
876
+ const idx = viewportStart + row + i;
877
+ if (idx >= 0 && idx < result.length) {
878
+ // Defensive: truncate overlay line to declared width before compositing
879
+ // (components should already respect width, but this ensures it)
880
+ const truncatedOverlayLine = visibleWidth(overlayLines[i]) > w
881
+ ? sliceByColumn(overlayLines[i], 0, w, true)
882
+ : overlayLines[i];
883
+ result[idx] = this.compositeLineAt(result[idx], truncatedOverlayLine, col, w, termWidth);
884
+ }
885
+ }
886
+ }
887
+ return result;
888
+ }
889
+ static SEGMENT_RESET = "\x1b[0m\x1b]8;;\x07";
890
+ applyLineResets(lines) {
891
+ const reset = TUI.SEGMENT_RESET;
892
+ for (let i = 0; i < lines.length; i++) {
893
+ const line = lines[i];
894
+ if (!isImageLine(line)) {
895
+ lines[i] = normalizeTerminalOutput(line) + reset;
896
+ }
897
+ }
898
+ return lines;
899
+ }
900
+ collectKittyImageIds(lines) {
901
+ const ids = new Set();
902
+ for (const line of lines) {
903
+ for (const id of extractKittyImageIds(line)) {
904
+ ids.add(id);
905
+ }
906
+ }
907
+ return ids;
908
+ }
909
+ deleteKittyImages(ids) {
910
+ let buffer = "";
911
+ for (const id of ids) {
912
+ buffer += deleteKittyImage(id);
913
+ }
914
+ return buffer;
915
+ }
916
+ getKittyImageReservedRows(lines, index, maxIndex = lines.length - 1) {
917
+ const rows = extractKittyImageRows(lines[index] ?? "");
918
+ if (rows <= 1)
919
+ return 1;
920
+ const maxRows = Math.min(rows, maxIndex - index + 1, lines.length - index);
921
+ let reservedRows = 1;
922
+ while (reservedRows < maxRows) {
923
+ const line = lines[index + reservedRows] ?? "";
924
+ if (isImageLine(line) || visibleWidth(line) > 0)
925
+ break;
926
+ reservedRows++;
927
+ }
928
+ return reservedRows;
929
+ }
930
+ expandChangedRangeForKittyImages(firstChanged, lastChanged, newLines) {
931
+ let expandedFirstChanged = firstChanged;
932
+ let expandedLastChanged = lastChanged;
933
+ const expandForLines = (lines) => {
934
+ for (let i = 0; i < lines.length; i++) {
935
+ if (extractKittyImageIds(lines[i]).length === 0)
936
+ continue;
937
+ const blockEnd = i + this.getKittyImageReservedRows(lines, i) - 1;
938
+ if (i >= firstChanged || (i <= lastChanged && blockEnd >= firstChanged)) {
939
+ expandedFirstChanged = Math.min(expandedFirstChanged, i);
940
+ expandedLastChanged = Math.max(expandedLastChanged, blockEnd);
941
+ }
942
+ }
943
+ };
944
+ expandForLines(this.previousLines);
945
+ expandForLines(newLines);
946
+ return {
947
+ firstChanged: expandedFirstChanged,
948
+ lastChanged: expandedLastChanged,
949
+ };
950
+ }
951
+ deleteChangedKittyImages(firstChanged, lastChanged) {
952
+ if (firstChanged < 0 || lastChanged < firstChanged)
953
+ return "";
954
+ const ids = new Set();
955
+ const maxLine = Math.min(lastChanged, this.previousLines.length - 1);
956
+ for (let i = firstChanged; i <= maxLine; i++) {
957
+ for (const id of extractKittyImageIds(this.previousLines[i] ?? "")) {
958
+ ids.add(id);
959
+ }
960
+ }
961
+ return this.deleteKittyImages(ids);
962
+ }
963
+ /** Splice overlay content into a base line at a specific column. Single-pass optimized. */
964
+ compositeLineAt(baseLine, overlayLine, startCol, overlayWidth, totalWidth) {
965
+ if (isImageLine(baseLine))
966
+ return baseLine;
967
+ // Single pass through baseLine extracts both before and after segments
968
+ const afterStart = startCol + overlayWidth;
969
+ const base = extractSegments(baseLine, startCol, afterStart, totalWidth - afterStart, true);
970
+ // Extract overlay with width tracking (strict=true to exclude wide chars at boundary)
971
+ const overlay = sliceWithWidth(overlayLine, 0, overlayWidth, true);
972
+ // Pad segments to target widths
973
+ const beforePad = Math.max(0, startCol - base.beforeWidth);
974
+ const overlayPad = Math.max(0, overlayWidth - overlay.width);
975
+ const actualBeforeWidth = Math.max(startCol, base.beforeWidth);
976
+ const actualOverlayWidth = Math.max(overlayWidth, overlay.width);
977
+ const afterTarget = Math.max(0, totalWidth - actualBeforeWidth - actualOverlayWidth);
978
+ const afterPad = Math.max(0, afterTarget - base.afterWidth);
979
+ // Compose result
980
+ const r = TUI.SEGMENT_RESET;
981
+ const result = base.before +
982
+ " ".repeat(beforePad) +
983
+ r +
984
+ overlay.text +
985
+ " ".repeat(overlayPad) +
986
+ r +
987
+ base.after +
988
+ " ".repeat(afterPad);
989
+ // CRITICAL: Always verify and truncate to terminal width.
990
+ // This is the final safeguard against width overflow which would crash the TUI.
991
+ // Width tracking can drift from actual visible width due to:
992
+ // - Complex ANSI/OSC sequences (hyperlinks, colors)
993
+ // - Wide characters at segment boundaries
994
+ // - Edge cases in segment extraction
995
+ const resultWidth = visibleWidth(result);
996
+ if (resultWidth <= totalWidth) {
997
+ return result;
998
+ }
999
+ // Truncate with strict=true to ensure we don't exceed totalWidth
1000
+ return sliceByColumn(result, 0, totalWidth, true);
1001
+ }
1002
+ /**
1003
+ * Find and extract cursor position from rendered lines.
1004
+ * Searches for CURSOR_MARKER, calculates its position, and strips it from the output.
1005
+ * Only scans the bottom terminal height lines (visible viewport).
1006
+ * @param lines - Rendered lines to search
1007
+ * @param height - Terminal height (visible viewport size)
1008
+ * @returns Cursor position { row, col } or null if no marker found
1009
+ */
1010
+ extractCursorPosition(lines, height) {
1011
+ // Only scan the bottom `height` lines (visible viewport)
1012
+ const viewportTop = Math.max(0, lines.length - height);
1013
+ for (let row = lines.length - 1; row >= viewportTop; row--) {
1014
+ const line = lines[row];
1015
+ const markerIndex = line.indexOf(CURSOR_MARKER);
1016
+ if (markerIndex !== -1) {
1017
+ // Calculate visual column (width of text before marker)
1018
+ const beforeMarker = line.slice(0, markerIndex);
1019
+ const col = visibleWidth(beforeMarker);
1020
+ // Strip marker from the line
1021
+ lines[row] = line.slice(0, markerIndex) + line.slice(markerIndex + CURSOR_MARKER.length);
1022
+ return { row, col };
1023
+ }
1024
+ }
1025
+ return null;
1026
+ }
1027
+ /** Advance the committed boundary and notify root children. */
1028
+ syncCommittedRows() {
1029
+ this.committedRows = Math.max(this.committedRows, this.previousViewportTop);
1030
+ for (const child of this.children) {
1031
+ setNativeScrollbackCommittedRows(child, this.committedRows);
1032
+ }
1033
+ }
1034
+ /** Provider frame path: append committed history to native scrollback and
1035
+ * repaint the bounded mutable viewport. When a terminal frame provider is
1036
+ * installed this replaces the full-frame differential renderer so old rows
1037
+ * scroll into the terminal's own scrollback instead of being covered. */
1038
+ renderProviderFrame(width, height) {
1039
+ const provider = this.frameProvider;
1040
+ if (!provider || width <= 0 || height <= 0)
1041
+ return;
1042
+ const plan = provider.renderFrame({ columns: width, rows: height });
1043
+ let viewport = [...plan.viewport];
1044
+ if (viewport.length > height)
1045
+ viewport = viewport.slice(0, height);
1046
+ if (this.overlayStack.length > 0) {
1047
+ while (viewport.length < height)
1048
+ viewport.push("");
1049
+ viewport = this.compositeOverlays(viewport, width, height);
1050
+ }
1051
+ const cursorPos = this.extractCursorPosition(viewport, height);
1052
+ viewport = this.applyLineResets(viewport);
1053
+ const rows = viewport.length;
1054
+ // A batch we already accepted is not pending; ack so the provider can drain.
1055
+ if (plan.history && plan.history.id <= this.acceptedHistoryBatchId) {
1056
+ provider.acknowledgeHistory?.(plan.history.id);
1057
+ }
1058
+ const history = plan.history && plan.history.id > this.acceptedHistoryBatchId ? plan.history : undefined;
1059
+ const historyRows = history?.rows ?? [];
1060
+ const widthChanged = this.previousWidth !== 0 && this.previousWidth !== width;
1061
+ const destructiveReset = widthChanged || this.providerForceRepaint;
1062
+ if (destructiveReset) {
1063
+ this.providerViewportTop = 0;
1064
+ this.providerWindow = [];
1065
+ }
1066
+ const startTop = destructiveReset
1067
+ ? 0
1068
+ : Math.min(this.providerViewportTop, Math.max(0, height - 1));
1069
+ const newTop = Math.max(0, Math.min(startTop + historyRows.length, height - rows));
1070
+ let buffer = "\x1b[?2026h";
1071
+ if (destructiveReset)
1072
+ buffer += "\x1b[H\x1b[3J\x1b[2J";
1073
+ const pushed = Math.max(0, startTop + historyRows.length + rows - height);
1074
+ if (pushed > this.providerViewportTop && this.providerWindow.length > 0) {
1075
+ buffer += `\x1b[${this.providerViewportTop + 1};1H\x1b[J`;
1076
+ }
1077
+ buffer += `\x1b[${startTop + 1};1H`;
1078
+ let screenRow = startTop;
1079
+ for (const line of historyRows) {
1080
+ if (screenRow > startTop)
1081
+ buffer += "\r\n";
1082
+ buffer += `\x1b[2K${line}`;
1083
+ screenRow++;
1084
+ }
1085
+ for (let index = 0; index < rows; index++) {
1086
+ if (index > 0 || screenRow > startTop)
1087
+ buffer += "\r\n";
1088
+ buffer += `\x1b[2K${viewport[index] ?? ""}`;
1089
+ screenRow++;
1090
+ }
1091
+ if (newTop + rows < height)
1092
+ buffer += `\x1b[${newTop + rows + 1};1H\x1b[J`;
1093
+ if (cursorPos !== null && rows > 0) {
1094
+ const targetRow = newTop + Math.min(cursorPos.row, rows - 1);
1095
+ buffer += `\x1b[${targetRow + 1};${cursorPos.col + 1}H`;
1096
+ }
1097
+ else {
1098
+ buffer += `\x1b[${newTop + 1};1H`;
1099
+ }
1100
+ buffer += "\x1b[?2026l";
1101
+ this.terminal.write(buffer);
1102
+ this.providerWindow = viewport;
1103
+ this.providerViewportTop = newTop;
1104
+ this.previousWidth = width;
1105
+ this.previousHeight = height;
1106
+ this.fullRedrawCount += destructiveReset ? 1 : 0;
1107
+ if (history) {
1108
+ this.acceptedHistoryBatchId = history.id;
1109
+ provider.acknowledgeHistory?.(history.id);
1110
+ this.requestRender();
1111
+ }
1112
+ this.providerForceRepaint = false;
1113
+ }
1114
+ doRender() {
1115
+ if (this.stopped)
1116
+ return;
1117
+ const width = this.terminal.columns;
1118
+ const height = this.terminal.rows;
1119
+ if (this.frameProvider) {
1120
+ this.renderProviderFrame(width, height);
1121
+ return;
1122
+ }
1123
+ const widthChanged = this.previousWidth !== 0 && this.previousWidth !== width;
1124
+ const heightChanged = this.previousHeight !== 0 && this.previousHeight !== height;
1125
+ const previousBufferLength = this.previousHeight > 0 ? this.previousViewportTop + this.previousHeight : height;
1126
+ let prevViewportTop = heightChanged
1127
+ ? Math.max(0, previousBufferLength - height)
1128
+ : this.previousViewportTop;
1129
+ let viewportTop = prevViewportTop;
1130
+ let hardwareCursorRow = this.hardwareCursorRow;
1131
+ const computeLineDiff = (targetRow) => {
1132
+ const currentScreenRow = hardwareCursorRow - prevViewportTop;
1133
+ const targetScreenRow = targetRow - viewportTop;
1134
+ return targetScreenRow - currentScreenRow;
1135
+ };
1136
+ // Render all components to get new lines
1137
+ let newLines = this.render(width);
1138
+ // Composite overlays into the rendered lines (before differential compare)
1139
+ if (this.overlayStack.length > 0) {
1140
+ newLines = this.compositeOverlays(newLines, width, height);
1141
+ }
1142
+ // Extract cursor position before applying line resets (marker must be found first)
1143
+ const cursorPos = this.extractCursorPosition(newLines, height);
1144
+ newLines = this.applyLineResets(newLines);
1145
+ // Helper to clear scrollback and viewport and render all new lines
1146
+ const fullRender = (clear, clearScrollback = false) => {
1147
+ this.fullRedrawCount += 1;
1148
+ if (clear) {
1149
+ // Destructive replay: let root components rehydrate their frames.
1150
+ for (const child of this.children)
1151
+ prepareNativeScrollbackReplay(child);
1152
+ }
1153
+ let buffer = "\x1b[?2026h"; // Begin synchronized output
1154
+ if (clear) {
1155
+ buffer += this.deleteKittyImages(this.previousKittyImageIds);
1156
+ buffer += "\x1b[2J\x1b[H"; // Clear screen, home
1157
+ // Width changes rewrap the whole transcript; stale scrollback rows at
1158
+ // the old width would misalign above the new-width content, so drop
1159
+ // native scrollback too (omp clearScrollback behavior).
1160
+ if (clearScrollback)
1161
+ buffer += "\x1b[3J";
1162
+ }
1163
+ for (let i = 0; i < newLines.length; i++) {
1164
+ if (i > 0)
1165
+ buffer += "\r\n";
1166
+ const line = newLines[i];
1167
+ const isImage = isImageLine(line);
1168
+ const imageReservedRows = isImage ? this.getKittyImageReservedRows(newLines, i) : 1;
1169
+ if (imageReservedRows > 1 && imageReservedRows <= height) {
1170
+ for (let row = 1; row < imageReservedRows; row++) {
1171
+ buffer += "\r\n";
1172
+ }
1173
+ buffer += `\x1b[${imageReservedRows - 1}A`;
1174
+ buffer += line;
1175
+ buffer += `\x1b[${imageReservedRows - 1}B`;
1176
+ i += imageReservedRows - 1;
1177
+ continue;
1178
+ }
1179
+ buffer += line;
1180
+ }
1181
+ buffer += "\x1b[?2026l"; // End synchronized output
1182
+ this.terminal.write(buffer);
1183
+ this.cursorRow = Math.max(0, newLines.length - 1);
1184
+ this.hardwareCursorRow = this.cursorRow;
1185
+ // Reset max lines when clearing, otherwise track growth
1186
+ if (clear) {
1187
+ this.maxLinesRendered = newLines.length;
1188
+ }
1189
+ else {
1190
+ this.maxLinesRendered = Math.max(this.maxLinesRendered, newLines.length);
1191
+ }
1192
+ const bufferLength = Math.max(height, newLines.length);
1193
+ this.previousViewportTop = Math.max(0, bufferLength - height);
1194
+ this.syncCommittedRows();
1195
+ this.positionHardwareCursor(cursorPos, newLines.length);
1196
+ this.previousLines = newLines;
1197
+ this.previousKittyImageIds = this.collectKittyImageIds(newLines);
1198
+ this.previousWidth = width;
1199
+ this.previousHeight = height;
1200
+ };
1201
+ const debugRedraw = process.env.PI_DEBUG_REDRAW === "1";
1202
+ const logRedraw = (reason) => {
1203
+ if (!debugRedraw)
1204
+ return;
1205
+ const logPath = path.join(os.homedir(), ".pi", "agent", "pi-debug.log");
1206
+ const msg = `[${new Date().toISOString()}] fullRender: ${reason} (prev=${this.previousLines.length}, new=${newLines.length}, height=${height})\n`;
1207
+ fs.appendFileSync(logPath, msg);
1208
+ };
1209
+ // First render - just output everything without clearing (assumes clean screen)
1210
+ if (this.previousLines.length === 0 && !widthChanged && !heightChanged) {
1211
+ logRedraw("first render");
1212
+ fullRender(false);
1213
+ return;
1214
+ }
1215
+ // Width changes always need a full re-render because wrapping changes.
1216
+ if (widthChanged) {
1217
+ logRedraw(`terminal width changed (${this.previousWidth} -> ${width})`);
1218
+ fullRender(true, true);
1219
+ return;
1220
+ }
1221
+ // Height changes normally need a full re-render to keep the visible viewport aligned,
1222
+ // but Termux changes height when the software keyboard shows or hides.
1223
+ // In that environment, a full redraw causes the entire history to replay on every toggle.
1224
+ if (heightChanged && !isTermuxSession()) {
1225
+ logRedraw(`terminal height changed (${this.previousHeight} -> ${height})`);
1226
+ fullRender(true);
1227
+ return;
1228
+ }
1229
+ // Content shrunk below the working area and no overlays - re-render to clear empty rows
1230
+ // (overlays need the padding, so only do this when no overlays are active)
1231
+ // Configurable via setClearOnShrink() or PI_CLEAR_ON_SHRINK=0 env var
1232
+ if (this.clearOnShrink &&
1233
+ newLines.length < this.maxLinesRendered &&
1234
+ this.overlayStack.length === 0) {
1235
+ logRedraw(`clearOnShrink (maxLinesRendered=${this.maxLinesRendered})`);
1236
+ fullRender(true);
1237
+ return;
1238
+ }
1239
+ // Find first and last changed lines
1240
+ let firstChanged = -1;
1241
+ let lastChanged = -1;
1242
+ const maxLines = Math.max(newLines.length, this.previousLines.length);
1243
+ for (let i = 0; i < maxLines; i++) {
1244
+ const oldLine = i < this.previousLines.length ? this.previousLines[i] : "";
1245
+ const newLine = i < newLines.length ? newLines[i] : "";
1246
+ if (oldLine !== newLine) {
1247
+ if (firstChanged === -1) {
1248
+ firstChanged = i;
1249
+ }
1250
+ lastChanged = i;
1251
+ }
1252
+ }
1253
+ const appendedLines = newLines.length > this.previousLines.length;
1254
+ if (appendedLines) {
1255
+ if (firstChanged === -1) {
1256
+ firstChanged = this.previousLines.length;
1257
+ }
1258
+ lastChanged = newLines.length - 1;
1259
+ }
1260
+ if (firstChanged !== -1) {
1261
+ const expandedRange = this.expandChangedRangeForKittyImages(firstChanged, lastChanged, newLines);
1262
+ firstChanged = expandedRange.firstChanged;
1263
+ lastChanged = expandedRange.lastChanged;
1264
+ }
1265
+ const appendStart = appendedLines && firstChanged === this.previousLines.length && firstChanged > 0;
1266
+ // No changes - but still need to update hardware cursor position if it moved
1267
+ if (firstChanged === -1) {
1268
+ this.positionHardwareCursor(cursorPos, newLines.length);
1269
+ this.previousViewportTop = prevViewportTop;
1270
+ this.syncCommittedRows();
1271
+ this.previousHeight = height;
1272
+ return;
1273
+ }
1274
+ // All changes are in deleted lines (nothing to render, just clear)
1275
+ if (firstChanged >= newLines.length) {
1276
+ if (this.previousLines.length > newLines.length) {
1277
+ let buffer = "\x1b[?2026h";
1278
+ buffer += this.deleteChangedKittyImages(firstChanged, lastChanged);
1279
+ // Move to end of new content (clamp to 0 for empty content)
1280
+ const targetRow = Math.max(0, newLines.length - 1);
1281
+ if (targetRow < prevViewportTop) {
1282
+ logRedraw(`deleted lines moved viewport up (${targetRow} < ${prevViewportTop})`);
1283
+ fullRender(true);
1284
+ return;
1285
+ }
1286
+ const lineDiff = computeLineDiff(targetRow);
1287
+ if (lineDiff > 0)
1288
+ buffer += `\x1b[${lineDiff}B`;
1289
+ else if (lineDiff < 0)
1290
+ buffer += `\x1b[${-lineDiff}A`;
1291
+ buffer += "\r";
1292
+ // Clear extra lines without scrolling
1293
+ const extraLines = this.previousLines.length - newLines.length;
1294
+ if (extraLines > height) {
1295
+ logRedraw(`extraLines > height (${extraLines} > ${height})`);
1296
+ fullRender(true);
1297
+ return;
1298
+ }
1299
+ const clearStartOffset = newLines.length === 0 ? 0 : 1;
1300
+ if (extraLines > 0 && clearStartOffset > 0) {
1301
+ buffer += `\x1b[${clearStartOffset}B`;
1302
+ }
1303
+ for (let i = 0; i < extraLines; i++) {
1304
+ buffer += "\r\x1b[2K";
1305
+ if (i < extraLines - 1)
1306
+ buffer += "\x1b[1B";
1307
+ }
1308
+ const moveBack = Math.max(0, extraLines - 1 + clearStartOffset);
1309
+ if (moveBack > 0) {
1310
+ buffer += `\x1b[${moveBack}A`;
1311
+ }
1312
+ buffer += "\x1b[?2026l";
1313
+ this.terminal.write(buffer);
1314
+ this.cursorRow = targetRow;
1315
+ this.hardwareCursorRow = targetRow;
1316
+ }
1317
+ this.positionHardwareCursor(cursorPos, newLines.length);
1318
+ this.previousLines = newLines;
1319
+ this.previousKittyImageIds = this.collectKittyImageIds(newLines);
1320
+ this.previousWidth = width;
1321
+ this.previousHeight = height;
1322
+ this.previousViewportTop = prevViewportTop;
1323
+ this.syncCommittedRows();
1324
+ return;
1325
+ }
1326
+ // Differential rendering can only touch what was actually visible.
1327
+ // If the first changed line is above the previous viewport, we need a full redraw.
1328
+ if (firstChanged < prevViewportTop) {
1329
+ logRedraw(`firstChanged < viewportTop (${firstChanged} < ${prevViewportTop})`);
1330
+ fullRender(true);
1331
+ return;
1332
+ }
1333
+ // Render from first changed line to end
1334
+ // Build buffer with all updates wrapped in synchronized output
1335
+ let buffer = "\x1b[?2026h"; // Begin synchronized output
1336
+ buffer += this.deleteChangedKittyImages(firstChanged, lastChanged);
1337
+ const prevViewportBottom = prevViewportTop + height - 1;
1338
+ const moveTargetRow = appendStart ? firstChanged - 1 : firstChanged;
1339
+ if (moveTargetRow > prevViewportBottom) {
1340
+ const currentScreenRow = Math.max(0, Math.min(height - 1, hardwareCursorRow - prevViewportTop));
1341
+ const moveToBottom = height - 1 - currentScreenRow;
1342
+ if (moveToBottom > 0) {
1343
+ buffer += `\x1b[${moveToBottom}B`;
1344
+ }
1345
+ const scroll = moveTargetRow - prevViewportBottom;
1346
+ buffer += "\r\n".repeat(scroll);
1347
+ prevViewportTop += scroll;
1348
+ viewportTop += scroll;
1349
+ hardwareCursorRow = moveTargetRow;
1350
+ }
1351
+ // Move cursor to first changed line (use hardwareCursorRow for actual position)
1352
+ const lineDiff = computeLineDiff(moveTargetRow);
1353
+ if (lineDiff > 0) {
1354
+ buffer += `\x1b[${lineDiff}B`; // Move down
1355
+ }
1356
+ else if (lineDiff < 0) {
1357
+ buffer += `\x1b[${-lineDiff}A`; // Move up
1358
+ }
1359
+ buffer += appendStart ? "\r\n" : "\r"; // Move to column 0
1360
+ // Only render changed lines (firstChanged to lastChanged), not all lines to end
1361
+ // This reduces flicker when only a single line changes (e.g., spinner animation)
1362
+ const renderEnd = Math.min(lastChanged, newLines.length - 1);
1363
+ for (let i = firstChanged; i <= renderEnd; i++) {
1364
+ if (i > firstChanged)
1365
+ buffer += "\r\n";
1366
+ const line = newLines[i];
1367
+ const isImage = isImageLine(line);
1368
+ const imageReservedRows = isImage
1369
+ ? this.getKittyImageReservedRows(newLines, i, renderEnd)
1370
+ : 1;
1371
+ if (imageReservedRows > 1) {
1372
+ const imageStartScreenRow = i - viewportTop;
1373
+ if (imageStartScreenRow < 0 || imageStartScreenRow + imageReservedRows > height) {
1374
+ logRedraw(`kitty image pre-clear would scroll (${imageStartScreenRow} + ${imageReservedRows} > ${height})`);
1375
+ fullRender(true);
1376
+ return;
1377
+ }
1378
+ buffer += "\x1b[2K";
1379
+ for (let row = 1; row < imageReservedRows; row++) {
1380
+ buffer += "\r\n\x1b[2K";
1381
+ }
1382
+ buffer += `\x1b[${imageReservedRows - 1}A`;
1383
+ buffer += line;
1384
+ buffer += `\x1b[${imageReservedRows - 1}B`;
1385
+ i += imageReservedRows - 1;
1386
+ continue;
1387
+ }
1388
+ buffer += "\x1b[2K"; // Clear current line
1389
+ if (!isImage && visibleWidth(line) > width) {
1390
+ // Log all lines to crash file for debugging
1391
+ const crashLogPath = path.join(os.homedir(), ".pi", "agent", "pi-crash.log");
1392
+ const crashData = [
1393
+ `Crash at ${new Date().toISOString()}`,
1394
+ `Terminal width: ${width}`,
1395
+ `Line ${i} visible width: ${visibleWidth(line)}`,
1396
+ "",
1397
+ "=== All rendered lines ===",
1398
+ ...newLines.map((l, idx) => `[${idx}] (w=${visibleWidth(l)}) ${l}`),
1399
+ "",
1400
+ ].join("\n");
1401
+ fs.mkdirSync(path.dirname(crashLogPath), { recursive: true });
1402
+ fs.writeFileSync(crashLogPath, crashData);
1403
+ // Clean up terminal state before throwing
1404
+ this.stop();
1405
+ const errorMsg = [
1406
+ `Rendered line ${i} exceeds terminal width (${visibleWidth(line)} > ${width}).`,
1407
+ "",
1408
+ "This is likely caused by a custom TUI component not truncating its output.",
1409
+ "Use visibleWidth() to measure and truncateToWidth() to truncate lines.",
1410
+ "",
1411
+ `Debug log written to: ${crashLogPath}`,
1412
+ ].join("\n");
1413
+ throw new Error(errorMsg);
1414
+ }
1415
+ buffer += line;
1416
+ }
1417
+ // Track where cursor ended up after rendering
1418
+ let finalCursorRow = renderEnd;
1419
+ // If we had more lines before, clear them and move cursor back
1420
+ if (this.previousLines.length > newLines.length) {
1421
+ // Move to end of new content first if we stopped before it
1422
+ if (renderEnd < newLines.length - 1) {
1423
+ const moveDown = newLines.length - 1 - renderEnd;
1424
+ buffer += `\x1b[${moveDown}B`;
1425
+ finalCursorRow = newLines.length - 1;
1426
+ }
1427
+ const extraLines = this.previousLines.length - newLines.length;
1428
+ for (let i = newLines.length; i < this.previousLines.length; i++) {
1429
+ buffer += "\r\n\x1b[2K";
1430
+ }
1431
+ // Move cursor back to end of new content
1432
+ buffer += `\x1b[${extraLines}A`;
1433
+ }
1434
+ buffer += "\x1b[?2026l"; // End synchronized output
1435
+ if (process.env.PI_TUI_DEBUG === "1") {
1436
+ const debugDir = "/tmp/tui";
1437
+ fs.mkdirSync(debugDir, { recursive: true });
1438
+ const debugPath = path.join(debugDir, `render-${Date.now()}-${Math.random().toString(36).slice(2)}.log`);
1439
+ const debugData = [
1440
+ `firstChanged: ${firstChanged}`,
1441
+ `viewportTop: ${viewportTop}`,
1442
+ `cursorRow: ${this.cursorRow}`,
1443
+ `height: ${height}`,
1444
+ `lineDiff: ${lineDiff}`,
1445
+ `hardwareCursorRow: ${hardwareCursorRow}`,
1446
+ `renderEnd: ${renderEnd}`,
1447
+ `finalCursorRow: ${finalCursorRow}`,
1448
+ `cursorPos: ${JSON.stringify(cursorPos)}`,
1449
+ `newLines.length: ${newLines.length}`,
1450
+ `previousLines.length: ${this.previousLines.length}`,
1451
+ "",
1452
+ "=== newLines ===",
1453
+ JSON.stringify(newLines, null, 2),
1454
+ "",
1455
+ "=== previousLines ===",
1456
+ JSON.stringify(this.previousLines, null, 2),
1457
+ "",
1458
+ "=== buffer ===",
1459
+ JSON.stringify(buffer),
1460
+ ].join("\n");
1461
+ fs.writeFileSync(debugPath, debugData);
1462
+ }
1463
+ // Write entire buffer at once
1464
+ this.terminal.write(buffer);
1465
+ // Track cursor position for next render
1466
+ // cursorRow tracks end of content (for viewport calculation)
1467
+ // hardwareCursorRow tracks actual terminal cursor position (for movement)
1468
+ this.cursorRow = Math.max(0, newLines.length - 1);
1469
+ this.hardwareCursorRow = finalCursorRow;
1470
+ // Track terminal's working area (grows but doesn't shrink unless cleared)
1471
+ this.maxLinesRendered = Math.max(this.maxLinesRendered, newLines.length);
1472
+ this.previousViewportTop = Math.max(prevViewportTop, finalCursorRow - height + 1);
1473
+ this.syncCommittedRows();
1474
+ // Position hardware cursor for IME
1475
+ this.positionHardwareCursor(cursorPos, newLines.length);
1476
+ this.previousLines = newLines;
1477
+ this.previousKittyImageIds = this.collectKittyImageIds(newLines);
1478
+ this.previousWidth = width;
1479
+ this.previousHeight = height;
1480
+ }
1481
+ /**
1482
+ * Position the hardware cursor for IME candidate window.
1483
+ * @param cursorPos The cursor position extracted from rendered output, or null
1484
+ * @param totalLines Total number of rendered lines
1485
+ */
1486
+ positionHardwareCursor(cursorPos, totalLines) {
1487
+ if (!cursorPos || totalLines <= 0) {
1488
+ this.terminal.hideCursor();
1489
+ return;
1490
+ }
1491
+ // Clamp cursor position to valid range
1492
+ const targetRow = Math.max(0, Math.min(cursorPos.row, totalLines - 1));
1493
+ const targetCol = Math.max(0, cursorPos.col);
1494
+ // Move cursor from current position to target
1495
+ const rowDelta = targetRow - this.hardwareCursorRow;
1496
+ let buffer = "";
1497
+ if (rowDelta > 0) {
1498
+ buffer += `\x1b[${rowDelta}B`; // Move down
1499
+ }
1500
+ else if (rowDelta < 0) {
1501
+ buffer += `\x1b[${-rowDelta}A`; // Move up
1502
+ }
1503
+ // Move to absolute column (1-indexed)
1504
+ buffer += `\x1b[${targetCol + 1}G`;
1505
+ if (buffer) {
1506
+ this.terminal.write(buffer);
1507
+ }
1508
+ this.hardwareCursorRow = targetRow;
1509
+ if (this.showHardwareCursor) {
1510
+ this.terminal.showCursor();
1511
+ }
1512
+ else {
1513
+ this.terminal.hideCursor();
1514
+ }
1515
+ }
1516
+ /**
1517
+ * Query the terminal's default background color with OSC 11 (`ESC ] 11 ; ? BEL`).
1518
+ * @param timeoutMs Query timeout in milliseconds.
1519
+ * @returns Promise containing the parsed RGB color, or undefined if it times out or fails to parse.
1520
+ */
1521
+ queryTerminalBackgroundColor({ timeoutMs, }) {
1522
+ return new Promise((resolve) => {
1523
+ const query = {
1524
+ settled: false,
1525
+ resolve,
1526
+ timer: undefined,
1527
+ };
1528
+ query.timer = setTimeout(() => {
1529
+ if (query.settled) {
1530
+ return;
1531
+ }
1532
+ query.settled = true;
1533
+ query.timer = undefined;
1534
+ query.resolve?.(undefined);
1535
+ query.resolve = undefined;
1536
+ }, timeoutMs);
1537
+ this.pendingOsc11BackgroundQueries.push(query);
1538
+ this.pendingOsc11BackgroundReplies += 1;
1539
+ this.terminal.write("\x1b]11;?\x07");
1540
+ });
1541
+ }
1542
+ /**
1543
+ * Query the terminal's color-scheme preference with DSR (`CSI ? 996 n`).
1544
+ * Terminals that support the color palette notification protocol reply with
1545
+ * `CSI ? 997 ; 1 n` for dark or `CSI ? 997 ; 2 n` for light.
1546
+ */
1547
+ queryTerminalColorScheme({ timeoutMs, }) {
1548
+ return new Promise((resolve) => {
1549
+ let settled = false;
1550
+ let timer;
1551
+ let unsubscribe = () => { };
1552
+ const settle = (scheme) => {
1553
+ if (settled)
1554
+ return;
1555
+ settled = true;
1556
+ if (timer) {
1557
+ clearTimeout(timer);
1558
+ timer = undefined;
1559
+ }
1560
+ unsubscribe();
1561
+ resolve(scheme);
1562
+ };
1563
+ unsubscribe = this.onTerminalColorSchemeChange(settle);
1564
+ timer = setTimeout(() => settle(undefined), timeoutMs);
1565
+ this.terminal.write("\x1b[?996n");
1566
+ });
1567
+ }
1568
+ }