tui-feature-viewport-contract.test.ts 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289
  1. import { describe, expect, it, vi } from 'vitest';
  2. import type { TuiSessionInputSummary } from '../../src/runtime/port.js';
  3. import { TuiAgentTeamPanel } from '../../src/tui/agent-team/panel.js';
  4. import type { TuiAgentTeamSnapshot } from '../../src/tui/agent-team/model.js';
  5. import { TuiBackgroundWorkPanel } from '../../src/tui/background-work/panel.js';
  6. import { TuiSessionMutationForkConfirmation } from '../../src/tui/controller/product/session-mutation-flow.js';
  7. import { TuiAltScreen } from '../../src/tui/engine/tui-alt-screen.js';
  8. import { TuiMainScreen } from '../../src/tui/engine/tui-main-screen.js';
  9. import { TuiPluginManager } from '../../src/tui/features/plugin/manager.js';
  10. import { TuiSessionHistoryExplorer } from '../../src/tui/features/session-mutation/history-explorer.js';
  11. import { TuiSessionMutationHistoryPicker } from '../../src/tui/features/session-mutation/history-picker.js';
  12. import { TuiSessionMutationRewindPreviewPanel } from '../../src/tui/features/session-mutation/rewind-preview-panel.js';
  13. import { TuiSessionMutationScopePicker } from '../../src/tui/features/session-mutation/scope-picker.js';
  14. import { TuiTranscriptPanel } from '../../src/tui/features/transcript/panel.js';
  15. import { TuiOverlayRegularFeaturePresenter } from '../../src/tui/shell/regular-feature-presenter.js';
  16. import { TuiSurfaceHost, type TuiFeatureScreen } from '../../src/tui/shell/surface-host.js';
  17. import { createTranscriptCell } from '../../src/tui/transcript/model.js';
  18. import { TranscriptStore } from '../../src/tui/transcript/store.js';
  19. import { VirtualTerminal } from '../pi-084-upstream/virtual-terminal.js';
  20. type Factory = (count: number, onCancel: () => void, requestRender: () => void) => TuiFeatureScreen;
  21. const summaries = (count: number): TuiSessionInputSummary[] =>
  22. Array.from({ length: count }, (_, index) => ({
  23. userMessageId: `input-${index}`,
  24. contentHead: `Prompt ${index}`,
  25. timestamp: index + 1,
  26. fileChangeCount: 0,
  27. }));
  28. const team = (count: number): TuiAgentTeamSnapshot => ({
  29. rootSessionId: 'root',
  30. capturedAtMs: 1,
  31. summary: { total: count, running: count, waiting: 0, queued: 0, done: 0, failed: 0, stopped: 0 },
  32. members: Array.from({ length: count }, (_, index) => ({
  33. sessionId: `agent-${index}`,
  34. parentSessionId: 'root',
  35. agentName: `Agent ${index}`,
  36. task: 'Inspect rendering',
  37. status: 'running',
  38. phase: 'tool',
  39. activity: 'Reading',
  40. toolCount: 1,
  41. startedAtMs: 1,
  42. updatedAtMs: 1,
  43. })),
  44. });
  45. const factories: Record<string, Factory> = {
  46. tasks: (count, onCancel, requestRender) =>
  47. new TuiBackgroundWorkPanel({
  48. agentTeam: () => team(count),
  49. backgroundTasks: () => [],
  50. activeSessionId: () => 'root',
  51. onOpenAgent: vi.fn(),
  52. onCancel,
  53. requestRender,
  54. }),
  55. agents: (count, onCancel, requestRender) =>
  56. new TuiAgentTeamPanel({
  57. snapshot: () => team(count),
  58. activeSessionId: () => 'root',
  59. onSelect: vi.fn(),
  60. onCancel,
  61. requestRender,
  62. }),
  63. plugins: (count, onCancel, requestRender) => {
  64. const plugins = Array.from({ length: count }, (_, index) => ({
  65. pluginId: `plugin-${index}`,
  66. name: `Plugin ${index}`,
  67. displayName: `Plugin ${index}`,
  68. marketplace: 'official' as const,
  69. installed: false,
  70. enabled: false,
  71. capabilities: { appCount: 0, mcpServerCount: 0, skillCount: 1 },
  72. }));
  73. return new TuiPluginManager({
  74. plugins,
  75. onInstall: async (plugin) => plugin,
  76. onRemove: async (plugin) => plugin,
  77. onSetEnabled: async (plugin) => plugin,
  78. onRefresh: async () => plugins,
  79. onCancel,
  80. requestRender,
  81. });
  82. },
  83. transcript: (count, onCancel, requestRender) =>
  84. new TuiTranscriptPanel({
  85. source: new TranscriptStore(
  86. Array.from({ length: count }, (_, index) =>
  87. createTranscriptCell({
  88. id: `cell-${index}`,
  89. turnId: `turn-${index}`,
  90. kind: 'user',
  91. status: 'succeeded',
  92. content: `Inspect message ${index}`,
  93. createdAtMs: index + 1,
  94. }),
  95. ),
  96. ),
  97. onCancel,
  98. requestRender,
  99. }),
  100. history: (count, onCancel, requestRender) =>
  101. new TuiSessionHistoryExplorer({
  102. summaries: summaries(count),
  103. mutationAvailable: true,
  104. onAction: vi.fn(),
  105. onCancel,
  106. requestRender,
  107. }),
  108. 'history-picker': (count, onCancel, requestRender) =>
  109. new TuiSessionMutationHistoryPicker({
  110. summaries: summaries(count),
  111. mode: 'rewind',
  112. onSelect: vi.fn(),
  113. onCancel,
  114. requestRender,
  115. }),
  116. 'rewind-preview': (count, onCancel, requestRender) =>
  117. new TuiSessionMutationRewindPreviewPanel({
  118. preview: {
  119. turns: [
  120. {
  121. turnId: 'turn',
  122. files: Array.from({ length: count }, (_, index) => ({
  123. filePath: `src/file-${index}.ts`,
  124. action: 'modified' as const,
  125. skipped: false,
  126. })),
  127. },
  128. ],
  129. },
  130. onContinue: vi.fn(),
  131. onCancel,
  132. requestRender,
  133. }),
  134. 'rewind-scope': (_count, onCancel, requestRender) =>
  135. new TuiSessionMutationScopePicker({
  136. onSelect: vi.fn(),
  137. onCancel,
  138. requestRender,
  139. }),
  140. 'fork-confirmation': (_count, onCancel, requestRender) =>
  141. new TuiSessionMutationForkConfirmation({
  142. summary: summaries(1)[0]!,
  143. options: { canFork: true, worktreeEligible: false, worktreeVisible: false },
  144. onConfirm: vi.fn(),
  145. onCancel,
  146. requestRender,
  147. }),
  148. };
  149. describe.each(Object.entries(factories))('%s regular viewport lifecycle', (_name, factory) => {
  150. it.each([
  151. ...[0, 1, 30].flatMap((count) => [8, 24, 50].map((rows) => ({ count, rows, chatCount: 80 }))),
  152. ...[0, 4].map((chatCount) => ({ count: 1, rows: 24, chatCount })),
  153. ])(
  154. 'isolates $count entries over $chatCount chat rows at $rows rows through updates, resize, nesting and return',
  155. async ({ count, rows, chatCount }) => {
  156. const terminal = new VirtualTerminal(80, rows);
  157. const tui = new TuiMainScreen(terminal);
  158. const messages = Array.from({ length: chatCount }, (_, index) => `BACKGROUND-${index}`);
  159. const chat = () => [...messages, 'COMPOSER', 'STATUS'];
  160. const chatComponent = { render: chat, invalidate() {} };
  161. const host = new TuiSurfaceHost({
  162. chat: { component: chatComponent, focus: chatComponent },
  163. chatMode: 'regular',
  164. viewportRows: () => terminal.rows,
  165. regularFeaturePresenter: new TuiOverlayRegularFeaturePresenter(terminal, tui, () =>
  166. tui.requestRender(),
  167. ),
  168. setFocus: (focus) => tui.setFocus(focus),
  169. requestRender: () => tui.requestRender(),
  170. });
  171. tui.addChild(host);
  172. const assertCovered = async () => {
  173. tui.renderNow();
  174. await terminal.flush();
  175. const viewport = terminal.getViewport().join('\n');
  176. expect(viewport.trim()).not.toBe('');
  177. expect(viewport).not.toMatch(/BACKGROUND-|COMPOSER|STATUS/);
  178. };
  179. tui.start();
  180. try {
  181. await terminal.waitForRender();
  182. const handle = host.pushFeature({
  183. screen: factory(
  184. count,
  185. () => handle.close(),
  186. () => tui.requestRender(),
  187. ),
  188. });
  189. await assertCovered();
  190. messages.push('BACKGROUND-live');
  191. await assertCovered();
  192. messages.splice(-12);
  193. await assertCovered();
  194. for (const key of ['\x1b[B', '\x1b[6~', '\x1b[5~']) {
  195. terminal.sendInput(key);
  196. await assertCovered();
  197. }
  198. terminal.resize(40, rows === 8 ? 24 : 8);
  199. await assertCovered();
  200. terminal.resize(80, rows);
  201. await assertCovered();
  202. const nestedFactory =
  203. _name === 'rewind-preview' ? factories['rewind-scope']! : factories['rewind-preview']!;
  204. const nested = host.pushFeature({
  205. screen: nestedFactory(
  206. 0,
  207. () => nested.close(),
  208. () => tui.requestRender(),
  209. ),
  210. });
  211. await assertCovered();
  212. terminal.sendInput('\x1b');
  213. await assertCovered();
  214. expect(handle.isActive()).toBe(true);
  215. // Some panels first clear a search/filter on Esc; close their surface handle here.
  216. handle.close();
  217. tui.renderNow();
  218. await vi.waitFor(async () => {
  219. await terminal.flush();
  220. const expected = [...chat(), ...Array(Math.max(0, rows - chat().length)).fill('')];
  221. expect(terminal.getViewport()).toEqual(expected.slice(-rows));
  222. expect(terminal.getScrollBuffer()).toEqual(expected);
  223. });
  224. } finally {
  225. host.dispose();
  226. tui.stop();
  227. }
  228. },
  229. );
  230. });
  231. describe.each(Object.entries(factories))('%s fullscreen viewport lifecycle', (_name, factory) => {
  232. it.each([
  233. { rows: 8, count: 0 },
  234. { rows: 24, count: 1 },
  235. { rows: 50, count: 30 },
  236. ])(
  237. 'isolates $count entries at $rows rows and restores the chat layout',
  238. async ({ rows, count }) => {
  239. const terminal = new VirtualTerminal(80, rows);
  240. const tui = new TuiAltScreen(terminal);
  241. const component = {
  242. render: () => ['BACKGROUND-chat', 'COMPOSER', 'STATUS'],
  243. invalidate() {},
  244. };
  245. const host = new TuiSurfaceHost({
  246. chat: { component, focus: component },
  247. chatMode: 'fullscreen',
  248. viewportRows: () => terminal.rows,
  249. regularFeaturePresenter: new TuiOverlayRegularFeaturePresenter(terminal, tui, () =>
  250. tui.requestRender(),
  251. ),
  252. setFocus: (focus) => tui.setFocus(focus),
  253. requestRender: () => tui.requestRender(),
  254. });
  255. tui.setLayoutRoot(host);
  256. tui.start();
  257. try {
  258. await terminal.waitForRender();
  259. const original = terminal.getViewport();
  260. const handle = host.pushFeature({
  261. screen: factory(
  262. count,
  263. () => handle.close(),
  264. () => tui.requestRender(),
  265. ),
  266. });
  267. for (const width of [80, 24, 80]) {
  268. terminal.resize(width, rows);
  269. terminal.sendInput('\x1b[B');
  270. terminal.sendInput('\x1b[6~');
  271. tui.renderNow();
  272. await terminal.flush();
  273. expect(terminal.getViewport().join('\n').trim()).not.toBe('');
  274. expect(terminal.getViewport().join('\n')).not.toMatch(/BACKGROUND-|COMPOSER|STATUS/);
  275. }
  276. handle.close();
  277. tui.renderNow();
  278. await terminal.flush();
  279. expect(terminal.getViewport()).toEqual(original);
  280. } finally {
  281. host.dispose();
  282. tui.stop();
  283. }
  284. },
  285. );
  286. });