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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412
  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.each([0, 30])('rebuilds changed scrollback text even when the document grows by %i rows', async (growth) => {
  164. const terminal = new RecordingVirtualTerminal(67, 24);
  165. const tui = new TuiMainScreen(terminal);
  166. const component = new MutableLines();
  167. const input = Array.from({ length: 80 }, (_, index) => `Queued input ${index}`);
  168. component.lines = [...input, `composer${CURSOR_MARKER}`, 'status'];
  169. tui.addChild(component);
  170. tui.renderNow();
  171. await terminal.flush();
  172. terminal.takeWrites();
  173. component.lines = [
  174. 'Recovered context',
  175. ...Array.from({ length: growth }, (_, index) => `Recovered row ${index}`),
  176. ...input.slice(1),
  177. `composer${CURSOR_MARKER}`,
  178. 'status',
  179. ];
  180. tui.renderNow();
  181. await terminal.flush();
  182. const expected = component.lines.map((line) => line.replace(CURSOR_MARKER, ''));
  183. expect(terminal.takeWrites()).toContain('\x1b[3J');
  184. expect(terminal.getScrollBuffer()).toEqual(expected);
  185. expect(terminal.getViewport()).toEqual(expected.slice(-terminal.rows));
  186. expect(terminal.getCursorPosition()).toEqual({ x: 8, y: 22 });
  187. // Subsequent streaming must overwrite the current footer, not append a second one.
  188. component.lines.splice(-2, 0, 'Next response');
  189. tui.renderNow();
  190. await terminal.flush();
  191. expect(terminal.takeWrites()).not.toContain('\x1b[3J');
  192. expect(terminal.getScrollBuffer()).toEqual([
  193. ...expected.slice(0, -2), 'Next response', 'composer', 'status',
  194. ]);
  195. });
  196. it('rebuilds the document when shrinking leaves no rows in the previous viewport', async () => {
  197. const terminal = new RecordingVirtualTerminal(67, 44);
  198. const tui = new TuiMainScreen(terminal);
  199. const component = new MutableLines();
  200. component.lines = Array.from({ length: 100 }, (_, index) => `Old line ${index}`);
  201. tui.addChild(component);
  202. tui.renderNow();
  203. await terminal.flush();
  204. component.lines = ['answer', `composer${CURSOR_MARKER}`];
  205. tui.renderNow();
  206. await terminal.flush();
  207. expect(terminal.getScrollBuffer().filter(Boolean)).toEqual(['answer', 'composer']);
  208. expect(terminal.getCursorPosition()).toEqual({ x: 8, y: 1 });
  209. });
  210. it('still previews the resized tail and restores ordered scrollback after resize settles', async () => {
  211. const terminal = new RecordingVirtualTerminal(67, 44);
  212. const tui = new TuiMainScreen(terminal);
  213. const component = new MutableLines();
  214. component.lines = [
  215. ...Array.from({ length: 80 }, (_, index) => `Answer line ${index}`),
  216. `composer${CURSOR_MARKER}`,
  217. ];
  218. tui.addChild(component);
  219. try {
  220. tui.start();
  221. tui.renderNow();
  222. await terminal.flush();
  223. terminal.takeWrites();
  224. terminal.resize(60, 30);
  225. tui.renderNow();
  226. await terminal.flush();
  227. expect(terminal.takeWrites()).not.toContain('\x1b[3J');
  228. expect(terminal.getViewport()).toEqual([
  229. ...Array.from({ length: 29 }, (_, index) => `Answer line ${index + 51}`),
  230. 'composer',
  231. ]);
  232. await new Promise<void>((resolve) => setTimeout(resolve, 200));
  233. tui.renderNow();
  234. await terminal.flush();
  235. expect(terminal.takeWrites()).toContain('\x1b[3J');
  236. expect(terminal.getScrollBuffer()).toEqual([
  237. ...Array.from({ length: 80 }, (_, index) => `Answer line ${index}`),
  238. 'composer',
  239. ]);
  240. expect(terminal.getCursorPosition()).toEqual({ x: 8, y: 29 });
  241. } finally {
  242. tui.stop();
  243. }
  244. });
  245. it('renders an urgent product interaction without resetting Main diff state', async () => {
  246. const terminal = new RecordingVirtualTerminal(40, 5);
  247. const tui = new TuiMainScreen(terminal);
  248. const component = new MutableLines();
  249. component.lines = ['stable', 'tail'];
  250. tui.addChild(component);
  251. tui.renderNow();
  252. await terminal.flush();
  253. terminal.takeWrites();
  254. component.lines.push('interaction');
  255. tui.requestImmediateRender();
  256. await new Promise<void>((resolve) => setImmediate(resolve));
  257. await terminal.flush();
  258. const writes = terminal.takeWrites();
  259. expect(writes).toContain('interaction');
  260. expect(writes).not.toContain('\x1b[2J');
  261. expect(writes).not.toContain('\x1b[3J');
  262. });
  263. it('keeps OSC 133 zone sentinels out of regular-mode terminal writes', async () => {
  264. const terminal = new RecordingVirtualTerminal(40, 5);
  265. const tui = new TuiMainScreen(terminal);
  266. const component = new MutableLines();
  267. const zoneStart = '\x1b]133;A\x07';
  268. const zoneClose = '\x1b]133;B\x07\x1b]133;C\x07';
  269. component.lines = [`${zoneStart}user prompt`, `${zoneClose}assistant reply`, 'composer'];
  270. tui.addChild(component);
  271. tui.renderNow();
  272. await terminal.flush();
  273. const initialWrites = terminal.takeWrites();
  274. expect(initialWrites).toContain('user prompt');
  275. expect(initialWrites).toContain('assistant reply');
  276. expect(initialWrites).not.toContain('\x1b]133;');
  277. component.lines = [`${zoneStart}user prompt`, `${zoneClose}assistant reply updated`, 'composer'];
  278. tui.renderNow();
  279. await terminal.flush();
  280. const diffWrites = terminal.takeWrites();
  281. expect(diffWrites).toContain('assistant reply updated');
  282. expect(diffWrites).not.toContain('\x1b]133;');
  283. });
  284. it('limits Input extensions to prompt, mask, and paste transformation', () => {
  285. const input = new Input({
  286. prompt: 'Search: ',
  287. mask: '•',
  288. transformPaste: (value) => value.replace(/\s+/gu, ' '),
  289. });
  290. input.handleInput('\u001B[200~secret\nvalue\u001B[201~');
  291. input.focused = true;
  292. const rendered = input.render(30)[0] ?? '';
  293. expect(input.getValue()).toBe('secret value');
  294. expect(rendered).toContain('Search: ');
  295. expect(rendered).toContain('•');
  296. expect(rendered).not.toContain('secret');
  297. expect(rendered).toContain(CURSOR_MARKER);
  298. });
  299. it('retains grouped SelectList headings while using Pi filtering and single-line descriptions', () => {
  300. const list = new SelectList(
  301. [
  302. {
  303. value: 'docs',
  304. label: 'Documents',
  305. description: 'Create, edit, search and share documents.',
  306. groupLabel: 'Files',
  307. },
  308. {
  309. value: 'code',
  310. label: 'Code',
  311. description: 'Inspect and modify source code.',
  312. groupLabel: 'Files',
  313. },
  314. ],
  315. 2,
  316. selectListTheme,
  317. );
  318. list.setFilter('docs');
  319. const rendered = list.render(48);
  320. expect(rendered.join('\n')).toContain('Files');
  321. expect(rendered.join('\n')).toContain('Documents');
  322. expect(rendered.join('\n')).not.toContain('Code');
  323. expect(rendered).toHaveLength(2);
  324. expect(rendered.every((line) => visibleWidth(line) <= 48)).toBe(true);
  325. });
  326. it('exposes only the generic Editor hooks required by a product Draft adapter', () => {
  327. const tui = {
  328. terminal: { rows: 24 },
  329. requestRender: () => undefined,
  330. } as TUI;
  331. const editor = new Editor(tui, { borderColor: passthrough, selectList: selectListTheme }, {
  332. transformPaste: (value) => value.replaceAll('\r', ''),
  333. });
  334. let extensionState = 'empty';
  335. editor.captureUndoExtensionState = () => extensionState;
  336. editor.restoreUndoExtensionState = (state) => {
  337. extensionState = String(state);
  338. };
  339. editor.handleInput('a');
  340. extensionState = 'typed';
  341. editor.handleInput('\x1f');
  342. expect(editor.getText()).toBe('');
  343. expect(extensionState).toBe('empty');
  344. editor.onPaste = (value) => value.endsWith('.png');
  345. editor.handleInput('\u001B[200~/tmp/image.png\r\u001B[201~');
  346. expect(editor.getText()).toBe('');
  347. const pasted = 'x'.repeat(1_001);
  348. editor.onPaste = undefined;
  349. editor.handleInput(`\u001B[200~${pasted}\u001B[201~`);
  350. const snapshot = editor.captureState();
  351. editor.setText('replacement');
  352. expect(editor.restoreState(snapshot)).toBe(true);
  353. expect(editor.getExpandedText()).toBe(pasted);
  354. let submitted = '';
  355. editor.onSubmit = (value) => {
  356. submitted = value;
  357. };
  358. editor.submit();
  359. expect(submitted).toBe(pasted);
  360. });
  361. });