tui-shell-block.test.ts 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241
  1. import { describe, expect, it, vi } from 'vitest';
  2. import { TuiBashFlow } from '../../src/tui/controller/product/bash-flow.js';
  3. import { TuiTurnProjection } from '../../src/tui/controller/projection/turn-projection.js';
  4. import type { TuiMessage } from '../../src/runtime/port.js';
  5. import { TranscriptStore } from '../../src/tui/transcript/store.js';
  6. import { TranscriptView } from '../../src/tui/transcript/view.js';
  7. import { renderShellBlock } from '../../src/tui/transcript/shell-block.js';
  8. import { createTranscriptCell } from '../../src/tui/transcript/model.js';
  9. import { presentTranscriptCell } from '../../src/tui/transcript/presentation/content.js';
  10. import { stripAnsi, visibleWidth } from '../../src/tui/rendering/text.js';
  11. function shellCell() {
  12. return createTranscriptCell({
  13. id: 'shell-1',
  14. kind: 'shell',
  15. status: 'succeeded',
  16. title: '! printf output',
  17. content: 'first line\n second line\n',
  18. detail: 'Exit code: 0',
  19. createdAtMs: 1,
  20. });
  21. }
  22. describe('Shell transcript block', () => {
  23. it.each([
  24. { exitCode: 0, cancelled: false, status: 'succeeded' },
  25. { exitCode: 7, cancelled: false, status: 'failed' },
  26. { exitCode: undefined, cancelled: true, status: 'cancelled' },
  27. ] as const)(
  28. 'dismisses $status shell results when the next turn starts without replaying them',
  29. async ({ exitCode, cancelled, status }) => {
  30. const transcript = new TranscriptStore();
  31. const view = new TranscriptView(transcript);
  32. const onChange = vi.fn();
  33. const projection = new TuiTurnProjection({ transcript, now: () => 10, onChange });
  34. const flow = new TuiBashFlow({
  35. transcript,
  36. onChanged: vi.fn(),
  37. execute: async ({ onOutput }) => {
  38. onOutput('shell output');
  39. return { exitCode, cancelled };
  40. },
  41. });
  42. for (const excludeFromContext of [false, true]) {
  43. await flow.run({ command: 'pwd', excludeFromContext }, '/workspace', 'session');
  44. }
  45. expect(transcript.snapshot()).toHaveLength(2);
  46. expect(transcript.snapshot().every((cell) => cell.status === status)).toBe(true);
  47. transcript.replaceDurableProjection(() => projection.hydrateHistory([]));
  48. expect(stripAnsi(view.render(80).join('\n'))).toContain('shell output');
  49. const messages: TuiMessage[] = [];
  50. for (const turnId of ['next-turn', 'later-turn']) {
  51. onChange.mockClear();
  52. projection.beginTurn(turnId, 10);
  53. expect(stripAnsi(view.render(80).join('\n'))).not.toContain('shell output');
  54. if (turnId === 'next-turn') expect(onChange).toHaveBeenCalled();
  55. const message: TuiMessage = {
  56. id: `answer:${turnId}`,
  57. role: 'assistant',
  58. content: `Answer for ${turnId}`,
  59. turnId,
  60. };
  61. projection.applyStreamEvent(turnId, { type: 'message', message });
  62. projection.markTurn(turnId, 'succeeded', 10);
  63. messages.push(message);
  64. transcript.replaceDurableProjection(() => projection.hydrateHistory(messages));
  65. const rendered = stripAnsi(view.render(80).join('\n'));
  66. expect(rendered).toContain(message.content);
  67. expect(rendered).not.toContain('shell output');
  68. expect(transcript.snapshot().some((cell) => cell.kind === 'shell')).toBe(false);
  69. }
  70. expect(flow.takeContext('session')?.match(/shell output/gu)).toHaveLength(1);
  71. expect(flow.takeContext('session')).toBeUndefined();
  72. },
  73. );
  74. it('preserves running shells, durable shells and unrelated temporary content', () => {
  75. const retained = [
  76. { ...shellCell(), id: 'running', status: 'running' as const, ephemeral: true },
  77. { ...shellCell(), id: 'pending', status: 'pending' as const, ephemeral: true },
  78. { ...shellCell(), id: 'durable' },
  79. { ...shellCell(), id: 'notice', kind: 'final-summary' as const, ephemeral: true },
  80. ];
  81. const transcript = new TranscriptStore(retained);
  82. const projection = new TuiTurnProjection({ transcript, now: () => 10, onChange: vi.fn() });
  83. projection.beginTurn('next-turn', 10);
  84. expect(transcript.snapshot()).toEqual(retained);
  85. });
  86. it('separates the shell command, literal output and status from adjacent prose', () => {
  87. const view = new TranscriptView(() => [
  88. createTranscriptCell({
  89. id: 'before',
  90. kind: 'final-summary',
  91. status: 'succeeded',
  92. content: 'Before shell',
  93. createdAtMs: 0,
  94. }),
  95. shellCell(),
  96. createTranscriptCell({
  97. id: 'after',
  98. kind: 'assistant',
  99. status: 'succeeded',
  100. content: 'After shell',
  101. createdAtMs: 2,
  102. }),
  103. ]);
  104. const text = stripAnsi(view.render(80).join('\n'));
  105. expect(text).toContain('Shell');
  106. expect(text.indexOf('Before shell')).toBeLessThan(text.indexOf('! printf output'));
  107. expect(text.indexOf('! printf output')).toBeLessThan(text.indexOf('first line'));
  108. expect(text.indexOf('first line')).toBeLessThan(text.indexOf('Exit code: 0'));
  109. expect(text.indexOf('Exit code: 0')).toBeLessThan(text.indexOf('After shell'));
  110. expect(text).toContain(' second line');
  111. });
  112. it.each([0, 1, 2, 4, 5, 8, 12, 30, 80])(
  113. 'keeps multiline Unicode output inside a %s-column terminal',
  114. (width) => {
  115. const cell = {
  116. ...shellCell(),
  117. title: '! echo 中文命令',
  118. content: `中文输出🙂\n${'a'.repeat(90)}`,
  119. };
  120. const lines = renderShellBlock(cell, width);
  121. expect(lines.every((line) => visibleWidth(line) <= width)).toBe(true);
  122. if (width === 0) expect(lines).toEqual([]);
  123. },
  124. );
  125. it('retains shell identity, command and exit status in plain-text inspection and search', () => {
  126. const presentation = presentTranscriptCell(shellCell());
  127. expect(presentation.title).toBe('Shell');
  128. expect(presentation.summary).toBe('! printf output');
  129. expect(presentation.rawText).toContain('! printf output');
  130. expect(presentation.rawText).toContain('first line');
  131. expect(presentation.rawText).toContain('Exit code: 0');
  132. expect(presentation.searchText).toContain('printf output');
  133. expect(presentation.rawText).not.toContain('\u001b');
  134. });
  135. it('labels !! as local-only and keeps output as terminal text', () => {
  136. const text = stripAnsi(
  137. renderShellBlock(
  138. { ...shellCell(), title: '!! echo local', content: '\u001b[2J# heading\n**literal**' },
  139. 60,
  140. ).join('\n'),
  141. );
  142. expect(text).toContain('Shell · Local only');
  143. expect(text).toContain('!! echo local');
  144. expect(text).toContain('# heading');
  145. expect(text).toContain('**literal**');
  146. expect(text).not.toContain('\u001b[2J');
  147. });
  148. it('updates the same block from streaming output to completed status', async () => {
  149. const transcript = new TranscriptStore();
  150. const view = new TranscriptView(transcript);
  151. let finish!: () => void;
  152. const flow = new TuiBashFlow({
  153. transcript,
  154. onChanged: vi.fn(),
  155. execute: async ({ onOutput }) => {
  156. onOutput('streamed output\n');
  157. await new Promise<void>((resolve) => {
  158. finish = resolve;
  159. });
  160. return { exitCode: 0, cancelled: false };
  161. },
  162. });
  163. const running = flow.run(
  164. { command: 'echo streamed output', excludeFromContext: false },
  165. '/workspace',
  166. );
  167. await vi.waitFor(() => expect(transcript.snapshot()[0]?.content).toContain('streamed output'));
  168. expect(transcript.snapshot()[0]).toMatchObject({
  169. kind: 'shell',
  170. title: '! echo streamed output',
  171. });
  172. expect(stripAnsi(view.render(80).join('\n'))).toContain('Running');
  173. finish();
  174. await running;
  175. const text = stripAnsi(view.render(80).join('\n'));
  176. expect(text).toContain('streamed output');
  177. expect(text).toContain('Exit code: 0');
  178. expect(text).not.toContain('Running');
  179. expect(transcript.snapshot()).toHaveLength(1);
  180. expect(flow.takeContext()).toContain('streamed output');
  181. });
  182. it.each([
  183. { exitCode: 7, cancelled: false, status: 'failed', detail: 'Exit code: 7' },
  184. { exitCode: undefined, cancelled: true, status: 'cancelled', detail: 'Command cancelled' },
  185. ])('shows $status with empty output', async ({ exitCode, cancelled, status, detail }) => {
  186. const transcript = new TranscriptStore();
  187. const flow = new TuiBashFlow({
  188. transcript,
  189. onChanged: vi.fn(),
  190. execute: async () => ({ exitCode, cancelled }),
  191. });
  192. await flow.run({ command: 'test', excludeFromContext: false }, '/workspace');
  193. const text = stripAnsi(new TranscriptView(transcript).render(80).join('\n'));
  194. expect(transcript.snapshot()[0]).toMatchObject({ kind: 'shell', status });
  195. expect(text).toContain('Shell');
  196. expect(text).toContain('No output');
  197. expect(text).toContain(detail);
  198. });
  199. it('distinguishes waiting for output from an empty completed command', () => {
  200. const text = stripAnsi(
  201. renderShellBlock(
  202. {
  203. ...shellCell(),
  204. status: 'running',
  205. content: '',
  206. detail: 'Running · Esc or Ctrl+C to cancel',
  207. },
  208. 80,
  209. ).join('\n'),
  210. );
  211. expect(text).toContain('Waiting for output');
  212. expect(text).toContain('Esc or Ctrl+C to cancel');
  213. expect(text).not.toContain('No output');
  214. });
  215. it('keeps a launch error inside the shell block', async () => {
  216. const transcript = new TranscriptStore();
  217. const flow = new TuiBashFlow({
  218. transcript,
  219. onChanged: vi.fn(),
  220. execute: async () => {
  221. throw new Error('launch failed');
  222. },
  223. });
  224. await flow.run({ command: 'test', excludeFromContext: false }, '/workspace');
  225. expect(stripAnsi(new TranscriptView(transcript).render(80).join('\n'))).toContain(
  226. 'Could not run command: launch failed',
  227. );
  228. });
  229. });