tui.ts 50 KB

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