tui-session-mutation-panels.test.ts 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458
  1. import { describe, expect, it, vi } from 'vitest';
  2. import { TuiMainScreen } from '../../src/tui/engine/tui-main-screen.js';
  3. import { TuiOverlayRegularFeaturePresenter } from '../../src/tui/shell/regular-feature-presenter.js';
  4. import { VirtualTerminal } from '../pi-084-upstream/virtual-terminal.js';
  5. import { TuiSessionMutationHistoryPicker } from '../../src/tui/features/session-mutation/history-picker.js';
  6. import { TuiSessionMutationRewindPreviewPanel } from '../../src/tui/features/session-mutation/rewind-preview-panel.js';
  7. import { TuiSessionMutationScopePicker } from '../../src/tui/features/session-mutation/scope-picker.js';
  8. import {
  9. formatPromptHead,
  10. formatRelativeTimestamp,
  11. formatSessionInputSummaryLabel,
  12. } from '../../src/tui/features/session-mutation/format.js';
  13. import {
  14. sessionHistoryText,
  15. sessionMutationTemplate,
  16. sessionMutationText,
  17. } from '../../src/tui/features/session-mutation/copy.js';
  18. import { stripAnsi } from '../../src/tui/rendering/text.js';
  19. import type {
  20. TuiRewindPreview,
  21. TuiSessionInputSummary,
  22. TuiRewindScope,
  23. } from '../../src/runtime/port.js';
  24. const NOW_MS = 1_700_000_000_000;
  25. function makeSummary(overrides: Partial<TuiSessionInputSummary> = {}): TuiSessionInputSummary {
  26. return {
  27. userMessageId: 'msg-user-1',
  28. assistantMessageId: 'msg-assistant-1',
  29. contentHead: 'Investigate flaky login tests and capture the failure trace',
  30. timestamp: NOW_MS - 5 * 60_000,
  31. fileChangeCount: 2,
  32. ...overrides,
  33. };
  34. }
  35. describe('formatSessionInputSummaryLabel', () => {
  36. it('formats a concise label with assistant-boundary, files, and relative time', () => {
  37. const label = formatSessionInputSummaryLabel(
  38. {
  39. userMessageId: 'msg-user-1',
  40. assistantMessageId: 'msg-assistant-1',
  41. contentHead: 'Investigate flaky login tests and capture the failure trace',
  42. timestamp: NOW_MS - 5 * 60_000,
  43. fileChangeCount: 2,
  44. },
  45. { nowMs: NOW_MS },
  46. );
  47. expect(label.title).toContain('Investigate flaky login tests');
  48. expect(label.title).toMatch(/\u2026$/u);
  49. expect(label.subtitle).toMatch(/2 files/u);
  50. expect(label.subtitle).toMatch(/5m/u);
  51. expect(label.subtitle).toMatch(/assistant replied/u);
  52. });
  53. it('omits the assistant marker when no assistant message exists', () => {
  54. const label = formatSessionInputSummaryLabel(
  55. makeSummary({ assistantMessageId: undefined, fileChangeCount: 0 }),
  56. { nowMs: NOW_MS },
  57. );
  58. expect(label.subtitle).not.toMatch(/assistant/u);
  59. expect(label.subtitle).toMatch(/0 files/u);
  60. });
  61. it('uses Chinese Session history copy and formatting for a Chinese locale', () => {
  62. const label = formatSessionInputSummaryLabel(makeSummary(), {
  63. nowMs: NOW_MS,
  64. locale: 'zh-CN',
  65. });
  66. expect(label.subtitle).toContain('2 个文件');
  67. expect(label.subtitle).toContain('助手已回复');
  68. expect(formatRelativeTimestamp(0, NOW_MS, 'zh-CN')).toBe('未知时间');
  69. expect(sessionHistoryText('actions', 'zh_CN')).toBe('选择历史操作');
  70. expect(sessionMutationText('sessionMutation.confirm.rewind.title', 'zh-Hans')).toBe(
  71. '确认回退',
  72. );
  73. expect(
  74. sessionMutationTemplate(
  75. 'sessionMutation.confirm.fileCounts',
  76. { ready: 2, skipped: 1 },
  77. 'zh-CN',
  78. ),
  79. ).toBe('2 可回退 · 1 已跳过');
  80. });
  81. });
  82. describe('TuiSessionMutationHistoryPicker', () => {
  83. it('renders the picker header and lists every summary newest-first with full id retained', () => {
  84. const older = makeSummary({
  85. userMessageId: 'msg-user-older',
  86. contentHead: 'Older prompt body',
  87. timestamp: NOW_MS - 30 * 60_000,
  88. fileChangeCount: 1,
  89. });
  90. const middle = makeSummary({
  91. userMessageId: 'msg-user-middle',
  92. contentHead: 'Middle prompt body',
  93. timestamp: NOW_MS - 10 * 60_000,
  94. fileChangeCount: 0,
  95. });
  96. const latest = makeSummary({
  97. userMessageId: 'msg-user-latest',
  98. contentHead: 'Latest prompt body',
  99. timestamp: NOW_MS - 1 * 60_000,
  100. fileChangeCount: 3,
  101. });
  102. const onSelect = vi.fn();
  103. const picker = new TuiSessionMutationHistoryPicker({
  104. summaries: [older, middle, latest],
  105. mode: 'rewind',
  106. onSelect,
  107. onCancel: vi.fn(),
  108. nowMs: NOW_MS,
  109. });
  110. const rendered = stripAnsi(picker.render(80).join('\n'));
  111. expect(rendered).toMatch(/Rewind to a previous message/);
  112. expect(rendered).toContain('Latest prompt body');
  113. expect(rendered).toContain('Middle prompt body');
  114. expect(rendered).toContain('Older prompt body');
  115. expect(rendered).toMatch(/1m/);
  116. expect(rendered).toMatch(/3 files/);
  117. expect(rendered.indexOf('Latest prompt body')).toBeLessThan(
  118. rendered.indexOf('Middle prompt body'),
  119. );
  120. expect(rendered.indexOf('Middle prompt body')).toBeLessThan(
  121. rendered.indexOf('Older prompt body'),
  122. );
  123. expect(rendered).toMatch(/1 turn affected/);
  124. expect(rendered).toMatch(/2 turns affected/);
  125. expect(rendered).toMatch(/3 turns affected/);
  126. // Selection defaults to the latest summary.
  127. picker.handleInput('\r');
  128. expect(onSelect).toHaveBeenCalledTimes(1);
  129. expect(onSelect).toHaveBeenCalledWith(latest);
  130. });
  131. it('does not offer incomplete inputs without an assistant boundary', () => {
  132. const complete = makeSummary({ userMessageId: 'msg-user-complete' });
  133. const incomplete = makeSummary({
  134. userMessageId: 'msg-user-incomplete',
  135. assistantMessageId: undefined,
  136. contentHead: 'Still running',
  137. });
  138. const onSelect = vi.fn();
  139. const picker = new TuiSessionMutationHistoryPicker({
  140. summaries: [complete, incomplete],
  141. mode: 'fork',
  142. onSelect,
  143. onCancel: vi.fn(),
  144. nowMs: NOW_MS,
  145. });
  146. const rendered = stripAnsi(picker.render(100).join('\n'));
  147. expect(rendered).toContain('Investigate flaky login tests');
  148. expect(rendered).not.toContain('Still running');
  149. expect(rendered).toMatch(/1 incomplete message hidden/);
  150. picker.handleInput('\r');
  151. expect(onSelect).toHaveBeenCalledWith(complete);
  152. });
  153. it('truncates the displayed prompt head but keeps the full summary object on select', () => {
  154. const longHead = 'word '.repeat(80).trim();
  155. const summary = makeSummary({
  156. userMessageId: 'msg-user-long',
  157. contentHead: longHead,
  158. fileChangeCount: 0,
  159. });
  160. const onSelect = vi.fn();
  161. const picker = new TuiSessionMutationHistoryPicker({
  162. summaries: [summary],
  163. mode: 'fork',
  164. onSelect,
  165. onCancel: vi.fn(),
  166. });
  167. const rendered = stripAnsi(picker.render(60).join('\n'));
  168. expect(rendered).toContain('Fork from a previous message');
  169. // Rendered line should not contain the full long head; it should be truncated with ellipsis.
  170. expect(rendered).not.toContain(longHead);
  171. expect(rendered).toMatch(/\u2026/);
  172. picker.handleInput('\r');
  173. expect(onSelect).toHaveBeenCalledWith(summary);
  174. });
  175. it('does not split an emoji at the prompt-head boundary', () => {
  176. const head = `${'a'.repeat(46)}😀z`;
  177. expect(formatPromptHead(head, 48)).toBe(head);
  178. expect(formatPromptHead(`${head}tail`, 48)).not.toContain('\uFFFD');
  179. });
  180. it('renders a safe empty state when there are no summaries', () => {
  181. const onSelect = vi.fn();
  182. const picker = new TuiSessionMutationHistoryPicker({
  183. summaries: [],
  184. mode: 'rewind',
  185. onSelect,
  186. onCancel: vi.fn(),
  187. });
  188. const rendered = stripAnsi(picker.render(80).join('\n'));
  189. expect(rendered).toMatch(/No previous user messages/i);
  190. expect(rendered).toMatch(/Esc cancel/);
  191. // No summaries means there is nothing to select, so onSelect must not fire.
  192. picker.handleInput('\r');
  193. picker.handleInput('\u001b');
  194. expect(onSelect).not.toHaveBeenCalled();
  195. });
  196. it('routes Escape to onCancel exactly once and never invokes the mutation callback', () => {
  197. const summary = makeSummary();
  198. const onSelect = vi.fn();
  199. const onCancel = vi.fn();
  200. const picker = new TuiSessionMutationHistoryPicker({
  201. summaries: [summary],
  202. mode: 'rewind',
  203. onSelect,
  204. onCancel,
  205. });
  206. picker.handleInput('\u001b');
  207. picker.handleInput('\u001b');
  208. expect(onCancel).toHaveBeenCalledTimes(1);
  209. expect(onSelect).not.toHaveBeenCalled();
  210. });
  211. it('exposes a stable surface id and pads renderViewport to the requested height', () => {
  212. const summary = makeSummary();
  213. const picker = new TuiSessionMutationHistoryPicker({
  214. summaries: [summary],
  215. mode: 'fork',
  216. onSelect: vi.fn(),
  217. onCancel: vi.fn(),
  218. });
  219. expect(picker.id).toBe('session-mutation:history');
  220. const padded = picker.renderViewport(80, 24);
  221. expect(padded.length).toBe(24);
  222. expect(padded.some((line) => line.length > 0)).toBe(true);
  223. const clipped = picker.renderViewport(80, 4);
  224. expect(clipped.length).toBe(4);
  225. expect(clipped.length).toBeLessThanOrEqual(picker.render(80).length);
  226. });
  227. it('returns an empty viewport for zero width without crashing', () => {
  228. const picker = new TuiSessionMutationHistoryPicker({
  229. summaries: [makeSummary()],
  230. mode: 'fork',
  231. onSelect: vi.fn(),
  232. onCancel: vi.fn(),
  233. });
  234. expect(picker.renderViewport(0, 10)).toEqual([]);
  235. });
  236. });
  237. describe('TuiSessionMutationRewindPreviewPanel', () => {
  238. it.each([8, 24, 50])(
  239. 'owns the complete regular viewport at %i rows and restores chat on cancel',
  240. async (rows) => {
  241. const terminal = new VirtualTerminal(80, rows);
  242. const tui = new TuiMainScreen(terminal);
  243. const messages = Array.from({ length: 80 }, (_, index) => `chat-marker-${index}`);
  244. const chat = () => [...messages, 'COMPOSER', 'STATUS'];
  245. tui.addChild({ render: chat, invalidate() {} });
  246. let close: () => void = () => undefined;
  247. const panel = new TuiSessionMutationRewindPreviewPanel({
  248. preview: { turns: [] },
  249. target: 'Target /example-skill',
  250. impact: '1 turn affected · 0 files',
  251. onCancel: () => close(),
  252. onContinue: vi.fn(),
  253. requestRender: () => tui.requestRender(),
  254. });
  255. tui.start();
  256. try {
  257. await terminal.waitForRender();
  258. const presenter = new TuiOverlayRegularFeaturePresenter(terminal, tui, () =>
  259. tui.requestRender(),
  260. );
  261. const handle = presenter.show(panel, panel);
  262. close = () => handle.close();
  263. tui.setFocus(handle.focus);
  264. for (let update = 0; update < 3; update++) {
  265. tui.renderNow();
  266. await terminal.flush();
  267. const viewport = terminal.getViewport().join('\n');
  268. expect(viewport).toContain('Rewind preview');
  269. expect(viewport).not.toContain('chat-marker-');
  270. expect(viewport).not.toContain('COMPOSER');
  271. expect(viewport).not.toContain('STATUS');
  272. if (update < 2) messages.push(`chat-marker-live-${update}`);
  273. }
  274. terminal.sendInput('\u001B');
  275. tui.renderNow();
  276. await terminal.flush();
  277. expect(terminal.getViewport()).toEqual(chat().slice(-rows));
  278. expect(terminal.getScrollBuffer()).toEqual(chat());
  279. } finally {
  280. tui.stop();
  281. }
  282. },
  283. );
  284. it('groups ready vs skipped files and shows modified/created/deleted actions', () => {
  285. const preview: TuiRewindPreview = {
  286. turns: [
  287. {
  288. turnId: 'turn-1',
  289. files: [
  290. { filePath: 'src/a.ts', action: 'modified', skipped: false },
  291. { filePath: 'src/b.ts', action: 'created', skipped: false },
  292. { filePath: 'src/c.ts', action: 'deleted', skipped: false },
  293. { filePath: 'src/skipped.ts', action: 'modified', skipped: true },
  294. ],
  295. },
  296. ],
  297. };
  298. const onCancel = vi.fn();
  299. const panel = new TuiSessionMutationRewindPreviewPanel({
  300. preview,
  301. onCancel,
  302. });
  303. const rendered = stripAnsi(panel.render(80).join('\n'));
  304. expect(rendered).toMatch(/Rewind preview/);
  305. expect(rendered).toMatch(/Ready to rewind/);
  306. expect(rendered).toMatch(/Skipped/);
  307. expect(rendered).toContain('src/a.ts');
  308. expect(rendered).toContain('src/b.ts');
  309. expect(rendered).toContain('src/c.ts');
  310. expect(rendered).toContain('src/skipped.ts');
  311. expect(rendered).toMatch(/modified/);
  312. expect(rendered).toMatch(/created/);
  313. expect(rendered).toMatch(/deleted/);
  314. expect(rendered).toMatch(/skipped/);
  315. });
  316. it('renders a no-diff message when no ready files remain', () => {
  317. const preview: TuiRewindPreview = {
  318. turns: [
  319. {
  320. turnId: 'turn-1',
  321. files: [{ filePath: 'src/already-clean.ts', action: 'modified', skipped: true }],
  322. },
  323. ],
  324. };
  325. const onCancel = vi.fn();
  326. const panel = new TuiSessionMutationRewindPreviewPanel({ preview, onCancel });
  327. const rendered = stripAnsi(panel.render(80).join('\n'));
  328. expect(rendered).toMatch(/no[- ]?diff/i);
  329. });
  330. it('treats repeated Escape presses as a single idempotent close', () => {
  331. const panel = new TuiSessionMutationRewindPreviewPanel({
  332. preview: { turns: [] },
  333. onCancel: vi.fn(),
  334. });
  335. panel.handleInput('\u001b');
  336. panel.handleInput('\u001b');
  337. expect(panel.isClosed()).toBe(true);
  338. });
  339. it('keeps scroll and confirmation controls visible when the file preview overflows', () => {
  340. const preview: TuiRewindPreview = {
  341. turns: [
  342. {
  343. turnId: 'turn-many-files',
  344. files: Array.from({ length: 20 }, (_, index) => ({
  345. filePath: `src/file-${String(index)}.ts`,
  346. action: 'modified',
  347. skipped: false,
  348. })),
  349. },
  350. ],
  351. };
  352. const onContinue = vi.fn();
  353. const panel = new TuiSessionMutationRewindPreviewPanel({
  354. preview,
  355. onCancel: vi.fn(),
  356. onContinue,
  357. continueHint: 'Enter rewind · Esc back',
  358. requestRender: vi.fn(),
  359. });
  360. const first = stripAnsi(panel.renderViewport(70, 10).join('\n'));
  361. expect(first).toContain('PgUp/PgDn scroll');
  362. expect(first).toContain('Enter rewind');
  363. expect(first).toContain('Esc back');
  364. panel.handleInput('\u001b[6~');
  365. const scrolled = stripAnsi(panel.renderViewport(70, 10).join('\n'));
  366. expect(scrolled).toContain('Enter rewind');
  367. expect(scrolled).not.toBe(first);
  368. panel.handleInput('\r');
  369. expect(onContinue).toHaveBeenCalledOnce();
  370. });
  371. });
  372. describe('TuiSessionMutationScopePicker', () => {
  373. it('only exposes the two Desktop-compatible rewind scopes', () => {
  374. const onSelect = vi.fn<(scope: TuiRewindScope) => void>();
  375. const picker = new TuiSessionMutationScopePicker({ onSelect, onCancel: vi.fn() });
  376. const rendered = stripAnsi(picker.render(80).join('\n'));
  377. expect(rendered).toMatch(/Choose what to rewind/);
  378. expect(rendered).toContain('Conversation only');
  379. expect(rendered).not.toContain('Files only');
  380. expect(rendered).toContain('Conversation and files');
  381. expect(rendered).not.toMatch(/partial/i);
  382. const compact = stripAnsi(picker.renderViewport(60, 4).join('\n'));
  383. expect(compact).toContain('Enter confirm');
  384. expect(compact).toContain('Esc cancel');
  385. picker.handleInput('\r');
  386. expect(onSelect).toHaveBeenCalledWith('conversation');
  387. });
  388. it('returns the selected scope when navigating down then confirming', () => {
  389. const onSelect = vi.fn<(scope: TuiRewindScope) => void>();
  390. const picker = new TuiSessionMutationScopePicker({ onSelect, onCancel: vi.fn() });
  391. picker.handleInput('\u001b[B');
  392. picker.handleInput('\r');
  393. expect(onSelect).toHaveBeenCalledWith('conversation_and_files');
  394. });
  395. it('cancels idempotently and never fires onSelect', () => {
  396. const onSelect = vi.fn();
  397. const onCancel = vi.fn();
  398. const picker = new TuiSessionMutationScopePicker({ onSelect, onCancel });
  399. picker.handleInput('\u001b');
  400. picker.handleInput('\u001b');
  401. expect(onCancel).toHaveBeenCalledTimes(1);
  402. expect(onSelect).not.toHaveBeenCalled();
  403. });
  404. });