lonny-agent 0.1.2 → 0.1.8

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 (216) hide show
  1. package/.kilo/plans/1780064105789-mighty-pixel.md +171 -0
  2. package/.lonny/fix-new-command-session-cleanup.md +65 -0
  3. package/.lonny/tui-autocomplete-above.md +62 -0
  4. package/dist/agent/__tests__/compaction.test.js +6 -4
  5. package/dist/agent/__tests__/compaction.test.js.map +1 -1
  6. package/dist/agent/llm.d.ts +1 -1
  7. package/dist/agent/llm.d.ts.map +1 -1
  8. package/dist/agent/prompt-builder.d.ts.map +1 -1
  9. package/dist/agent/prompt-builder.js +26 -8
  10. package/dist/agent/prompt-builder.js.map +1 -1
  11. package/dist/agent/providers/anthropic.d.ts +1 -1
  12. package/dist/agent/providers/anthropic.d.ts.map +1 -1
  13. package/dist/agent/providers/anthropic.js +2 -2
  14. package/dist/agent/providers/anthropic.js.map +1 -1
  15. package/dist/agent/providers/google.d.ts +1 -1
  16. package/dist/agent/providers/google.d.ts.map +1 -1
  17. package/dist/agent/providers/google.js +2 -1
  18. package/dist/agent/providers/google.js.map +1 -1
  19. package/dist/agent/providers/ollama.d.ts +1 -1
  20. package/dist/agent/providers/ollama.d.ts.map +1 -1
  21. package/dist/agent/providers/ollama.js +2 -1
  22. package/dist/agent/providers/ollama.js.map +1 -1
  23. package/dist/agent/providers/openai.d.ts +1 -1
  24. package/dist/agent/providers/openai.d.ts.map +1 -1
  25. package/dist/agent/providers/openai.js +2 -2
  26. package/dist/agent/providers/openai.js.map +1 -1
  27. package/dist/agent/session.d.ts +1 -0
  28. package/dist/agent/session.d.ts.map +1 -1
  29. package/dist/agent/session.js +8 -2
  30. package/dist/agent/session.js.map +1 -1
  31. package/dist/pi-tui/autocomplete.d.ts +54 -0
  32. package/dist/pi-tui/autocomplete.d.ts.map +1 -0
  33. package/dist/pi-tui/autocomplete.js +636 -0
  34. package/dist/pi-tui/autocomplete.js.map +1 -0
  35. package/dist/pi-tui/components/box.d.ts +22 -0
  36. package/dist/pi-tui/components/box.d.ts.map +1 -0
  37. package/dist/pi-tui/components/box.js +104 -0
  38. package/dist/pi-tui/components/box.js.map +1 -0
  39. package/dist/pi-tui/components/cancellable-loader.d.ts +22 -0
  40. package/dist/pi-tui/components/cancellable-loader.d.ts.map +1 -0
  41. package/dist/pi-tui/components/cancellable-loader.js +35 -0
  42. package/dist/pi-tui/components/cancellable-loader.js.map +1 -0
  43. package/dist/pi-tui/components/editor.d.ts +249 -0
  44. package/dist/pi-tui/components/editor.d.ts.map +1 -0
  45. package/dist/pi-tui/components/editor.js +1883 -0
  46. package/dist/pi-tui/components/editor.js.map +1 -0
  47. package/dist/pi-tui/components/image.d.ts +28 -0
  48. package/dist/pi-tui/components/image.d.ts.map +1 -0
  49. package/dist/pi-tui/components/image.js +90 -0
  50. package/dist/pi-tui/components/image.js.map +1 -0
  51. package/dist/pi-tui/components/input.d.ts +37 -0
  52. package/dist/pi-tui/components/input.d.ts.map +1 -0
  53. package/dist/pi-tui/components/input.js +382 -0
  54. package/dist/pi-tui/components/input.js.map +1 -0
  55. package/dist/pi-tui/components/loader.d.ts +31 -0
  56. package/dist/pi-tui/components/loader.d.ts.map +1 -0
  57. package/dist/pi-tui/components/loader.js +70 -0
  58. package/dist/pi-tui/components/loader.js.map +1 -0
  59. package/dist/pi-tui/components/markdown.d.ts +96 -0
  60. package/dist/pi-tui/components/markdown.d.ts.map +1 -0
  61. package/dist/pi-tui/components/markdown.js +647 -0
  62. package/dist/pi-tui/components/markdown.js.map +1 -0
  63. package/dist/pi-tui/components/select-list.d.ts +50 -0
  64. package/dist/pi-tui/components/select-list.d.ts.map +1 -0
  65. package/dist/pi-tui/components/select-list.js +167 -0
  66. package/dist/pi-tui/components/select-list.js.map +1 -0
  67. package/dist/pi-tui/components/settings-list.d.ts +50 -0
  68. package/dist/pi-tui/components/settings-list.d.ts.map +1 -0
  69. package/dist/pi-tui/components/settings-list.js +189 -0
  70. package/dist/pi-tui/components/settings-list.js.map +1 -0
  71. package/dist/pi-tui/components/spacer.d.ts +12 -0
  72. package/dist/pi-tui/components/spacer.d.ts.map +1 -0
  73. package/dist/pi-tui/components/spacer.js +23 -0
  74. package/dist/pi-tui/components/spacer.js.map +1 -0
  75. package/dist/pi-tui/components/text.d.ts +19 -0
  76. package/dist/pi-tui/components/text.d.ts.map +1 -0
  77. package/dist/pi-tui/components/text.js +91 -0
  78. package/dist/pi-tui/components/text.js.map +1 -0
  79. package/dist/pi-tui/components/truncated-text.d.ts +13 -0
  80. package/dist/pi-tui/components/truncated-text.d.ts.map +1 -0
  81. package/dist/pi-tui/components/truncated-text.js +51 -0
  82. package/dist/pi-tui/components/truncated-text.js.map +1 -0
  83. package/dist/pi-tui/editor-component.d.ts +39 -0
  84. package/dist/pi-tui/editor-component.d.ts.map +1 -0
  85. package/dist/pi-tui/editor-component.js +2 -0
  86. package/dist/pi-tui/editor-component.js.map +1 -0
  87. package/dist/pi-tui/fuzzy.d.ts +16 -0
  88. package/dist/pi-tui/fuzzy.d.ts.map +1 -0
  89. package/dist/pi-tui/fuzzy.js +110 -0
  90. package/dist/pi-tui/fuzzy.js.map +1 -0
  91. package/dist/pi-tui/index.d.ts +23 -0
  92. package/dist/pi-tui/index.d.ts.map +1 -0
  93. package/dist/pi-tui/index.js +32 -0
  94. package/dist/pi-tui/index.js.map +1 -0
  95. package/dist/pi-tui/keybindings.d.ts +193 -0
  96. package/dist/pi-tui/keybindings.d.ts.map +1 -0
  97. package/dist/pi-tui/keybindings.js +174 -0
  98. package/dist/pi-tui/keybindings.js.map +1 -0
  99. package/dist/pi-tui/keys.d.ts +184 -0
  100. package/dist/pi-tui/keys.d.ts.map +1 -0
  101. package/dist/pi-tui/keys.js +1182 -0
  102. package/dist/pi-tui/keys.js.map +1 -0
  103. package/dist/pi-tui/kill-ring.d.ts +28 -0
  104. package/dist/pi-tui/kill-ring.d.ts.map +1 -0
  105. package/dist/pi-tui/kill-ring.js +44 -0
  106. package/dist/pi-tui/kill-ring.js.map +1 -0
  107. package/dist/pi-tui/native/darwin/prebuilds/darwin-arm64/darwin-modifiers.node +0 -0
  108. package/dist/pi-tui/native/darwin/prebuilds/darwin-x64/darwin-modifiers.node +0 -0
  109. package/dist/pi-tui/native/win32/prebuilds/win32-arm64/win32-console-mode.node +0 -0
  110. package/dist/pi-tui/native/win32/prebuilds/win32-x64/win32-console-mode.node +0 -0
  111. package/dist/pi-tui/native-modifiers.d.ts +3 -0
  112. package/dist/pi-tui/native-modifiers.d.ts.map +1 -0
  113. package/dist/pi-tui/native-modifiers.js +53 -0
  114. package/dist/pi-tui/native-modifiers.js.map +1 -0
  115. package/dist/pi-tui/stdin-buffer.d.ts +50 -0
  116. package/dist/pi-tui/stdin-buffer.d.ts.map +1 -0
  117. package/dist/pi-tui/stdin-buffer.js +361 -0
  118. package/dist/pi-tui/stdin-buffer.js.map +1 -0
  119. package/dist/pi-tui/terminal-image.d.ts +90 -0
  120. package/dist/pi-tui/terminal-image.d.ts.map +1 -0
  121. package/dist/pi-tui/terminal-image.js +343 -0
  122. package/dist/pi-tui/terminal-image.js.map +1 -0
  123. package/dist/pi-tui/terminal.d.ts +113 -0
  124. package/dist/pi-tui/terminal.d.ts.map +1 -0
  125. package/dist/pi-tui/terminal.js +478 -0
  126. package/dist/pi-tui/terminal.js.map +1 -0
  127. package/dist/pi-tui/tui.d.ts +227 -0
  128. package/dist/pi-tui/tui.d.ts.map +1 -0
  129. package/dist/pi-tui/tui.js +1091 -0
  130. package/dist/pi-tui/tui.js.map +1 -0
  131. package/dist/pi-tui/undo-stack.d.ts +17 -0
  132. package/dist/pi-tui/undo-stack.d.ts.map +1 -0
  133. package/dist/pi-tui/undo-stack.js +25 -0
  134. package/dist/pi-tui/undo-stack.js.map +1 -0
  135. package/dist/pi-tui/utils.d.ts +84 -0
  136. package/dist/pi-tui/utils.d.ts.map +1 -0
  137. package/dist/pi-tui/utils.js +1024 -0
  138. package/dist/pi-tui/utils.js.map +1 -0
  139. package/dist/pi-tui/word-navigation.d.ts +25 -0
  140. package/dist/pi-tui/word-navigation.d.ts.map +1 -0
  141. package/dist/pi-tui/word-navigation.js +98 -0
  142. package/dist/pi-tui/word-navigation.js.map +1 -0
  143. package/dist/tools/__tests__/edit.test.js +85 -0
  144. package/dist/tools/__tests__/edit.test.js.map +1 -1
  145. package/dist/tools/edit.d.ts.map +1 -1
  146. package/dist/tools/edit.js +23 -1
  147. package/dist/tools/edit.js.map +1 -1
  148. package/dist/tui/components.d.ts +1 -1
  149. package/dist/tui/components.d.ts.map +1 -1
  150. package/dist/tui/components.js +1 -1
  151. package/dist/tui/components.js.map +1 -1
  152. package/dist/tui/editor-patch.d.ts +13 -0
  153. package/dist/tui/editor-patch.d.ts.map +1 -0
  154. package/dist/tui/editor-patch.js +41 -0
  155. package/dist/tui/editor-patch.js.map +1 -0
  156. package/dist/tui/index.d.ts.map +1 -1
  157. package/dist/tui/index.js +15 -3
  158. package/dist/tui/index.js.map +1 -1
  159. package/dist/web/index.d.ts.map +1 -1
  160. package/dist/web/index.js +9 -2
  161. package/dist/web/index.js.map +1 -1
  162. package/dist/web/public/app.js +65 -4
  163. package/dist/web/public/style.css +49 -0
  164. package/dist/web/session-bridge.d.ts +0 -4
  165. package/dist/web/session-bridge.d.ts.map +1 -1
  166. package/dist/web/session-bridge.js +16 -2
  167. package/dist/web/session-bridge.js.map +1 -1
  168. package/package.json +5 -3
  169. package/src/agent/__tests__/compaction.test.ts +6 -4
  170. package/src/agent/llm.ts +5 -1
  171. package/src/agent/prompt-builder.ts +27 -8
  172. package/src/agent/providers/anthropic.ts +15 -8
  173. package/src/agent/providers/google.ts +6 -1
  174. package/src/agent/providers/ollama.ts +6 -1
  175. package/src/agent/providers/openai.ts +21 -12
  176. package/src/agent/session.ts +12 -2
  177. package/src/pi-tui/autocomplete.ts +808 -0
  178. package/src/pi-tui/components/box.ts +137 -0
  179. package/src/pi-tui/components/cancellable-loader.ts +40 -0
  180. package/src/pi-tui/components/editor.ts +2321 -0
  181. package/src/pi-tui/components/image.ts +130 -0
  182. package/src/pi-tui/components/input.ts +456 -0
  183. package/src/pi-tui/components/loader.ts +93 -0
  184. package/src/pi-tui/components/markdown.ts +839 -0
  185. package/src/pi-tui/components/select-list.ts +263 -0
  186. package/src/pi-tui/components/settings-list.ts +264 -0
  187. package/src/pi-tui/components/spacer.ts +28 -0
  188. package/src/pi-tui/components/text.ts +113 -0
  189. package/src/pi-tui/components/truncated-text.ts +65 -0
  190. package/src/pi-tui/editor-component.ts +74 -0
  191. package/src/pi-tui/fuzzy.ts +137 -0
  192. package/src/pi-tui/index.ts +115 -0
  193. package/src/pi-tui/keybindings.ts +245 -0
  194. package/src/pi-tui/keys.ts +1440 -0
  195. package/src/pi-tui/kill-ring.ts +46 -0
  196. package/src/pi-tui/native/darwin/prebuilds/darwin-arm64/darwin-modifiers.node +0 -0
  197. package/src/pi-tui/native/darwin/prebuilds/darwin-x64/darwin-modifiers.node +0 -0
  198. package/src/pi-tui/native/win32/prebuilds/win32-arm64/win32-console-mode.node +0 -0
  199. package/src/pi-tui/native/win32/prebuilds/win32-x64/win32-console-mode.node +0 -0
  200. package/src/pi-tui/native-modifiers.ts +65 -0
  201. package/src/pi-tui/stdin-buffer.ts +434 -0
  202. package/src/pi-tui/terminal-image.ts +469 -0
  203. package/src/pi-tui/terminal.ts +594 -0
  204. package/src/pi-tui/tui.ts +1376 -0
  205. package/src/pi-tui/undo-stack.ts +28 -0
  206. package/src/pi-tui/utils.ts +1176 -0
  207. package/src/pi-tui/word-navigation.ts +127 -0
  208. package/src/tools/__tests__/edit.test.ts +91 -0
  209. package/src/tools/edit.ts +27 -1
  210. package/src/tui/components.ts +2 -2
  211. package/src/tui/index.ts +24 -10
  212. package/src/web/index.ts +9 -2
  213. package/src/web/public/app.js +65 -4
  214. package/src/web/public/style.css +49 -0
  215. package/src/web/session-bridge.ts +13 -2
  216. package/tsconfig.json +2 -2
@@ -0,0 +1,1091 @@
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 { deleteKittyImage, getCapabilities, isImageLine, setCellDimensions, } from './terminal-image.js';
10
+ import { extractSegments, normalizeTerminalOutput, sliceByColumn, sliceWithWidth, visibleWidth, } from './utils.js';
11
+ const KITTY_SEQUENCE_PREFIX = '\x1b_G';
12
+ function extractKittyImageIds(line) {
13
+ const sequenceStart = line.indexOf(KITTY_SEQUENCE_PREFIX);
14
+ if (sequenceStart === -1)
15
+ return [];
16
+ const paramsStart = sequenceStart + KITTY_SEQUENCE_PREFIX.length;
17
+ const paramsEnd = line.indexOf(';', paramsStart);
18
+ if (paramsEnd === -1)
19
+ return [];
20
+ const params = line.slice(paramsStart, paramsEnd);
21
+ for (const param of params.split(',')) {
22
+ const [key, value] = param.split('=', 2);
23
+ if (key !== 'i' || value === undefined)
24
+ continue;
25
+ const id = Number(value);
26
+ if (Number.isInteger(id) && id > 0 && id <= 0xffffffff) {
27
+ return [id];
28
+ }
29
+ }
30
+ return [];
31
+ }
32
+ /** Type guard to check if a component implements Focusable */
33
+ export function isFocusable(component) {
34
+ return component !== null && 'focused' in component;
35
+ }
36
+ /**
37
+ * Cursor position marker - APC (Application Program Command) sequence.
38
+ * This is a zero-width escape sequence that terminals ignore.
39
+ * Components emit this at the cursor position when focused.
40
+ * TUI finds and strips this marker, then positions the hardware cursor there.
41
+ */
42
+ export const CURSOR_MARKER = '\x1b_pi:c\x07';
43
+ export { visibleWidth };
44
+ /** Parse a SizeValue into absolute value given a reference size */
45
+ function parseSizeValue(value, referenceSize) {
46
+ if (value === undefined)
47
+ return undefined;
48
+ if (typeof value === 'number')
49
+ return value;
50
+ // Parse percentage string like "50%"
51
+ const match = value.match(/^(\d+(?:\.\d+)?)%$/);
52
+ if (match) {
53
+ return Math.floor((referenceSize * parseFloat(match[1])) / 100);
54
+ }
55
+ return undefined;
56
+ }
57
+ function isTermuxSession() {
58
+ return Boolean(process.env.TERMUX_VERSION);
59
+ }
60
+ /**
61
+ * Container - a component that contains other components
62
+ */
63
+ export class Container {
64
+ children = [];
65
+ addChild(component) {
66
+ this.children.push(component);
67
+ }
68
+ removeChild(component) {
69
+ const index = this.children.indexOf(component);
70
+ if (index !== -1) {
71
+ this.children.splice(index, 1);
72
+ }
73
+ }
74
+ clear() {
75
+ this.children = [];
76
+ }
77
+ invalidate() {
78
+ for (const child of this.children) {
79
+ child.invalidate?.();
80
+ }
81
+ }
82
+ render(width) {
83
+ const lines = [];
84
+ for (const child of this.children) {
85
+ const childLines = child.render(width);
86
+ for (const line of childLines) {
87
+ lines.push(line);
88
+ }
89
+ }
90
+ return lines;
91
+ }
92
+ }
93
+ /**
94
+ * TUI - Main class for managing terminal UI with differential rendering
95
+ */
96
+ export class TUI extends Container {
97
+ terminal;
98
+ previousLines = [];
99
+ previousKittyImageIds = new Set();
100
+ previousWidth = 0;
101
+ previousHeight = 0;
102
+ focusedComponent = null;
103
+ inputListeners = new Set();
104
+ /** Global callback for debug key (Shift+Ctrl+D). Called before input is forwarded to focused component. */
105
+ onDebug;
106
+ renderRequested = false;
107
+ renderTimer;
108
+ lastRenderAt = 0;
109
+ static MIN_RENDER_INTERVAL_MS = 16;
110
+ cursorRow = 0; // Logical cursor row (end of rendered content)
111
+ hardwareCursorRow = 0; // Actual terminal cursor row (may differ due to IME positioning)
112
+ showHardwareCursor = process.env.PI_HARDWARE_CURSOR === '1';
113
+ clearOnShrink = process.env.PI_CLEAR_ON_SHRINK === '1'; // Clear empty rows when content shrinks (default: off)
114
+ maxLinesRendered = 0; // Track terminal's working area (max lines ever rendered)
115
+ previousViewportTop = 0; // Track previous viewport top for resize-aware cursor moves
116
+ fullRedrawCount = 0;
117
+ stopped = false;
118
+ // Overlay stack for modal components rendered on top of base content
119
+ focusOrderCounter = 0;
120
+ overlayStack = [];
121
+ constructor(terminal, showHardwareCursor) {
122
+ super();
123
+ this.terminal = terminal;
124
+ if (showHardwareCursor !== undefined) {
125
+ this.showHardwareCursor = showHardwareCursor;
126
+ }
127
+ }
128
+ get fullRedraws() {
129
+ return this.fullRedrawCount;
130
+ }
131
+ getShowHardwareCursor() {
132
+ return this.showHardwareCursor;
133
+ }
134
+ setShowHardwareCursor(enabled) {
135
+ if (this.showHardwareCursor === enabled)
136
+ return;
137
+ this.showHardwareCursor = enabled;
138
+ if (!enabled) {
139
+ this.terminal.hideCursor();
140
+ }
141
+ this.requestRender();
142
+ }
143
+ getClearOnShrink() {
144
+ return this.clearOnShrink;
145
+ }
146
+ /**
147
+ * Set whether to trigger full re-render when content shrinks.
148
+ * When true (default), empty rows are cleared when content shrinks.
149
+ * When false, empty rows remain (reduces redraws on slower terminals).
150
+ */
151
+ setClearOnShrink(enabled) {
152
+ this.clearOnShrink = enabled;
153
+ }
154
+ setFocus(component) {
155
+ // Clear focused flag on old component
156
+ if (isFocusable(this.focusedComponent)) {
157
+ this.focusedComponent.focused = false;
158
+ }
159
+ this.focusedComponent = component;
160
+ // Set focused flag on new component
161
+ if (isFocusable(component)) {
162
+ component.focused = true;
163
+ }
164
+ }
165
+ /**
166
+ * Show an overlay component with configurable positioning and sizing.
167
+ * Returns a handle to control the overlay's visibility.
168
+ */
169
+ showOverlay(component, options) {
170
+ const entry = {
171
+ component,
172
+ options,
173
+ preFocus: this.focusedComponent,
174
+ hidden: false,
175
+ focusOrder: ++this.focusOrderCounter,
176
+ };
177
+ this.overlayStack.push(entry);
178
+ // Only focus if overlay is actually visible
179
+ if (!options?.nonCapturing && this.isOverlayVisible(entry)) {
180
+ this.setFocus(component);
181
+ }
182
+ this.terminal.hideCursor();
183
+ this.requestRender();
184
+ // Return handle for controlling this overlay
185
+ return {
186
+ hide: () => {
187
+ const index = this.overlayStack.indexOf(entry);
188
+ if (index !== -1) {
189
+ this.overlayStack.splice(index, 1);
190
+ // Restore focus if this overlay had focus
191
+ if (this.focusedComponent === component) {
192
+ const topVisible = this.getTopmostVisibleOverlay();
193
+ this.setFocus(topVisible?.component ?? entry.preFocus);
194
+ }
195
+ if (this.overlayStack.length === 0)
196
+ this.terminal.hideCursor();
197
+ this.requestRender();
198
+ }
199
+ },
200
+ setHidden: (hidden) => {
201
+ if (entry.hidden === hidden)
202
+ return;
203
+ entry.hidden = hidden;
204
+ // Update focus when hiding/showing
205
+ if (hidden) {
206
+ // If this overlay had focus, move focus to next visible or preFocus
207
+ if (this.focusedComponent === component) {
208
+ const topVisible = this.getTopmostVisibleOverlay();
209
+ this.setFocus(topVisible?.component ?? entry.preFocus);
210
+ }
211
+ }
212
+ else {
213
+ // Restore focus to this overlay when showing (if it's actually visible)
214
+ if (!options?.nonCapturing && this.isOverlayVisible(entry)) {
215
+ entry.focusOrder = ++this.focusOrderCounter;
216
+ this.setFocus(component);
217
+ }
218
+ }
219
+ this.requestRender();
220
+ },
221
+ isHidden: () => entry.hidden,
222
+ focus: () => {
223
+ if (!this.overlayStack.includes(entry) || !this.isOverlayVisible(entry))
224
+ return;
225
+ if (this.focusedComponent !== component) {
226
+ this.setFocus(component);
227
+ }
228
+ entry.focusOrder = ++this.focusOrderCounter;
229
+ this.requestRender();
230
+ },
231
+ unfocus: () => {
232
+ if (this.focusedComponent !== component)
233
+ return;
234
+ const topVisible = this.getTopmostVisibleOverlay();
235
+ this.setFocus(topVisible && topVisible !== entry ? topVisible.component : entry.preFocus);
236
+ this.requestRender();
237
+ },
238
+ isFocused: () => this.focusedComponent === component,
239
+ };
240
+ }
241
+ /** Hide the topmost overlay and restore previous focus. */
242
+ hideOverlay() {
243
+ const overlay = this.overlayStack.pop();
244
+ if (!overlay)
245
+ return;
246
+ if (this.focusedComponent === overlay.component) {
247
+ // Find topmost visible overlay, or fall back to preFocus
248
+ const topVisible = this.getTopmostVisibleOverlay();
249
+ this.setFocus(topVisible?.component ?? overlay.preFocus);
250
+ }
251
+ if (this.overlayStack.length === 0)
252
+ this.terminal.hideCursor();
253
+ this.requestRender();
254
+ }
255
+ /** Check if there are any visible overlays */
256
+ hasOverlay() {
257
+ return this.overlayStack.some(o => this.isOverlayVisible(o));
258
+ }
259
+ /** Check if an overlay entry is currently visible */
260
+ isOverlayVisible(entry) {
261
+ if (entry.hidden)
262
+ return false;
263
+ if (entry.options?.visible) {
264
+ return entry.options.visible(this.terminal.columns, this.terminal.rows);
265
+ }
266
+ return true;
267
+ }
268
+ /** Find the topmost visible capturing overlay, if any */
269
+ getTopmostVisibleOverlay() {
270
+ for (let i = this.overlayStack.length - 1; i >= 0; i--) {
271
+ if (this.overlayStack[i].options?.nonCapturing)
272
+ continue;
273
+ if (this.isOverlayVisible(this.overlayStack[i])) {
274
+ return this.overlayStack[i];
275
+ }
276
+ }
277
+ return undefined;
278
+ }
279
+ invalidate() {
280
+ super.invalidate();
281
+ for (const overlay of this.overlayStack)
282
+ overlay.component.invalidate?.();
283
+ }
284
+ start() {
285
+ this.stopped = false;
286
+ // Enter alternate screen buffer so there's no terminal scrollback.
287
+ // This keeps overlay-anchored components (header/footer) fixed in place
288
+ // instead of scrolling away when content exceeds terminal height.
289
+ this.terminal.write('\x1b[?1049h');
290
+ this.terminal.start(data => this.handleInput(data), () => this.requestRender());
291
+ this.terminal.hideCursor();
292
+ this.queryCellSize();
293
+ this.requestRender();
294
+ }
295
+ addInputListener(listener) {
296
+ this.inputListeners.add(listener);
297
+ return () => {
298
+ this.inputListeners.delete(listener);
299
+ };
300
+ }
301
+ removeInputListener(listener) {
302
+ this.inputListeners.delete(listener);
303
+ }
304
+ queryCellSize() {
305
+ // Only query if terminal supports images (cell size is only used for image rendering)
306
+ if (!getCapabilities().images) {
307
+ return;
308
+ }
309
+ // Query terminal for cell size in pixels: CSI 16 t
310
+ // Response format: CSI 6 ; height ; width t
311
+ this.terminal.write('\x1b[16t');
312
+ }
313
+ stop() {
314
+ this.stopped = true;
315
+ if (this.renderTimer) {
316
+ clearTimeout(this.renderTimer);
317
+ this.renderTimer = undefined;
318
+ }
319
+ // Exit alternate screen buffer before showing the cursor and stopping.
320
+ // Without this, the terminal stays in the alt screen after exit,
321
+ // obscuring the user's original terminal content.
322
+ this.terminal.write('\x1b[?1049l');
323
+ // Move cursor to the end of the content to prevent overwriting/artifacts on exit
324
+ if (this.previousLines.length > 0) {
325
+ const targetRow = this.previousLines.length; // Line after the last content
326
+ const lineDiff = targetRow - this.hardwareCursorRow;
327
+ if (lineDiff > 0) {
328
+ this.terminal.write(`\x1b[${lineDiff}B`);
329
+ }
330
+ else if (lineDiff < 0) {
331
+ this.terminal.write(`\x1b[${-lineDiff}A`);
332
+ }
333
+ this.terminal.write('\r\n');
334
+ }
335
+ this.terminal.showCursor();
336
+ this.terminal.stop();
337
+ }
338
+ requestRender(force = false) {
339
+ if (force) {
340
+ this.previousLines = [];
341
+ this.previousWidth = -1; // -1 triggers widthChanged, forcing a full clear
342
+ this.previousHeight = -1; // -1 triggers heightChanged, forcing a full clear
343
+ this.cursorRow = 0;
344
+ this.hardwareCursorRow = 0;
345
+ this.maxLinesRendered = 0;
346
+ this.previousViewportTop = 0;
347
+ if (this.renderTimer) {
348
+ clearTimeout(this.renderTimer);
349
+ this.renderTimer = undefined;
350
+ }
351
+ this.renderRequested = true;
352
+ process.nextTick(() => {
353
+ if (this.stopped || !this.renderRequested) {
354
+ return;
355
+ }
356
+ this.renderRequested = false;
357
+ this.lastRenderAt = performance.now();
358
+ this.doRender();
359
+ });
360
+ return;
361
+ }
362
+ if (this.renderRequested)
363
+ return;
364
+ this.renderRequested = true;
365
+ process.nextTick(() => this.scheduleRender());
366
+ }
367
+ scheduleRender() {
368
+ if (this.stopped || this.renderTimer || !this.renderRequested) {
369
+ return;
370
+ }
371
+ const elapsed = performance.now() - this.lastRenderAt;
372
+ const delay = Math.max(0, TUI.MIN_RENDER_INTERVAL_MS - elapsed);
373
+ this.renderTimer = setTimeout(() => {
374
+ this.renderTimer = undefined;
375
+ if (this.stopped || !this.renderRequested) {
376
+ return;
377
+ }
378
+ this.renderRequested = false;
379
+ this.lastRenderAt = performance.now();
380
+ this.doRender();
381
+ if (this.renderRequested) {
382
+ this.scheduleRender();
383
+ }
384
+ }, delay);
385
+ }
386
+ handleInput(data) {
387
+ if (this.inputListeners.size > 0) {
388
+ let current = data;
389
+ for (const listener of this.inputListeners) {
390
+ const result = listener(current);
391
+ if (result?.consume) {
392
+ return;
393
+ }
394
+ if (result?.data !== undefined) {
395
+ current = result.data;
396
+ }
397
+ }
398
+ if (current.length === 0) {
399
+ return;
400
+ }
401
+ data = current;
402
+ }
403
+ // Consume terminal cell size responses without blocking unrelated input.
404
+ if (this.consumeCellSizeResponse(data)) {
405
+ return;
406
+ }
407
+ // Global debug key handler (Shift+Ctrl+D)
408
+ if (matchesKey(data, 'shift+ctrl+d') && this.onDebug) {
409
+ this.onDebug();
410
+ return;
411
+ }
412
+ // If focused component is an overlay, verify it's still visible
413
+ // (visibility can change due to terminal resize or visible() callback)
414
+ const focusedOverlay = this.overlayStack.find(o => o.component === this.focusedComponent);
415
+ if (focusedOverlay && !this.isOverlayVisible(focusedOverlay)) {
416
+ // Focused overlay is no longer visible, redirect to topmost visible overlay
417
+ const topVisible = this.getTopmostVisibleOverlay();
418
+ if (topVisible) {
419
+ this.setFocus(topVisible.component);
420
+ }
421
+ else {
422
+ // No visible overlays, restore to preFocus
423
+ this.setFocus(focusedOverlay.preFocus);
424
+ }
425
+ }
426
+ // Pass input to focused component (including Ctrl+C)
427
+ // The focused component can decide how to handle Ctrl+C
428
+ if (this.focusedComponent?.handleInput) {
429
+ // Filter out key release events unless component opts in
430
+ if (isKeyRelease(data) && !this.focusedComponent.wantsKeyRelease) {
431
+ return;
432
+ }
433
+ this.focusedComponent.handleInput(data);
434
+ this.requestRender();
435
+ }
436
+ }
437
+ consumeCellSizeResponse(data) {
438
+ // Response format: ESC [ 6 ; height ; width t
439
+ const match = data.match(/^\x1b\[6;(\d+);(\d+)t$/);
440
+ if (!match) {
441
+ return false;
442
+ }
443
+ const heightPx = parseInt(match[1], 10);
444
+ const widthPx = parseInt(match[2], 10);
445
+ if (heightPx <= 0 || widthPx <= 0) {
446
+ return true;
447
+ }
448
+ setCellDimensions({ widthPx, heightPx });
449
+ // Invalidate all components so images re-render with correct dimensions.
450
+ this.invalidate();
451
+ this.requestRender();
452
+ return true;
453
+ }
454
+ /**
455
+ * Resolve overlay layout from options.
456
+ * Returns { width, row, col, maxHeight } for rendering.
457
+ */
458
+ resolveOverlayLayout(options, overlayHeight, termWidth, termHeight) {
459
+ const opt = options ?? {};
460
+ // Parse margin (clamp to non-negative)
461
+ const margin = typeof opt.margin === 'number'
462
+ ? { top: opt.margin, right: opt.margin, bottom: opt.margin, left: opt.margin }
463
+ : (opt.margin ?? {});
464
+ const marginTop = Math.max(0, margin.top ?? 0);
465
+ const marginRight = Math.max(0, margin.right ?? 0);
466
+ const marginBottom = Math.max(0, margin.bottom ?? 0);
467
+ const marginLeft = Math.max(0, margin.left ?? 0);
468
+ // Available space after margins
469
+ const availWidth = Math.max(1, termWidth - marginLeft - marginRight);
470
+ const availHeight = Math.max(1, termHeight - marginTop - marginBottom);
471
+ // === Resolve width ===
472
+ let width = parseSizeValue(opt.width, termWidth) ?? Math.min(80, availWidth);
473
+ // Apply minWidth
474
+ if (opt.minWidth !== undefined) {
475
+ width = Math.max(width, opt.minWidth);
476
+ }
477
+ // Clamp to available space
478
+ width = Math.max(1, Math.min(width, availWidth));
479
+ // === Resolve maxHeight ===
480
+ let maxHeight = parseSizeValue(opt.maxHeight, termHeight);
481
+ // Clamp to available space
482
+ if (maxHeight !== undefined) {
483
+ maxHeight = Math.max(1, Math.min(maxHeight, availHeight));
484
+ }
485
+ // Effective overlay height (may be clamped by maxHeight)
486
+ const effectiveHeight = maxHeight !== undefined ? Math.min(overlayHeight, maxHeight) : overlayHeight;
487
+ // === Resolve position ===
488
+ let row;
489
+ let col;
490
+ if (opt.row !== undefined) {
491
+ if (typeof opt.row === 'string') {
492
+ // Percentage: 0% = top, 100% = bottom (overlay stays within bounds)
493
+ const match = opt.row.match(/^(\d+(?:\.\d+)?)%$/);
494
+ if (match) {
495
+ const maxRow = Math.max(0, availHeight - effectiveHeight);
496
+ const percent = parseFloat(match[1]) / 100;
497
+ row = marginTop + Math.floor(maxRow * percent);
498
+ }
499
+ else {
500
+ // Invalid format, fall back to center
501
+ row = this.resolveAnchorRow('center', effectiveHeight, availHeight, marginTop);
502
+ }
503
+ }
504
+ else {
505
+ // Absolute row position
506
+ row = opt.row;
507
+ }
508
+ }
509
+ else {
510
+ // Anchor-based (default: center)
511
+ const anchor = opt.anchor ?? 'center';
512
+ row = this.resolveAnchorRow(anchor, effectiveHeight, availHeight, marginTop);
513
+ }
514
+ if (opt.col !== undefined) {
515
+ if (typeof opt.col === 'string') {
516
+ // Percentage: 0% = left, 100% = right (overlay stays within bounds)
517
+ const match = opt.col.match(/^(\d+(?:\.\d+)?)%$/);
518
+ if (match) {
519
+ const maxCol = Math.max(0, availWidth - width);
520
+ const percent = parseFloat(match[1]) / 100;
521
+ col = marginLeft + Math.floor(maxCol * percent);
522
+ }
523
+ else {
524
+ // Invalid format, fall back to center
525
+ col = this.resolveAnchorCol('center', width, availWidth, marginLeft);
526
+ }
527
+ }
528
+ else {
529
+ // Absolute column position
530
+ col = opt.col;
531
+ }
532
+ }
533
+ else {
534
+ // Anchor-based (default: center)
535
+ const anchor = opt.anchor ?? 'center';
536
+ col = this.resolveAnchorCol(anchor, width, availWidth, marginLeft);
537
+ }
538
+ // Apply offsets
539
+ if (opt.offsetY !== undefined)
540
+ row += opt.offsetY;
541
+ if (opt.offsetX !== undefined)
542
+ col += opt.offsetX;
543
+ // Clamp to terminal bounds (respecting margins)
544
+ row = Math.max(marginTop, Math.min(row, termHeight - marginBottom - effectiveHeight));
545
+ col = Math.max(marginLeft, Math.min(col, termWidth - marginRight - width));
546
+ return { width, row, col, maxHeight };
547
+ }
548
+ resolveAnchorRow(anchor, height, availHeight, marginTop) {
549
+ switch (anchor) {
550
+ case 'top-left':
551
+ case 'top-center':
552
+ case 'top-right':
553
+ return marginTop;
554
+ case 'bottom-left':
555
+ case 'bottom-center':
556
+ case 'bottom-right':
557
+ return marginTop + availHeight - height;
558
+ case 'left-center':
559
+ case 'center':
560
+ case 'right-center':
561
+ return marginTop + Math.floor((availHeight - height) / 2);
562
+ }
563
+ }
564
+ resolveAnchorCol(anchor, width, availWidth, marginLeft) {
565
+ switch (anchor) {
566
+ case 'top-left':
567
+ case 'left-center':
568
+ case 'bottom-left':
569
+ return marginLeft;
570
+ case 'top-right':
571
+ case 'right-center':
572
+ case 'bottom-right':
573
+ return marginLeft + availWidth - width;
574
+ case 'top-center':
575
+ case 'center':
576
+ case 'bottom-center':
577
+ return marginLeft + Math.floor((availWidth - width) / 2);
578
+ }
579
+ }
580
+ /** Composite all overlays into content lines (sorted by focusOrder, higher = on top). */
581
+ compositeOverlays(lines, termWidth, termHeight) {
582
+ if (this.overlayStack.length === 0)
583
+ return lines;
584
+ const result = [...lines];
585
+ // Pre-render all visible overlays and calculate positions
586
+ const rendered = [];
587
+ let minLinesNeeded = result.length;
588
+ const visibleEntries = this.overlayStack.filter(e => this.isOverlayVisible(e));
589
+ visibleEntries.sort((a, b) => a.focusOrder - b.focusOrder);
590
+ for (const entry of visibleEntries) {
591
+ const { component, options } = entry;
592
+ // Get layout with height=0 first to determine width and maxHeight
593
+ // (width and maxHeight don't depend on overlay height)
594
+ const { width, maxHeight } = this.resolveOverlayLayout(options, 0, termWidth, termHeight);
595
+ // Render component at calculated width
596
+ let overlayLines = component.render(width);
597
+ // Apply maxHeight if specified
598
+ if (maxHeight !== undefined && overlayLines.length > maxHeight) {
599
+ overlayLines = overlayLines.slice(0, maxHeight);
600
+ }
601
+ // Get final row/col with actual overlay height
602
+ const { row, col } = this.resolveOverlayLayout(options, overlayLines.length, termWidth, termHeight);
603
+ rendered.push({ overlayLines, row, col, w: width });
604
+ minLinesNeeded = Math.max(minLinesNeeded, row + overlayLines.length);
605
+ }
606
+ // Pad to at least terminal height so overlays have screen-relative positions.
607
+ // Excludes maxLinesRendered: the historical high-water mark caused self-reinforcing
608
+ // inflation that pushed content into scrollback on terminal widen.
609
+ const workingHeight = Math.max(result.length, termHeight, minLinesNeeded);
610
+ // Extend result with empty lines if content is too short for overlay placement or working area
611
+ while (result.length < workingHeight) {
612
+ result.push('');
613
+ }
614
+ const viewportStart = Math.max(0, workingHeight - termHeight);
615
+ // Composite each overlay
616
+ for (const { overlayLines, row, col, w } of rendered) {
617
+ for (let i = 0; i < overlayLines.length; i++) {
618
+ const idx = viewportStart + row + i;
619
+ if (idx >= 0 && idx < result.length) {
620
+ // Defensive: truncate overlay line to declared width before compositing
621
+ // (components should already respect width, but this ensures it)
622
+ const truncatedOverlayLine = visibleWidth(overlayLines[i]) > w
623
+ ? sliceByColumn(overlayLines[i], 0, w, true)
624
+ : overlayLines[i];
625
+ result[idx] = this.compositeLineAt(result[idx], truncatedOverlayLine, col, w, termWidth);
626
+ }
627
+ }
628
+ }
629
+ return result;
630
+ }
631
+ static SEGMENT_RESET = '\x1b[0m\x1b]8;;\x07';
632
+ applyLineResets(lines) {
633
+ const reset = TUI.SEGMENT_RESET;
634
+ for (let i = 0; i < lines.length; i++) {
635
+ const line = lines[i];
636
+ if (!isImageLine(line)) {
637
+ lines[i] = normalizeTerminalOutput(line) + reset;
638
+ }
639
+ }
640
+ return lines;
641
+ }
642
+ collectKittyImageIds(lines) {
643
+ const ids = new Set();
644
+ for (const line of lines) {
645
+ for (const id of extractKittyImageIds(line)) {
646
+ ids.add(id);
647
+ }
648
+ }
649
+ return ids;
650
+ }
651
+ deleteKittyImages(ids) {
652
+ let buffer = '';
653
+ for (const id of ids) {
654
+ buffer += deleteKittyImage(id);
655
+ }
656
+ return buffer;
657
+ }
658
+ expandLastChangedForKittyImages(firstChanged, lastChanged) {
659
+ let expandedLastChanged = lastChanged;
660
+ for (let i = firstChanged; i < this.previousLines.length; i++) {
661
+ if (extractKittyImageIds(this.previousLines[i]).length > 0) {
662
+ expandedLastChanged = Math.max(expandedLastChanged, i);
663
+ }
664
+ }
665
+ return expandedLastChanged;
666
+ }
667
+ deleteChangedKittyImages(firstChanged, lastChanged) {
668
+ if (firstChanged < 0 || lastChanged < firstChanged)
669
+ return '';
670
+ const ids = new Set();
671
+ const maxLine = Math.min(lastChanged, this.previousLines.length - 1);
672
+ for (let i = firstChanged; i <= maxLine; i++) {
673
+ for (const id of extractKittyImageIds(this.previousLines[i] ?? '')) {
674
+ ids.add(id);
675
+ }
676
+ }
677
+ return this.deleteKittyImages(ids);
678
+ }
679
+ /** Splice overlay content into a base line at a specific column. Single-pass optimized. */
680
+ compositeLineAt(baseLine, overlayLine, startCol, overlayWidth, totalWidth) {
681
+ if (isImageLine(baseLine))
682
+ return baseLine;
683
+ // Single pass through baseLine extracts both before and after segments
684
+ const afterStart = startCol + overlayWidth;
685
+ const base = extractSegments(baseLine, startCol, afterStart, totalWidth - afterStart, true);
686
+ // Extract overlay with width tracking (strict=true to exclude wide chars at boundary)
687
+ const overlay = sliceWithWidth(overlayLine, 0, overlayWidth, true);
688
+ // Pad segments to target widths
689
+ const beforePad = Math.max(0, startCol - base.beforeWidth);
690
+ const overlayPad = Math.max(0, overlayWidth - overlay.width);
691
+ const actualBeforeWidth = Math.max(startCol, base.beforeWidth);
692
+ const actualOverlayWidth = Math.max(overlayWidth, overlay.width);
693
+ const afterTarget = Math.max(0, totalWidth - actualBeforeWidth - actualOverlayWidth);
694
+ const afterPad = Math.max(0, afterTarget - base.afterWidth);
695
+ // Compose result
696
+ const r = TUI.SEGMENT_RESET;
697
+ const result = base.before +
698
+ ' '.repeat(beforePad) +
699
+ r +
700
+ overlay.text +
701
+ ' '.repeat(overlayPad) +
702
+ r +
703
+ base.after +
704
+ ' '.repeat(afterPad);
705
+ // CRITICAL: Always verify and truncate to terminal width.
706
+ // This is the final safeguard against width overflow which would crash the TUI.
707
+ // Width tracking can drift from actual visible width due to:
708
+ // - Complex ANSI/OSC sequences (hyperlinks, colors)
709
+ // - Wide characters at segment boundaries
710
+ // - Edge cases in segment extraction
711
+ const resultWidth = visibleWidth(result);
712
+ if (resultWidth <= totalWidth) {
713
+ return result;
714
+ }
715
+ // Truncate with strict=true to ensure we don't exceed totalWidth
716
+ return sliceByColumn(result, 0, totalWidth, true);
717
+ }
718
+ /**
719
+ * Find and extract cursor position from rendered lines.
720
+ * Searches for CURSOR_MARKER, calculates its position, and strips it from the output.
721
+ * Only scans the bottom terminal height lines (visible viewport).
722
+ * @param lines - Rendered lines to search
723
+ * @param height - Terminal height (visible viewport size)
724
+ * @returns Cursor position { row, col } or null if no marker found
725
+ */
726
+ extractCursorPosition(lines, height) {
727
+ // Only scan the bottom `height` lines (visible viewport)
728
+ const viewportTop = Math.max(0, lines.length - height);
729
+ for (let row = lines.length - 1; row >= viewportTop; row--) {
730
+ const line = lines[row];
731
+ const markerIndex = line.indexOf(CURSOR_MARKER);
732
+ if (markerIndex !== -1) {
733
+ // Calculate visual column (width of text before marker)
734
+ const beforeMarker = line.slice(0, markerIndex);
735
+ const col = visibleWidth(beforeMarker);
736
+ // Strip marker from the line
737
+ lines[row] = line.slice(0, markerIndex) + line.slice(markerIndex + CURSOR_MARKER.length);
738
+ return { row, col };
739
+ }
740
+ }
741
+ return null;
742
+ }
743
+ doRender() {
744
+ if (this.stopped)
745
+ return;
746
+ const width = this.terminal.columns;
747
+ const height = this.terminal.rows;
748
+ const widthChanged = this.previousWidth !== 0 && this.previousWidth !== width;
749
+ const heightChanged = this.previousHeight !== 0 && this.previousHeight !== height;
750
+ const previousBufferLength = this.previousHeight > 0 ? this.previousViewportTop + this.previousHeight : height;
751
+ let prevViewportTop = heightChanged
752
+ ? Math.max(0, previousBufferLength - height)
753
+ : this.previousViewportTop;
754
+ let viewportTop = prevViewportTop;
755
+ let hardwareCursorRow = this.hardwareCursorRow;
756
+ const computeLineDiff = (targetRow) => {
757
+ const currentScreenRow = hardwareCursorRow - prevViewportTop;
758
+ const targetScreenRow = targetRow - viewportTop;
759
+ return targetScreenRow - currentScreenRow;
760
+ };
761
+ // Render all components to get new lines
762
+ let newLines = this.render(width);
763
+ // Composite overlays into the rendered lines (before differential compare)
764
+ if (this.overlayStack.length > 0) {
765
+ newLines = this.compositeOverlays(newLines, width, height);
766
+ }
767
+ // Extract cursor position before applying line resets (marker must be found first)
768
+ const cursorPos = this.extractCursorPosition(newLines, height);
769
+ newLines = this.applyLineResets(newLines);
770
+ // Helper to clear scrollback and viewport and render all new lines
771
+ const fullRender = (clear) => {
772
+ this.fullRedrawCount += 1;
773
+ let buffer = '\x1b[?2026h'; // Begin synchronized output
774
+ if (clear) {
775
+ buffer += this.deleteKittyImages(this.previousKittyImageIds);
776
+ buffer += '\x1b[2J\x1b[H\x1b[3J'; // Clear screen, home, then clear scrollback
777
+ }
778
+ for (let i = 0; i < newLines.length; i++) {
779
+ if (i > 0)
780
+ buffer += '\r\n';
781
+ buffer += newLines[i];
782
+ }
783
+ buffer += '\x1b[?2026l'; // End synchronized output
784
+ this.terminal.write(buffer);
785
+ this.cursorRow = Math.max(0, newLines.length - 1);
786
+ this.hardwareCursorRow = this.cursorRow;
787
+ // Reset max lines when clearing, otherwise track growth
788
+ if (clear) {
789
+ this.maxLinesRendered = newLines.length;
790
+ }
791
+ else {
792
+ this.maxLinesRendered = Math.max(this.maxLinesRendered, newLines.length);
793
+ }
794
+ const bufferLength = Math.max(height, newLines.length);
795
+ this.previousViewportTop = Math.max(0, bufferLength - height);
796
+ this.positionHardwareCursor(cursorPos, newLines.length);
797
+ this.previousLines = newLines;
798
+ this.previousKittyImageIds = this.collectKittyImageIds(newLines);
799
+ this.previousWidth = width;
800
+ this.previousHeight = height;
801
+ };
802
+ const debugRedraw = process.env.PI_DEBUG_REDRAW === '1';
803
+ const logRedraw = (reason) => {
804
+ if (!debugRedraw)
805
+ return;
806
+ const logPath = path.join(os.homedir(), '.pi', 'agent', 'pi-debug.log');
807
+ const msg = `[${new Date().toISOString()}] fullRender: ${reason} (prev=${this.previousLines.length}, new=${newLines.length}, height=${height})\n`;
808
+ fs.appendFileSync(logPath, msg);
809
+ };
810
+ // First render - just output everything without clearing (assumes clean screen)
811
+ if (this.previousLines.length === 0 && !widthChanged && !heightChanged) {
812
+ logRedraw('first render');
813
+ fullRender(false);
814
+ return;
815
+ }
816
+ // Width changes always need a full re-render because wrapping changes.
817
+ if (widthChanged) {
818
+ logRedraw(`terminal width changed (${this.previousWidth} -> ${width})`);
819
+ fullRender(true);
820
+ return;
821
+ }
822
+ // Height changes normally need a full re-render to keep the visible viewport aligned,
823
+ // but Termux changes height when the software keyboard shows or hides.
824
+ // In that environment, a full redraw causes the entire history to replay on every toggle.
825
+ if (heightChanged && !isTermuxSession()) {
826
+ logRedraw(`terminal height changed (${this.previousHeight} -> ${height})`);
827
+ fullRender(true);
828
+ return;
829
+ }
830
+ // Content shrunk below the working area and no overlays - re-render to clear empty rows
831
+ // (overlays need the padding, so only do this when no overlays are active)
832
+ // Configurable via setClearOnShrink() or PI_CLEAR_ON_SHRINK=0 env var
833
+ if (this.clearOnShrink &&
834
+ newLines.length < this.maxLinesRendered &&
835
+ this.overlayStack.length === 0) {
836
+ logRedraw(`clearOnShrink (maxLinesRendered=${this.maxLinesRendered})`);
837
+ fullRender(true);
838
+ return;
839
+ }
840
+ // Find first and last changed lines
841
+ let firstChanged = -1;
842
+ let lastChanged = -1;
843
+ const maxLines = Math.max(newLines.length, this.previousLines.length);
844
+ for (let i = 0; i < maxLines; i++) {
845
+ const oldLine = i < this.previousLines.length ? this.previousLines[i] : '';
846
+ const newLine = i < newLines.length ? newLines[i] : '';
847
+ if (oldLine !== newLine) {
848
+ if (firstChanged === -1) {
849
+ firstChanged = i;
850
+ }
851
+ lastChanged = i;
852
+ }
853
+ }
854
+ const appendedLines = newLines.length > this.previousLines.length;
855
+ if (appendedLines) {
856
+ if (firstChanged === -1) {
857
+ firstChanged = this.previousLines.length;
858
+ }
859
+ lastChanged = newLines.length - 1;
860
+ }
861
+ if (firstChanged !== -1) {
862
+ lastChanged = this.expandLastChangedForKittyImages(firstChanged, lastChanged);
863
+ }
864
+ const appendStart = appendedLines && firstChanged === this.previousLines.length && firstChanged > 0;
865
+ // No changes - but still need to update hardware cursor position if it moved
866
+ if (firstChanged === -1) {
867
+ this.positionHardwareCursor(cursorPos, newLines.length);
868
+ this.previousViewportTop = prevViewportTop;
869
+ this.previousHeight = height;
870
+ return;
871
+ }
872
+ // All changes are in deleted lines (nothing to render, just clear)
873
+ if (firstChanged >= newLines.length) {
874
+ if (this.previousLines.length > newLines.length) {
875
+ let buffer = '\x1b[?2026h';
876
+ buffer += this.deleteChangedKittyImages(firstChanged, lastChanged);
877
+ // Move to end of new content (clamp to 0 for empty content)
878
+ const targetRow = Math.max(0, newLines.length - 1);
879
+ if (targetRow < prevViewportTop) {
880
+ logRedraw(`deleted lines moved viewport up (${targetRow} < ${prevViewportTop})`);
881
+ fullRender(true);
882
+ return;
883
+ }
884
+ const lineDiff = computeLineDiff(targetRow);
885
+ if (lineDiff > 0)
886
+ buffer += `\x1b[${lineDiff}B`;
887
+ else if (lineDiff < 0)
888
+ buffer += `\x1b[${-lineDiff}A`;
889
+ buffer += '\r';
890
+ // Clear extra lines without scrolling
891
+ const extraLines = this.previousLines.length - newLines.length;
892
+ if (extraLines > height) {
893
+ logRedraw(`extraLines > height (${extraLines} > ${height})`);
894
+ fullRender(true);
895
+ return;
896
+ }
897
+ if (extraLines > 0) {
898
+ buffer += '\x1b[1B';
899
+ }
900
+ for (let i = 0; i < extraLines; i++) {
901
+ buffer += '\r\x1b[2K';
902
+ if (i < extraLines - 1)
903
+ buffer += '\x1b[1B';
904
+ }
905
+ if (extraLines > 0) {
906
+ buffer += `\x1b[${extraLines}A`;
907
+ }
908
+ buffer += '\x1b[?2026l';
909
+ this.terminal.write(buffer);
910
+ this.cursorRow = targetRow;
911
+ this.hardwareCursorRow = targetRow;
912
+ }
913
+ this.positionHardwareCursor(cursorPos, newLines.length);
914
+ this.previousLines = newLines;
915
+ this.previousKittyImageIds = this.collectKittyImageIds(newLines);
916
+ this.previousWidth = width;
917
+ this.previousHeight = height;
918
+ this.previousViewportTop = prevViewportTop;
919
+ return;
920
+ }
921
+ // Differential rendering can only touch what was actually visible.
922
+ // If the first changed line is above the previous viewport, we need a full redraw.
923
+ if (firstChanged < prevViewportTop) {
924
+ logRedraw(`firstChanged < viewportTop (${firstChanged} < ${prevViewportTop})`);
925
+ fullRender(true);
926
+ return;
927
+ }
928
+ // Render from first changed line to end
929
+ // Build buffer with all updates wrapped in synchronized output
930
+ let buffer = '\x1b[?2026h'; // Begin synchronized output
931
+ buffer += this.deleteChangedKittyImages(firstChanged, lastChanged);
932
+ const prevViewportBottom = prevViewportTop + height - 1;
933
+ const moveTargetRow = appendStart ? firstChanged - 1 : firstChanged;
934
+ if (moveTargetRow > prevViewportBottom) {
935
+ const currentScreenRow = Math.max(0, Math.min(height - 1, hardwareCursorRow - prevViewportTop));
936
+ const moveToBottom = height - 1 - currentScreenRow;
937
+ if (moveToBottom > 0) {
938
+ buffer += `\x1b[${moveToBottom}B`;
939
+ }
940
+ const scroll = moveTargetRow - prevViewportBottom;
941
+ buffer += '\r\n'.repeat(scroll);
942
+ prevViewportTop += scroll;
943
+ viewportTop += scroll;
944
+ hardwareCursorRow = moveTargetRow;
945
+ }
946
+ // Move cursor to first changed line (use hardwareCursorRow for actual position)
947
+ const lineDiff = computeLineDiff(moveTargetRow);
948
+ if (lineDiff > 0) {
949
+ buffer += `\x1b[${lineDiff}B`; // Move down
950
+ }
951
+ else if (lineDiff < 0) {
952
+ buffer += `\x1b[${-lineDiff}A`; // Move up
953
+ }
954
+ buffer += appendStart ? '\r\n' : '\r'; // Move to column 0
955
+ // Only render changed lines (firstChanged to lastChanged), not all lines to end
956
+ // This reduces flicker when only a single line changes (e.g., spinner animation)
957
+ const renderEnd = Math.min(lastChanged, newLines.length - 1);
958
+ for (let i = firstChanged; i <= renderEnd; i++) {
959
+ if (i > firstChanged)
960
+ buffer += '\r\n';
961
+ buffer += '\x1b[2K'; // Clear current line
962
+ const line = newLines[i];
963
+ const isImage = isImageLine(line);
964
+ if (!isImage && visibleWidth(line) > width) {
965
+ // Log all lines to crash file for debugging
966
+ const crashLogPath = path.join(os.homedir(), '.pi', 'agent', 'pi-crash.log');
967
+ const crashData = [
968
+ `Crash at ${new Date().toISOString()}`,
969
+ `Terminal width: ${width}`,
970
+ `Line ${i} visible width: ${visibleWidth(line)}`,
971
+ '',
972
+ '=== All rendered lines ===',
973
+ ...newLines.map((l, idx) => `[${idx}] (w=${visibleWidth(l)}) ${l}`),
974
+ '',
975
+ ].join('\n');
976
+ fs.mkdirSync(path.dirname(crashLogPath), { recursive: true });
977
+ fs.writeFileSync(crashLogPath, crashData);
978
+ // Clean up terminal state before throwing
979
+ this.stop();
980
+ const errorMsg = [
981
+ `Rendered line ${i} exceeds terminal width (${visibleWidth(line)} > ${width}).`,
982
+ '',
983
+ 'This is likely caused by a custom TUI component not truncating its output.',
984
+ 'Use visibleWidth() to measure and truncateToWidth() to truncate lines.',
985
+ '',
986
+ `Debug log written to: ${crashLogPath}`,
987
+ ].join('\n');
988
+ throw new Error(errorMsg);
989
+ }
990
+ buffer += line;
991
+ }
992
+ // Track where cursor ended up after rendering
993
+ let finalCursorRow = renderEnd;
994
+ // If we had more lines before, clear them and move cursor back
995
+ if (this.previousLines.length > newLines.length) {
996
+ // Move to end of new content first if we stopped before it
997
+ if (renderEnd < newLines.length - 1) {
998
+ const moveDown = newLines.length - 1 - renderEnd;
999
+ buffer += `\x1b[${moveDown}B`;
1000
+ finalCursorRow = newLines.length - 1;
1001
+ }
1002
+ const extraLines = this.previousLines.length - newLines.length;
1003
+ for (let i = newLines.length; i < this.previousLines.length; i++) {
1004
+ buffer += '\r\n\x1b[2K';
1005
+ }
1006
+ // Move cursor back to end of new content
1007
+ buffer += `\x1b[${extraLines}A`;
1008
+ }
1009
+ buffer += '\x1b[?2026l'; // End synchronized output
1010
+ if (process.env.PI_TUI_DEBUG === '1') {
1011
+ const debugDir = '/tmp/tui';
1012
+ fs.mkdirSync(debugDir, { recursive: true });
1013
+ const debugPath = path.join(debugDir, `render-${Date.now()}-${Math.random().toString(36).slice(2)}.log`);
1014
+ const debugData = [
1015
+ `firstChanged: ${firstChanged}`,
1016
+ `viewportTop: ${viewportTop}`,
1017
+ `cursorRow: ${this.cursorRow}`,
1018
+ `height: ${height}`,
1019
+ `lineDiff: ${lineDiff}`,
1020
+ `hardwareCursorRow: ${hardwareCursorRow}`,
1021
+ `renderEnd: ${renderEnd}`,
1022
+ `finalCursorRow: ${finalCursorRow}`,
1023
+ `cursorPos: ${JSON.stringify(cursorPos)}`,
1024
+ `newLines.length: ${newLines.length}`,
1025
+ `previousLines.length: ${this.previousLines.length}`,
1026
+ '',
1027
+ '=== newLines ===',
1028
+ JSON.stringify(newLines, null, 2),
1029
+ '',
1030
+ '=== previousLines ===',
1031
+ JSON.stringify(this.previousLines, null, 2),
1032
+ '',
1033
+ '=== buffer ===',
1034
+ JSON.stringify(buffer),
1035
+ ].join('\n');
1036
+ fs.writeFileSync(debugPath, debugData);
1037
+ }
1038
+ // Write entire buffer at once
1039
+ this.terminal.write(buffer);
1040
+ // Track cursor position for next render
1041
+ // cursorRow tracks end of content (for viewport calculation)
1042
+ // hardwareCursorRow tracks actual terminal cursor position (for movement)
1043
+ this.cursorRow = Math.max(0, newLines.length - 1);
1044
+ this.hardwareCursorRow = finalCursorRow;
1045
+ // Track terminal's working area (grows but doesn't shrink unless cleared)
1046
+ this.maxLinesRendered = Math.max(this.maxLinesRendered, newLines.length);
1047
+ this.previousViewportTop = Math.max(prevViewportTop, finalCursorRow - height + 1);
1048
+ // Position hardware cursor for IME
1049
+ this.positionHardwareCursor(cursorPos, newLines.length);
1050
+ this.previousLines = newLines;
1051
+ this.previousKittyImageIds = this.collectKittyImageIds(newLines);
1052
+ this.previousWidth = width;
1053
+ this.previousHeight = height;
1054
+ }
1055
+ /**
1056
+ * Position the hardware cursor for IME candidate window.
1057
+ * @param cursorPos The cursor position extracted from rendered output, or null
1058
+ * @param totalLines Total number of rendered lines
1059
+ */
1060
+ positionHardwareCursor(cursorPos, totalLines) {
1061
+ if (!cursorPos || totalLines <= 0) {
1062
+ this.terminal.hideCursor();
1063
+ return;
1064
+ }
1065
+ // Clamp cursor position to valid range
1066
+ const targetRow = Math.max(0, Math.min(cursorPos.row, totalLines - 1));
1067
+ const targetCol = Math.max(0, cursorPos.col);
1068
+ // Move cursor from current position to target
1069
+ const rowDelta = targetRow - this.hardwareCursorRow;
1070
+ let buffer = '';
1071
+ if (rowDelta > 0) {
1072
+ buffer += `\x1b[${rowDelta}B`; // Move down
1073
+ }
1074
+ else if (rowDelta < 0) {
1075
+ buffer += `\x1b[${-rowDelta}A`; // Move up
1076
+ }
1077
+ // Move to absolute column (1-indexed)
1078
+ buffer += `\x1b[${targetCol + 1}G`;
1079
+ if (buffer) {
1080
+ this.terminal.write(buffer);
1081
+ }
1082
+ this.hardwareCursorRow = targetRow;
1083
+ if (this.showHardwareCursor) {
1084
+ this.terminal.showCursor();
1085
+ }
1086
+ else {
1087
+ this.terminal.hideCursor();
1088
+ }
1089
+ }
1090
+ }
1091
+ //# sourceMappingURL=tui.js.map