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

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