tui-engine-local-deltas.test.ts 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375
  1. import { describe, expect, it } from 'vitest';
  2. import {
  3. CURSOR_MARKER,
  4. Editor,
  5. Input,
  6. SelectList,
  7. Text,
  8. TuiMainScreen,
  9. type Component,
  10. type TUI,
  11. visibleWidth,
  12. } from '../../src/tui/engine/public.js';
  13. import { VirtualTerminal } from '../pi-084-upstream/virtual-terminal.js';
  14. const passthrough = (value: string): string => value;
  15. const selectListTheme = {
  16. selectedPrefix: passthrough,
  17. selectedText: passthrough,
  18. description: passthrough,
  19. scrollInfo: passthrough,
  20. noMatch: passthrough,
  21. };
  22. class RecordingVirtualTerminal extends VirtualTerminal {
  23. private writes: string[] = [];
  24. override write(data: string): void {
  25. this.writes.push(data);
  26. super.write(data);
  27. }
  28. takeWrites(): string {
  29. const output = this.writes.join('');
  30. this.writes = [];
  31. return output;
  32. }
  33. }
  34. class MutableLines implements Component {
  35. lines: string[] = [];
  36. render(): string[] {
  37. return [...this.lines];
  38. }
  39. invalidate(): void {}
  40. }
  41. describe('MCode Pi Engine local deltas', () => {
  42. it('fits Text padding within narrow terminal widths', () => {
  43. const text = new Text('content', 2, 0);
  44. for (const width of [1, 2, 3, 4]) {
  45. expect(text.render(width).every((line) => visibleWidth(line) <= width)).toBe(true);
  46. }
  47. });
  48. it('rebuilds when a transient collapse changes rows already in scrollback', async () => {
  49. const terminal = new RecordingVirtualTerminal(40, 5);
  50. const tui = new TuiMainScreen(terminal);
  51. const component = new MutableLines();
  52. component.lines = [
  53. 'header',
  54. 'activity-1',
  55. 'activity-2',
  56. 'activity-3',
  57. 'activity-4',
  58. 'status',
  59. 'composer',
  60. ];
  61. tui.addChild(component);
  62. tui.renderNow();
  63. await terminal.flush();
  64. terminal.takeWrites();
  65. component.lines = ['header', 'status', 'composer'];
  66. tui.renderNow();
  67. await terminal.flush();
  68. const writes = terminal.takeWrites();
  69. expect(writes).toContain('\x1b[2J\x1b[H');
  70. expect(writes).toContain('\x1b[3J');
  71. expect(terminal.getScrollBuffer()).not.toContain('activity-1');
  72. expect(terminal.getViewport()).toEqual(['header', 'status', 'composer', '', '']);
  73. expect(terminal.getScrollBuffer().filter((line) => line === 'header')).toHaveLength(1);
  74. expect(tui.fullRedraws).toBe(2);
  75. });
  76. it('does not replay scrolled answer rows after a narrow terminal frame shrinks', async () => {
  77. const terminal = new RecordingVirtualTerminal(67, 44);
  78. const tui = new TuiMainScreen(terminal);
  79. const component = new MutableLines();
  80. const answer = Array.from({ length: 80 }, (_, index) => `Answer line ${index}`);
  81. component.lines = [...answer, 'activity', `composer${CURSOR_MARKER}`, 'status'];
  82. tui.addChild(component);
  83. tui.renderNow();
  84. await terminal.flush();
  85. // Settle the activity row, then repaint a historical line (for example Markdown styling).
  86. terminal.takeWrites();
  87. component.lines = [...answer, `composer${CURSOR_MARKER}`, 'status'];
  88. component.lines[0] = '\x1b[1mAnswer line 0\x1b[0m';
  89. tui.renderNow();
  90. await terminal.flush();
  91. expect(terminal.takeWrites()).toContain('\x1b[3J');
  92. component.lines[0] = '\x1b[1mAnswer line 0\x1b[0m';
  93. tui.renderNow();
  94. await terminal.flush();
  95. expect(terminal.takeWrites()).not.toContain('\x1b[3J');
  96. expect(terminal.getScrollBuffer()).toEqual([...answer, 'composer', 'status']);
  97. expect(terminal.getViewport().at(-1)).toBe('status');
  98. expect(terminal.getCursorPosition()).toEqual({ x: 8, y: 42 });
  99. // A later burst must continue from the same logical/physical boundary.
  100. component.lines.splice(80, 0, ...Array.from({ length: 50 }, (_, index) => `More ${index}`));
  101. tui.renderNow();
  102. await terminal.flush();
  103. expect(terminal.getScrollBuffer()).toEqual([
  104. ...answer,
  105. ...Array.from({ length: 50 }, (_, index) => `More ${index}`),
  106. 'composer',
  107. 'status',
  108. ]);
  109. });
  110. it.each([1, 8, 30])(
  111. 'keeps the composer and status at the bottom as %i running rows settle and new output grows',
  112. async (activityRows) => {
  113. const terminal = new RecordingVirtualTerminal(60, 44);
  114. const tui = new TuiMainScreen(terminal);
  115. const component = new MutableLines();
  116. const answer = Array.from({ length: 80 }, (_, index) => `Answer ${index}`);
  117. component.lines = [
  118. ...answer,
  119. ...Array.from({ length: activityRows }, (_, index) => `Activity ${index}`),
  120. `composer${CURSOR_MARKER}`,
  121. 'running',
  122. ];
  123. tui.addChild(component);
  124. tui.renderNow();
  125. await terminal.flush();
  126. terminal.takeWrites();
  127. component.lines = [...answer, `composer${CURSOR_MARKER}`, 'idle'];
  128. for (let added = 0; added <= activityRows + 1; added++) {
  129. tui.renderNow();
  130. await terminal.flush();
  131. expect(terminal.getViewport()).toEqual(
  132. component.lines.slice(-terminal.rows).map((line) => line.replace(CURSOR_MARKER, '')),
  133. );
  134. expect(terminal.getCursorPosition()).toEqual({ x: 8, y: 42 });
  135. if (added === 0) expect(terminal.takeWrites()).toContain('\x1b[3J');
  136. else expect(terminal.takeWrites()).not.toContain('\x1b[3J');
  137. expect(terminal.getScrollBuffer()).toEqual(
  138. component.lines.map((line) => line.replace(CURSOR_MARKER, '')),
  139. );
  140. if (added <= activityRows) component.lines.splice(-2, 0, `New answer ${added}`);
  141. }
  142. expect(terminal.getScrollBuffer()).not.toContain('');
  143. },
  144. );
  145. it('keeps every appended row when a historical row changes in the same frame', async () => {
  146. const terminal = new RecordingVirtualTerminal(67, 44);
  147. const tui = new TuiMainScreen(terminal);
  148. const component = new MutableLines();
  149. const answer = Array.from({ length: 80 }, (_, index) => `Answer line ${index}`);
  150. component.lines = [...answer, 'composer'];
  151. tui.addChild(component);
  152. tui.renderNow();
  153. await terminal.flush();
  154. terminal.takeWrites();
  155. const more = Array.from({ length: 50 }, (_, index) => `More ${index}`);
  156. component.lines = [...answer, ...more, 'composer'];
  157. component.lines[0] = '\x1b[1mAnswer line 0\x1b[0m';
  158. tui.renderNow();
  159. await terminal.flush();
  160. expect(terminal.takeWrites()).not.toContain('\x1b[3J');
  161. expect(terminal.getScrollBuffer()).toEqual([...answer, ...more, 'composer']);
  162. });
  163. it('rebuilds the document when shrinking leaves no rows in the previous viewport', async () => {
  164. const terminal = new RecordingVirtualTerminal(67, 44);
  165. const tui = new TuiMainScreen(terminal);
  166. const component = new MutableLines();
  167. component.lines = Array.from({ length: 100 }, (_, index) => `Old line ${index}`);
  168. tui.addChild(component);
  169. tui.renderNow();
  170. await terminal.flush();
  171. component.lines = ['answer', `composer${CURSOR_MARKER}`];
  172. tui.renderNow();
  173. await terminal.flush();
  174. expect(terminal.getScrollBuffer().filter(Boolean)).toEqual(['answer', 'composer']);
  175. expect(terminal.getCursorPosition()).toEqual({ x: 8, y: 1 });
  176. });
  177. it('still previews the resized tail and restores ordered scrollback after resize settles', async () => {
  178. const terminal = new RecordingVirtualTerminal(67, 44);
  179. const tui = new TuiMainScreen(terminal);
  180. const component = new MutableLines();
  181. component.lines = [
  182. ...Array.from({ length: 80 }, (_, index) => `Answer line ${index}`),
  183. `composer${CURSOR_MARKER}`,
  184. ];
  185. tui.addChild(component);
  186. try {
  187. tui.start();
  188. tui.renderNow();
  189. await terminal.flush();
  190. terminal.takeWrites();
  191. terminal.resize(60, 30);
  192. tui.renderNow();
  193. await terminal.flush();
  194. expect(terminal.takeWrites()).not.toContain('\x1b[3J');
  195. expect(terminal.getViewport()).toEqual([
  196. ...Array.from({ length: 29 }, (_, index) => `Answer line ${index + 51}`),
  197. 'composer',
  198. ]);
  199. await new Promise<void>((resolve) => setTimeout(resolve, 200));
  200. tui.renderNow();
  201. await terminal.flush();
  202. expect(terminal.takeWrites()).toContain('\x1b[3J');
  203. expect(terminal.getScrollBuffer()).toEqual([
  204. ...Array.from({ length: 80 }, (_, index) => `Answer line ${index}`),
  205. 'composer',
  206. ]);
  207. expect(terminal.getCursorPosition()).toEqual({ x: 8, y: 29 });
  208. } finally {
  209. tui.stop();
  210. }
  211. });
  212. it('renders an urgent product interaction without resetting Main diff state', async () => {
  213. const terminal = new RecordingVirtualTerminal(40, 5);
  214. const tui = new TuiMainScreen(terminal);
  215. const component = new MutableLines();
  216. component.lines = ['stable', 'tail'];
  217. tui.addChild(component);
  218. tui.renderNow();
  219. await terminal.flush();
  220. terminal.takeWrites();
  221. component.lines.push('interaction');
  222. tui.requestImmediateRender();
  223. await new Promise<void>((resolve) => setImmediate(resolve));
  224. await terminal.flush();
  225. const writes = terminal.takeWrites();
  226. expect(writes).toContain('interaction');
  227. expect(writes).not.toContain('\x1b[2J');
  228. expect(writes).not.toContain('\x1b[3J');
  229. });
  230. it('keeps OSC 133 zone sentinels out of regular-mode terminal writes', async () => {
  231. const terminal = new RecordingVirtualTerminal(40, 5);
  232. const tui = new TuiMainScreen(terminal);
  233. const component = new MutableLines();
  234. const zoneStart = '\x1b]133;A\x07';
  235. const zoneClose = '\x1b]133;B\x07\x1b]133;C\x07';
  236. component.lines = [`${zoneStart}user prompt`, `${zoneClose}assistant reply`, 'composer'];
  237. tui.addChild(component);
  238. tui.renderNow();
  239. await terminal.flush();
  240. const initialWrites = terminal.takeWrites();
  241. expect(initialWrites).toContain('user prompt');
  242. expect(initialWrites).toContain('assistant reply');
  243. expect(initialWrites).not.toContain('\x1b]133;');
  244. component.lines = [`${zoneStart}user prompt`, `${zoneClose}assistant reply updated`, 'composer'];
  245. tui.renderNow();
  246. await terminal.flush();
  247. const diffWrites = terminal.takeWrites();
  248. expect(diffWrites).toContain('assistant reply updated');
  249. expect(diffWrites).not.toContain('\x1b]133;');
  250. });
  251. it('limits Input extensions to prompt, mask, and paste transformation', () => {
  252. const input = new Input({
  253. prompt: 'Search: ',
  254. mask: '•',
  255. transformPaste: (value) => value.replace(/\s+/gu, ' '),
  256. });
  257. input.handleInput('\u001B[200~secret\nvalue\u001B[201~');
  258. input.focused = true;
  259. const rendered = input.render(30)[0] ?? '';
  260. expect(input.getValue()).toBe('secret value');
  261. expect(rendered).toContain('Search: ');
  262. expect(rendered).toContain('•');
  263. expect(rendered).not.toContain('secret');
  264. expect(rendered).toContain(CURSOR_MARKER);
  265. });
  266. it('retains grouped SelectList headings while using Pi filtering and single-line descriptions', () => {
  267. const list = new SelectList(
  268. [
  269. {
  270. value: 'docs',
  271. label: 'Documents',
  272. description: 'Create, edit, search and share documents.',
  273. groupLabel: 'Files',
  274. },
  275. {
  276. value: 'code',
  277. label: 'Code',
  278. description: 'Inspect and modify source code.',
  279. groupLabel: 'Files',
  280. },
  281. ],
  282. 2,
  283. selectListTheme,
  284. );
  285. list.setFilter('docs');
  286. const rendered = list.render(48);
  287. expect(rendered.join('\n')).toContain('Files');
  288. expect(rendered.join('\n')).toContain('Documents');
  289. expect(rendered.join('\n')).not.toContain('Code');
  290. expect(rendered).toHaveLength(2);
  291. expect(rendered.every((line) => visibleWidth(line) <= 48)).toBe(true);
  292. });
  293. it('exposes only the generic Editor hooks required by a product Draft adapter', () => {
  294. const tui = {
  295. terminal: { rows: 24 },
  296. requestRender: () => undefined,
  297. } as TUI;
  298. const editor = new Editor(tui, { borderColor: passthrough, selectList: selectListTheme }, {
  299. transformPaste: (value) => value.replaceAll('\r', ''),
  300. });
  301. let extensionState = 'empty';
  302. editor.captureUndoExtensionState = () => extensionState;
  303. editor.restoreUndoExtensionState = (state) => {
  304. extensionState = String(state);
  305. };
  306. editor.handleInput('a');
  307. extensionState = 'typed';
  308. editor.handleInput('\x1f');
  309. expect(editor.getText()).toBe('');
  310. expect(extensionState).toBe('empty');
  311. editor.onPaste = (value) => value.endsWith('.png');
  312. editor.handleInput('\u001B[200~/tmp/image.png\r\u001B[201~');
  313. expect(editor.getText()).toBe('');
  314. const pasted = 'x'.repeat(1_001);
  315. editor.onPaste = undefined;
  316. editor.handleInput(`\u001B[200~${pasted}\u001B[201~`);
  317. const snapshot = editor.captureState();
  318. editor.setText('replacement');
  319. expect(editor.restoreState(snapshot)).toBe(true);
  320. expect(editor.getExpandedText()).toBe(pasted);
  321. let submitted = '';
  322. editor.onSubmit = (value) => {
  323. submitted = value;
  324. };
  325. editor.submit();
  326. expect(submitted).toBe(pasted);
  327. });
  328. });