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

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