tui-render.test.ts 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591
  1. import assert from "node:assert";
  2. import { describe, it } from "node:test";
  3. import type { Terminal as XtermTerminalType } from "@xterm/headless";
  4. import { deleteKittyImage, encodeKitty } from "../src/terminal-image.ts";
  5. import { type Component, TUI } from "../src/tui.ts";
  6. import { VirtualTerminal } from "./virtual-terminal.ts";
  7. class TestComponent implements Component {
  8. lines: string[] = [];
  9. render(_width: number): string[] {
  10. return this.lines;
  11. }
  12. invalidate(): void {}
  13. }
  14. class LoggingVirtualTerminal extends VirtualTerminal {
  15. private writes: string[] = [];
  16. override write(data: string): void {
  17. this.writes.push(data);
  18. super.write(data);
  19. }
  20. getWrites(): string {
  21. return this.writes.join("");
  22. }
  23. clearWrites(): void {
  24. this.writes = [];
  25. }
  26. }
  27. async function withEnv<T>(updates: Record<string, string | undefined>, run: () => Promise<T>): Promise<T> {
  28. const previousValues = new Map<string, string | undefined>();
  29. for (const [key, value] of Object.entries(updates)) {
  30. previousValues.set(key, process.env[key]);
  31. if (value === undefined) {
  32. delete process.env[key];
  33. } else {
  34. process.env[key] = value;
  35. }
  36. }
  37. try {
  38. return await run();
  39. } finally {
  40. for (const [key, value] of previousValues) {
  41. if (value === undefined) {
  42. delete process.env[key];
  43. } else {
  44. process.env[key] = value;
  45. }
  46. }
  47. }
  48. }
  49. function getCellItalic(terminal: VirtualTerminal, row: number, col: number): number {
  50. const xterm = (terminal as unknown as { xterm: XtermTerminalType }).xterm;
  51. const buffer = xterm.buffer.active;
  52. const line = buffer.getLine(buffer.viewportY + row);
  53. assert.ok(line, `Missing buffer line at row ${row}`);
  54. const cell = line.getCell(col);
  55. assert.ok(cell, `Missing cell at row ${row} col ${col}`);
  56. return cell.isItalic();
  57. }
  58. describe("TUI Kitty image cleanup", () => {
  59. it("deletes changed image ids before drawing moved placements", async () => {
  60. const terminal = new LoggingVirtualTerminal(40, 10);
  61. const tui = new TUI(terminal);
  62. const component = new TestComponent();
  63. tui.addChild(component);
  64. const oldImage = encodeKitty("AAAA", { columns: 2, rows: 2, imageId: 42, moveCursor: false });
  65. component.lines = ["top", oldImage];
  66. tui.start();
  67. await terminal.waitForRender();
  68. terminal.clearWrites();
  69. const newImage = encodeKitty("BBBB", { columns: 2, rows: 1, imageId: 42, moveCursor: false });
  70. component.lines = [newImage, ""];
  71. tui.requestRender();
  72. await terminal.waitForRender();
  73. const writes = terminal.getWrites();
  74. const deleteIndex = writes.indexOf(deleteKittyImage(42));
  75. const drawIndex = writes.indexOf(newImage);
  76. assert.ok(deleteIndex >= 0, "changed old image should be deleted");
  77. assert.ok(drawIndex >= 0, "new image should be drawn");
  78. assert.ok(deleteIndex < drawIndex, "old image must be deleted before the new placement is drawn");
  79. tui.stop();
  80. });
  81. it("redraws image lines when an earlier reserved image row changes", async () => {
  82. const terminal = new LoggingVirtualTerminal(40, 10);
  83. const tui = new TUI(terminal);
  84. const component = new TestComponent();
  85. tui.addChild(component);
  86. const image = encodeKitty("AAAA", { columns: 2, rows: 2, imageId: 88, moveCursor: false });
  87. component.lines = ["", image];
  88. tui.start();
  89. await terminal.waitForRender();
  90. terminal.clearWrites();
  91. component.lines = ["covered", image];
  92. tui.requestRender();
  93. await terminal.waitForRender();
  94. const writes = terminal.getWrites();
  95. const deleteIndex = writes.indexOf(deleteKittyImage(88));
  96. const drawIndex = writes.indexOf(image);
  97. assert.ok(deleteIndex >= 0, "image should be deleted when a reserved row changes");
  98. assert.ok(drawIndex >= 0, "unchanged image line should be redrawn after deleting the placement");
  99. assert.ok(deleteIndex < drawIndex, "old placement must be deleted before the image line is redrawn");
  100. assert.ok(!writes.includes("\x1b[2J"), "reserved row changes should not force a full redraw");
  101. tui.stop();
  102. });
  103. it("deletes previously rendered image ids during full redraws", async () => {
  104. const terminal = new LoggingVirtualTerminal(40, 10);
  105. const tui = new TUI(terminal);
  106. const component = new TestComponent();
  107. tui.addChild(component);
  108. component.lines = [encodeKitty("AAAA", { columns: 2, rows: 2, imageId: 77, moveCursor: false })];
  109. tui.start();
  110. await terminal.waitForRender();
  111. terminal.clearWrites();
  112. component.lines = ["plain text"];
  113. tui.requestRender(true);
  114. await terminal.waitForRender();
  115. const writes = terminal.getWrites();
  116. const deleteIndex = writes.indexOf(deleteKittyImage(77));
  117. const clearIndex = writes.indexOf("\x1b[2J");
  118. assert.ok(deleteIndex >= 0, "previous image should be deleted during full redraw");
  119. assert.ok(clearIndex >= 0, "full redraw should clear the screen");
  120. assert.ok(deleteIndex < clearIndex, "old image should be deleted before the screen is cleared");
  121. tui.stop();
  122. });
  123. });
  124. describe("TUI resize handling", () => {
  125. it("triggers full re-render when terminal height changes", async () => {
  126. await withEnv({ TERMUX_VERSION: undefined }, async () => {
  127. const terminal = new VirtualTerminal(40, 10);
  128. const tui = new TUI(terminal);
  129. const component = new TestComponent();
  130. tui.addChild(component);
  131. component.lines = ["Line 0", "Line 1", "Line 2"];
  132. tui.start();
  133. await terminal.waitForRender();
  134. const initialRedraws = tui.fullRedraws;
  135. // Resize height
  136. terminal.resize(40, 15);
  137. await terminal.waitForRender();
  138. // Should have triggered a full redraw
  139. assert.ok(tui.fullRedraws > initialRedraws, "Height change should trigger full redraw");
  140. const viewport = terminal.getViewport();
  141. assert.ok(viewport[0]?.includes("Line 0"), "Content preserved after height change");
  142. tui.stop();
  143. });
  144. });
  145. it("skips full re-render on height changes in Termux", async () => {
  146. await withEnv({ TERMUX_VERSION: "1" }, async () => {
  147. const terminal = new LoggingVirtualTerminal(40, 10);
  148. const tui = new TUI(terminal);
  149. const component = new TestComponent();
  150. tui.addChild(component);
  151. component.lines = Array.from({ length: 20 }, (_, i) => `Line ${i}`);
  152. tui.start();
  153. await terminal.waitForRender();
  154. terminal.clearWrites();
  155. const initialRedraws = tui.fullRedraws;
  156. for (const height of [15, 8, 14, 11]) {
  157. terminal.resize(40, height);
  158. await terminal.waitForRender();
  159. }
  160. assert.strictEqual(tui.fullRedraws, initialRedraws, "Height change should not trigger full redraw");
  161. assert.ok(!terminal.getWrites().includes("\x1b[2J"), "Height change should not clear the screen");
  162. assert.ok(!terminal.getWrites().includes("\x1b[3J"), "Height change should not clear scrollback");
  163. const viewport = terminal.getViewport();
  164. assert.ok(viewport.join("\n").includes("Line 19"), "Latest content remains visible after resize");
  165. tui.stop();
  166. });
  167. });
  168. it("triggers full re-render when terminal width changes", async () => {
  169. const terminal = new VirtualTerminal(40, 10);
  170. const tui = new TUI(terminal);
  171. const component = new TestComponent();
  172. tui.addChild(component);
  173. component.lines = ["Line 0", "Line 1", "Line 2"];
  174. tui.start();
  175. await terminal.waitForRender();
  176. const initialRedraws = tui.fullRedraws;
  177. // Resize width
  178. terminal.resize(60, 10);
  179. await terminal.waitForRender();
  180. // Should have triggered a full redraw
  181. assert.ok(tui.fullRedraws > initialRedraws, "Width change should trigger full redraw");
  182. tui.stop();
  183. });
  184. });
  185. describe("TUI content shrinkage", () => {
  186. it("clears empty rows when content shrinks significantly", async () => {
  187. const terminal = new VirtualTerminal(40, 10);
  188. const tui = new TUI(terminal);
  189. tui.setClearOnShrink(true); // Explicitly enable (may be disabled via env var)
  190. const component = new TestComponent();
  191. tui.addChild(component);
  192. // Start with many lines
  193. component.lines = ["Line 0", "Line 1", "Line 2", "Line 3", "Line 4", "Line 5"];
  194. tui.start();
  195. await terminal.waitForRender();
  196. const initialRedraws = tui.fullRedraws;
  197. // Shrink to fewer lines
  198. component.lines = ["Line 0", "Line 1"];
  199. tui.requestRender();
  200. await terminal.waitForRender();
  201. // Should have triggered a full redraw to clear empty rows
  202. assert.ok(tui.fullRedraws > initialRedraws, "Content shrinkage should trigger full redraw");
  203. const viewport = terminal.getViewport();
  204. assert.ok(viewport[0]?.includes("Line 0"), "First line preserved");
  205. assert.ok(viewport[1]?.includes("Line 1"), "Second line preserved");
  206. // Lines below should be empty (cleared)
  207. assert.strictEqual(viewport[2]?.trim(), "", "Line 2 should be cleared");
  208. assert.strictEqual(viewport[3]?.trim(), "", "Line 3 should be cleared");
  209. tui.stop();
  210. });
  211. it("handles shrink to single line", async () => {
  212. const terminal = new VirtualTerminal(40, 10);
  213. const tui = new TUI(terminal);
  214. tui.setClearOnShrink(true); // Explicitly enable (may be disabled via env var)
  215. const component = new TestComponent();
  216. tui.addChild(component);
  217. component.lines = ["Line 0", "Line 1", "Line 2", "Line 3"];
  218. tui.start();
  219. await terminal.waitForRender();
  220. // Shrink to single line
  221. component.lines = ["Only line"];
  222. tui.requestRender();
  223. await terminal.waitForRender();
  224. const viewport = terminal.getViewport();
  225. assert.ok(viewport[0]?.includes("Only line"), "Single line rendered");
  226. assert.strictEqual(viewport[1]?.trim(), "", "Line 1 should be cleared");
  227. tui.stop();
  228. });
  229. it("handles shrink to empty", async () => {
  230. const terminal = new VirtualTerminal(40, 10);
  231. const tui = new TUI(terminal);
  232. tui.setClearOnShrink(true); // Explicitly enable (may be disabled via env var)
  233. const component = new TestComponent();
  234. tui.addChild(component);
  235. component.lines = ["Line 0", "Line 1", "Line 2"];
  236. tui.start();
  237. await terminal.waitForRender();
  238. // Shrink to empty
  239. component.lines = [];
  240. tui.requestRender();
  241. await terminal.waitForRender();
  242. const viewport = terminal.getViewport();
  243. // All lines should be empty
  244. assert.strictEqual(viewport[0]?.trim(), "", "Line 0 should be cleared");
  245. assert.strictEqual(viewport[1]?.trim(), "", "Line 1 should be cleared");
  246. tui.stop();
  247. });
  248. });
  249. describe("TUI differential rendering", () => {
  250. it("tracks cursor correctly when content shrinks with unchanged remaining lines", async () => {
  251. const terminal = new VirtualTerminal(40, 10);
  252. const tui = new TUI(terminal);
  253. const component = new TestComponent();
  254. tui.addChild(component);
  255. // Initial render: 5 identical lines
  256. component.lines = ["Line 0", "Line 1", "Line 2", "Line 3", "Line 4"];
  257. tui.start();
  258. await terminal.waitForRender();
  259. // Shrink to 3 lines, all identical to before (no content changes in remaining lines)
  260. component.lines = ["Line 0", "Line 1", "Line 2"];
  261. tui.requestRender();
  262. await terminal.waitForRender();
  263. // cursorRow should be 2 (last line of new content)
  264. // Verify by doing another render with a change on line 1
  265. component.lines = ["Line 0", "CHANGED", "Line 2"];
  266. tui.requestRender();
  267. await terminal.waitForRender();
  268. const viewport = terminal.getViewport();
  269. // Line 1 should show "CHANGED", proving cursor tracking was correct
  270. assert.ok(viewport[1]?.includes("CHANGED"), `Expected "CHANGED" on line 1, got: ${viewport[1]}`);
  271. tui.stop();
  272. });
  273. it("renders correctly when only a middle line changes (spinner case)", async () => {
  274. const terminal = new VirtualTerminal(40, 10);
  275. const tui = new TUI(terminal);
  276. const component = new TestComponent();
  277. tui.addChild(component);
  278. // Initial render
  279. component.lines = ["Header", "Working...", "Footer"];
  280. tui.start();
  281. await terminal.waitForRender();
  282. // Simulate spinner animation - only middle line changes
  283. const spinnerFrames = ["|", "/", "-", "\\"];
  284. for (const frame of spinnerFrames) {
  285. component.lines = ["Header", `Working ${frame}`, "Footer"];
  286. tui.requestRender();
  287. await terminal.waitForRender();
  288. const viewport = terminal.getViewport();
  289. assert.ok(viewport[0]?.includes("Header"), `Header preserved: ${viewport[0]}`);
  290. assert.ok(viewport[1]?.includes(`Working ${frame}`), `Spinner updated: ${viewport[1]}`);
  291. assert.ok(viewport[2]?.includes("Footer"), `Footer preserved: ${viewport[2]}`);
  292. }
  293. tui.stop();
  294. });
  295. it("resets styles after each rendered line", async () => {
  296. const terminal = new VirtualTerminal(20, 6);
  297. const tui = new TUI(terminal);
  298. const component = new TestComponent();
  299. tui.addChild(component);
  300. component.lines = ["\x1b[3mItalic", "Plain"];
  301. tui.start();
  302. await terminal.waitForRender();
  303. assert.strictEqual(getCellItalic(terminal, 1, 0), 0);
  304. tui.stop();
  305. });
  306. it("renders correctly when first line changes but rest stays same", async () => {
  307. const terminal = new VirtualTerminal(40, 10);
  308. const tui = new TUI(terminal);
  309. const component = new TestComponent();
  310. tui.addChild(component);
  311. component.lines = ["Line 0", "Line 1", "Line 2", "Line 3"];
  312. tui.start();
  313. await terminal.waitForRender();
  314. // Change only first line
  315. component.lines = ["CHANGED", "Line 1", "Line 2", "Line 3"];
  316. tui.requestRender();
  317. await terminal.waitForRender();
  318. const viewport = terminal.getViewport();
  319. assert.ok(viewport[0]?.includes("CHANGED"), `First line changed: ${viewport[0]}`);
  320. assert.ok(viewport[1]?.includes("Line 1"), `Line 1 preserved: ${viewport[1]}`);
  321. assert.ok(viewport[2]?.includes("Line 2"), `Line 2 preserved: ${viewport[2]}`);
  322. assert.ok(viewport[3]?.includes("Line 3"), `Line 3 preserved: ${viewport[3]}`);
  323. tui.stop();
  324. });
  325. it("renders correctly when last line changes but rest stays same", async () => {
  326. const terminal = new VirtualTerminal(40, 10);
  327. const tui = new TUI(terminal);
  328. const component = new TestComponent();
  329. tui.addChild(component);
  330. component.lines = ["Line 0", "Line 1", "Line 2", "Line 3"];
  331. tui.start();
  332. await terminal.waitForRender();
  333. // Change only last line
  334. component.lines = ["Line 0", "Line 1", "Line 2", "CHANGED"];
  335. tui.requestRender();
  336. await terminal.waitForRender();
  337. const viewport = terminal.getViewport();
  338. assert.ok(viewport[0]?.includes("Line 0"), `Line 0 preserved: ${viewport[0]}`);
  339. assert.ok(viewport[1]?.includes("Line 1"), `Line 1 preserved: ${viewport[1]}`);
  340. assert.ok(viewport[2]?.includes("Line 2"), `Line 2 preserved: ${viewport[2]}`);
  341. assert.ok(viewport[3]?.includes("CHANGED"), `Last line changed: ${viewport[3]}`);
  342. tui.stop();
  343. });
  344. it("renders correctly when multiple non-adjacent lines change", async () => {
  345. const terminal = new VirtualTerminal(40, 10);
  346. const tui = new TUI(terminal);
  347. const component = new TestComponent();
  348. tui.addChild(component);
  349. component.lines = ["Line 0", "Line 1", "Line 2", "Line 3", "Line 4"];
  350. tui.start();
  351. await terminal.waitForRender();
  352. // Change lines 1 and 3, keep 0, 2, 4 the same
  353. component.lines = ["Line 0", "CHANGED 1", "Line 2", "CHANGED 3", "Line 4"];
  354. tui.requestRender();
  355. await terminal.waitForRender();
  356. const viewport = terminal.getViewport();
  357. assert.ok(viewport[0]?.includes("Line 0"), `Line 0 preserved: ${viewport[0]}`);
  358. assert.ok(viewport[1]?.includes("CHANGED 1"), `Line 1 changed: ${viewport[1]}`);
  359. assert.ok(viewport[2]?.includes("Line 2"), `Line 2 preserved: ${viewport[2]}`);
  360. assert.ok(viewport[3]?.includes("CHANGED 3"), `Line 3 changed: ${viewport[3]}`);
  361. assert.ok(viewport[4]?.includes("Line 4"), `Line 4 preserved: ${viewport[4]}`);
  362. tui.stop();
  363. });
  364. it("handles transition from content to empty and back to content", async () => {
  365. const terminal = new VirtualTerminal(40, 10);
  366. const tui = new TUI(terminal);
  367. const component = new TestComponent();
  368. tui.addChild(component);
  369. // Start with content
  370. component.lines = ["Line 0", "Line 1", "Line 2"];
  371. tui.start();
  372. await terminal.waitForRender();
  373. let viewport = terminal.getViewport();
  374. assert.ok(viewport[0]?.includes("Line 0"), "Initial content rendered");
  375. // Clear to empty
  376. component.lines = [];
  377. tui.requestRender();
  378. await terminal.waitForRender();
  379. // Add content back - this should work correctly even after empty state
  380. component.lines = ["New Line 0", "New Line 1"];
  381. tui.requestRender();
  382. await terminal.waitForRender();
  383. viewport = terminal.getViewport();
  384. assert.ok(viewport[0]?.includes("New Line 0"), `New content rendered: ${viewport[0]}`);
  385. assert.ok(viewport[1]?.includes("New Line 1"), `New content line 1: ${viewport[1]}`);
  386. tui.stop();
  387. });
  388. it("full re-renders when deleted lines move the viewport upward", async () => {
  389. const terminal = new VirtualTerminal(20, 5);
  390. const tui = new TUI(terminal);
  391. const component = new TestComponent();
  392. tui.addChild(component);
  393. component.lines = Array.from({ length: 12 }, (_, i) => `Line ${i}`);
  394. tui.start();
  395. await terminal.waitForRender();
  396. const initialRedraws = tui.fullRedraws;
  397. component.lines = Array.from({ length: 7 }, (_, i) => `Line ${i}`);
  398. tui.requestRender();
  399. await terminal.waitForRender();
  400. assert.ok(tui.fullRedraws > initialRedraws, "Shrink should trigger a full redraw");
  401. assert.deepStrictEqual(terminal.getViewport(), ["Line 2", "Line 3", "Line 4", "Line 5", "Line 6"]);
  402. tui.stop();
  403. });
  404. it("appends after a shrink without another full redraw once the viewport is reset", async () => {
  405. const terminal = new VirtualTerminal(20, 5);
  406. const tui = new TUI(terminal);
  407. const component = new TestComponent();
  408. tui.addChild(component);
  409. component.lines = Array.from({ length: 8 }, (_, i) => `Line ${i}`);
  410. tui.start();
  411. await terminal.waitForRender();
  412. const initialRedraws = tui.fullRedraws;
  413. component.lines = ["Line 0", "Line 1"];
  414. tui.requestRender();
  415. await terminal.waitForRender();
  416. assert.ok(tui.fullRedraws > initialRedraws, "Shrink should reset the viewport with a full redraw");
  417. const redrawsAfterShrink = tui.fullRedraws;
  418. component.lines = ["Line 0", "Line 1", "Line 2"];
  419. tui.requestRender();
  420. await terminal.waitForRender();
  421. assert.strictEqual(tui.fullRedraws, redrawsAfterShrink, "Append should stay on the differential path");
  422. assert.deepStrictEqual(terminal.getViewport(), ["Line 0", "Line 1", "Line 2", "", ""]);
  423. tui.stop();
  424. });
  425. it("clears stale content when maxLinesRendered was inflated by a transient component", async () => {
  426. const terminal = new VirtualTerminal(40, 10);
  427. const tui = new TUI(terminal);
  428. const chat = new TestComponent();
  429. const editor = new TestComponent();
  430. tui.addChild(chat);
  431. tui.addChild(editor);
  432. const longChat = Array.from({ length: 15 }, (_, i) => `Chat ${i}`);
  433. const shortChat = Array.from({ length: 12 }, (_, i) => `Chat ${i}`);
  434. const editorLines = ["Editor 0", "Editor 1", "Editor 2"];
  435. const selectorLines = Array.from({ length: 8 }, (_, i) => `Selector ${i}`);
  436. chat.lines = longChat;
  437. editor.lines = editorLines;
  438. tui.start();
  439. await terminal.waitForRender();
  440. editor.lines = selectorLines;
  441. tui.requestRender();
  442. await terminal.waitForRender();
  443. editor.lines = editorLines;
  444. tui.requestRender();
  445. await terminal.waitForRender();
  446. const redrawsBeforeSwitch = tui.fullRedraws;
  447. chat.lines = shortChat;
  448. tui.requestRender();
  449. await terminal.waitForRender();
  450. assert.ok(tui.fullRedraws > redrawsBeforeSwitch, "Branch switch should trigger a full redraw");
  451. const viewport = terminal.getViewport();
  452. for (let i = 0; i < 10; i++) {
  453. const line = viewport[i] ?? "";
  454. assert.ok(!line.includes("Chat 12"), `Stale "Chat 12" at viewport row ${i}`);
  455. assert.ok(!line.includes("Chat 13"), `Stale "Chat 13" at viewport row ${i}`);
  456. assert.ok(!line.includes("Chat 14"), `Stale "Chat 14" at viewport row ${i}`);
  457. }
  458. assert.deepStrictEqual(viewport, [
  459. "Chat 5",
  460. "Chat 6",
  461. "Chat 7",
  462. "Chat 8",
  463. "Chat 9",
  464. "Chat 10",
  465. "Chat 11",
  466. "Editor 0",
  467. "Editor 1",
  468. "Editor 2",
  469. ]);
  470. tui.stop();
  471. });
  472. });