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