tui-session-history-flow.test.ts 10.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274
  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 { TuiSurfaceHost, type TuiFeatureScreen } from '../../src/tui/shell/surface-host.js';
  5. import { VirtualTerminal } from '../pi-084-upstream/virtual-terminal.js';
  6. import type { TuiSessionInputSummary } from '../../src/runtime/port.js';
  7. import { TuiSessionMutationFlow } from '../../src/tui/controller/product/session-mutation-flow.js';
  8. import { stripAnsi } from '../../src/tui/rendering/text.js';
  9. const SESSION_ID = 'session-history';
  10. const SUMMARY: TuiSessionInputSummary = {
  11. userMessageId: 'user-history-1',
  12. assistantMessageId: 'assistant-history-1',
  13. contentHead: 'Change the historical input',
  14. timestamp: 1_700_000_000_000,
  15. fileChangeCount: 1,
  16. };
  17. function createHarness(realHost?: TuiSurfaceHost) {
  18. const listSessionInputSummaries = vi.fn(async () => [SUMMARY]);
  19. const getSessionRewindPreview = vi.fn(async () => ({
  20. turns: [
  21. {
  22. turnId: 'turn-history-1',
  23. files: [{ filePath: 'src/history.ts', action: 'modified' as const, skipped: false }],
  24. },
  25. ],
  26. }));
  27. const rewindSession = vi.fn(async () => ({ rewound: true }));
  28. const listMessagePage = vi.fn(async () => ({
  29. messages: [
  30. {
  31. id: SUMMARY.userMessageId,
  32. role: 'user' as const,
  33. content: 'Full historical input',
  34. timestamp: SUMMARY.timestamp,
  35. },
  36. ],
  37. hasMore: false,
  38. }));
  39. const editSessionMessage = vi.fn();
  40. const pushedScreens: Array<TuiFeatureScreen & {
  41. id: string;
  42. handleInput(data: string): void;
  43. render(width: number): string[];
  44. }> = [];
  45. const closeHandles: Array<ReturnType<typeof vi.fn>> = [];
  46. const surfaceHost = {
  47. pushFeature: vi.fn(
  48. ({
  49. screen,
  50. }: {
  51. screen: TuiFeatureScreen & { handleInput(data: string): void };
  52. }) => {
  53. pushedScreens.push(screen);
  54. const realHandle = realHost?.pushFeature({ screen });
  55. const close = vi.fn(() => realHandle?.close() ?? true);
  56. closeHandles.push(close);
  57. return { id: screen.id, close, isActive: () => true };
  58. },
  59. ),
  60. setChatFocus: vi.fn(),
  61. };
  62. const editor = { setText: vi.fn() };
  63. const refreshProjection = vi.fn(async () => undefined);
  64. const reloadSessionProjection = vi.fn(async () => undefined);
  65. const setEditTranscriptBoundary = vi.fn();
  66. const flow = new TuiSessionMutationFlow({
  67. runtime: {
  68. listSessionInputSummaries,
  69. getSessionRewindPreview,
  70. rewindSession,
  71. listMessagePage,
  72. editSessionMessage,
  73. } as never,
  74. controller: {
  75. snapshot: () => ({
  76. session: { sessionId: SESSION_ID, title: 'History test' },
  77. sessions: [],
  78. }),
  79. } as never,
  80. sessionFlow: { activateSessionById: vi.fn() } as never,
  81. refreshProjection,
  82. reloadSessionProjection,
  83. surfaceHost: surfaceHost as never,
  84. editor: editor as never,
  85. setHint: vi.fn(),
  86. append: vi.fn(),
  87. setEditTranscriptBoundary,
  88. onChanged: vi.fn(),
  89. hasLiveRun: () => false,
  90. });
  91. return {
  92. flow,
  93. listSessionInputSummaries,
  94. getSessionRewindPreview,
  95. rewindSession,
  96. listMessagePage,
  97. editSessionMessage,
  98. pushedScreens,
  99. closeHandles,
  100. surfaceHost,
  101. editor,
  102. refreshProjection,
  103. reloadSessionProjection,
  104. setEditTranscriptBoundary,
  105. };
  106. }
  107. describe('TuiSessionMutationFlow history explorer', () => {
  108. it.each([8, 24, 50])(
  109. 'restores chat after cancelling the real rewind confirmation at %i rows',
  110. async (rows) => {
  111. const terminal = new VirtualTerminal(80, rows);
  112. const tui = new TuiMainScreen(terminal);
  113. const chat = [
  114. ...Array.from({ length: 80 }, (_, index) => `BACKGROUND-${index}`),
  115. 'COMPOSER',
  116. 'STATUS',
  117. ];
  118. const component = { render: () => chat, invalidate() {} };
  119. const host = new TuiSurfaceHost({
  120. chat: { component, focus: component },
  121. chatMode: 'regular',
  122. viewportRows: () => terminal.rows,
  123. regularFeaturePresenter: new TuiOverlayRegularFeaturePresenter(terminal, tui, () =>
  124. tui.requestRender(),
  125. ),
  126. setFocus: (focus) => tui.setFocus(focus),
  127. requestRender: () => tui.requestRender(),
  128. });
  129. const harness = createHarness(host);
  130. tui.addChild(host);
  131. tui.start();
  132. try {
  133. await terminal.waitForRender();
  134. harness.flow.startHistory();
  135. await vi.waitFor(() => expect(harness.pushedScreens).toHaveLength(1));
  136. // Choose conversation-only rewind through the actual history action menu.
  137. for (const key of ['\r', '\x1b[B', '\x1b[B', '\r']) terminal.sendInput(key);
  138. await vi.waitFor(() => expect(harness.pushedScreens).toHaveLength(2));
  139. tui.renderNow();
  140. await terminal.flush();
  141. expect(harness.pushedScreens[1]?.id).toBe('session-mutation:rewind-confirm');
  142. expect(terminal.getViewport().join('\n')).not.toMatch(/BACKGROUND-|COMPOSER|STATUS/);
  143. terminal.sendInput('\x1b');
  144. tui.renderNow();
  145. await terminal.flush();
  146. expect(host.getActiveSurface()).toEqual({
  147. kind: 'feature',
  148. id: 'session-history:explorer',
  149. });
  150. terminal.sendInput('\x1b');
  151. tui.renderNow();
  152. await terminal.flush();
  153. expect(terminal.getViewport()).toEqual(chat.slice(-rows));
  154. expect(terminal.getScrollBuffer()).toEqual(chat);
  155. expect(harness.rewindSession).not.toHaveBeenCalled();
  156. } finally {
  157. host.dispose();
  158. tui.stop();
  159. }
  160. },
  161. );
  162. it('confirms a conversation-only rewind without an irrelevant file preview', async () => {
  163. const harness = createHarness();
  164. harness.flow.startHistory();
  165. await vi.waitFor(() => expect(harness.pushedScreens).toHaveLength(1));
  166. expect(harness.pushedScreens[0]?.id).toBe('session-history:explorer');
  167. harness.pushedScreens[0]?.handleInput('\r');
  168. harness.pushedScreens[0]?.handleInput('\u001b[B');
  169. harness.pushedScreens[0]?.handleInput('\u001b[B');
  170. harness.pushedScreens[0]?.handleInput('\r');
  171. await vi.waitFor(() => expect(harness.pushedScreens).toHaveLength(2));
  172. expect(harness.pushedScreens[1]?.id).toBe('session-mutation:rewind-confirm');
  173. expect(harness.getSessionRewindPreview).not.toHaveBeenCalled();
  174. expect(harness.rewindSession).not.toHaveBeenCalled();
  175. harness.pushedScreens[1]?.handleInput('\r');
  176. await vi.waitFor(() =>
  177. expect(harness.rewindSession).toHaveBeenCalledWith({
  178. sessionId: SESSION_ID,
  179. userMessageId: SUMMARY.userMessageId,
  180. clientRequestId: expect.stringMatching(/^tui-rewind_/u),
  181. }),
  182. );
  183. await vi.waitFor(() =>
  184. expect(harness.reloadSessionProjection).toHaveBeenCalledWith(SESSION_ID),
  185. );
  186. expect(harness.refreshProjection).not.toHaveBeenCalled();
  187. expect(harness.flow.getInvocationCountForTesting()).toBe(0);
  188. });
  189. it('restores the history explorer after cancelling a conversation-only rewind', async () => {
  190. const harness = createHarness();
  191. harness.flow.startHistory();
  192. await vi.waitFor(() => expect(harness.pushedScreens).toHaveLength(1));
  193. const explorer = harness.pushedScreens[0];
  194. explorer?.handleInput('\r');
  195. explorer?.handleInput('\u001b[B');
  196. explorer?.handleInput('\u001b[B');
  197. explorer?.handleInput('\r');
  198. await vi.waitFor(() => expect(harness.pushedScreens).toHaveLength(2));
  199. harness.pushedScreens[1]?.handleInput('\u001b');
  200. expect(harness.flow.getInvocationCountForTesting()).toBe(0);
  201. expect(stripAnsi(explorer?.render(100).join('\n') ?? '')).toContain('Search:');
  202. explorer?.handleInput('\r');
  203. expect(stripAnsi(explorer?.render(100).join('\n') ?? '')).toContain('Choose history action');
  204. });
  205. it('previews a historical edit before loading it into the composer', async () => {
  206. const harness = createHarness();
  207. harness.flow.startHistory();
  208. await vi.waitFor(() => expect(harness.pushedScreens).toHaveLength(1));
  209. harness.pushedScreens[0]?.handleInput('\r');
  210. harness.pushedScreens[0]?.handleInput('\u001b[B');
  211. harness.pushedScreens[0]?.handleInput('\r');
  212. await vi.waitFor(() => expect(harness.pushedScreens).toHaveLength(2));
  213. expect(harness.pushedScreens[1]?.id).toBe('session-mutation:rewind-preview');
  214. expect(harness.listMessagePage).not.toHaveBeenCalled();
  215. expect(harness.editor.setText).not.toHaveBeenCalled();
  216. harness.pushedScreens[1]?.handleInput('\r');
  217. await vi.waitFor(() =>
  218. expect(harness.listMessagePage).toHaveBeenCalledWith(SESSION_ID, {
  219. limit: 100,
  220. }),
  221. );
  222. await vi.waitFor(() =>
  223. expect(harness.editor.setText).toHaveBeenCalledWith('Full historical input'),
  224. );
  225. expect(harness.setEditTranscriptBoundary).toHaveBeenCalledWith(SUMMARY.userMessageId);
  226. expect(harness.surfaceHost.setChatFocus).toHaveBeenCalled();
  227. expect(harness.editSessionMessage).not.toHaveBeenCalled();
  228. });
  229. it('uses the file preview as the final confirmation for a file rewind', async () => {
  230. const harness = createHarness();
  231. harness.flow.startHistory();
  232. await vi.waitFor(() => expect(harness.pushedScreens).toHaveLength(1));
  233. harness.pushedScreens[0]?.handleInput('\r');
  234. harness.pushedScreens[0]?.handleInput('\u001b[B');
  235. harness.pushedScreens[0]?.handleInput('\u001b[B');
  236. harness.pushedScreens[0]?.handleInput('\u001b[B');
  237. harness.pushedScreens[0]?.handleInput('\r');
  238. await vi.waitFor(() => expect(harness.pushedScreens).toHaveLength(2));
  239. expect(harness.pushedScreens[1]?.id).toBe('session-mutation:rewind-preview');
  240. expect(harness.rewindSession).not.toHaveBeenCalled();
  241. harness.pushedScreens[1]?.handleInput('\r');
  242. await vi.waitFor(() =>
  243. expect(harness.rewindSession).toHaveBeenCalledWith({
  244. sessionId: SESSION_ID,
  245. userMessageId: SUMMARY.userMessageId,
  246. clientRequestId: expect.stringMatching(/^tui-rewind_/u),
  247. rewindTurnDiff: true,
  248. }),
  249. );
  250. expect(harness.pushedScreens).toHaveLength(2);
  251. });
  252. });