@dungle-scrubs/tallow 0.8.21 → 0.8.23

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