headless-preparation-cancellation.test.ts 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188
  1. import { EventEmitter } from 'node:events';
  2. import { mkdtemp, rm } from 'node:fs/promises';
  3. import { tmpdir } from 'node:os';
  4. import { join } from 'node:path';
  5. import { describe, expect, it, vi } from 'vitest';
  6. import { runTuiExec, type TuiHeadlessRuntime } from '../../src/headless/runner.js';
  7. import { ExecDiagnostics } from '../../src/headless/diagnostics.js';
  8. describe('headless preparation cancellation', () => {
  9. it('stops before account access when cancelled during diagnostics preparation', async () => {
  10. const directory = await mkdtemp(join(tmpdir(), 'mcode-cancel-diagnostics-'));
  11. const controller = new AbortController();
  12. const createDiagnostics = ExecDiagnostics.create;
  13. const create = vi.spyOn(ExecDiagnostics, 'create').mockImplementationOnce(async (...args) => {
  14. const diagnostics = await createDiagnostics(...args);
  15. controller.abort();
  16. return diagnostics;
  17. });
  18. const getAccountStatus = vi.fn();
  19. const shutdown = vi.fn(async () => false);
  20. try {
  21. await expect(runTuiExec(
  22. {
  23. prompt: 'Fix it', workspaceDir: '/workspace', version: 'test',
  24. diagnosticsDir: directory,
  25. },
  26. {
  27. runtime: { getAccountStatus } as unknown as TuiHeadlessRuntime,
  28. signal: controller.signal,
  29. shutdown,
  30. stdout: vi.fn(),
  31. stderr: vi.fn(),
  32. },
  33. )).resolves.toBe(130);
  34. expect(getAccountStatus).not.toHaveBeenCalled();
  35. expect(shutdown).toHaveBeenCalledOnce();
  36. } finally {
  37. create.mockRestore();
  38. await rm(directory, { recursive: true, force: true });
  39. }
  40. });
  41. it.each(['account', 'session', 'interaction', 'model'] as const)(
  42. 'does not submit after cancellation during %s preparation',
  43. async (stage) => {
  44. const processRef = new EventEmitter();
  45. let enteredPreparation!: () => void;
  46. const entered = new Promise<void>((resolve) => {
  47. enteredPreparation = resolve;
  48. });
  49. let finishPreparation!: () => void;
  50. const preparing = new Promise<void>((resolve) => {
  51. finishPreparation = resolve;
  52. });
  53. const pause = async (currentStage: typeof stage) => {
  54. if (stage !== currentStage) return;
  55. enteredPreparation();
  56. await preparing;
  57. };
  58. const sendMessage = vi.fn(async function* () {
  59. yield { type: 'message' as const, message: { role: 'assistant' as const, content: 'done' } };
  60. yield { type: 'session-status' as const, status: 'finished' as const };
  61. });
  62. const runtime = {
  63. getAccountStatus: async () => {
  64. await pause('account');
  65. return { status: 'ready', managedTokenPresent: true, warnings: [] };
  66. },
  67. createSession: async () => {
  68. await pause('session');
  69. return { sessionId: 'session-1', workspaceDir: '/workspace' };
  70. },
  71. getPendingQuestionnaire: async () => {
  72. await pause('interaction');
  73. return undefined;
  74. },
  75. listPendingPermissions: async () => [],
  76. listModels: async () => {
  77. await pause('model');
  78. return [{ providerId: 'provider', modelId: 'model', selected: true, effortOptions: ['high'] }];
  79. },
  80. sendMessage,
  81. abortSession: vi.fn(async () => true),
  82. } as unknown as TuiHeadlessRuntime;
  83. const shutdown = vi.fn(async () => false);
  84. const execution = runTuiExec(
  85. { prompt: 'Fix it', workspaceDir: '/workspace', version: '0.1.0', effort: 'high' },
  86. { runtime, processRef, shutdown, stdout: vi.fn(), stderr: vi.fn() },
  87. );
  88. await entered;
  89. processRef.emit('SIGTERM');
  90. finishPreparation();
  91. await expect(execution).resolves.toBe(130);
  92. expect(sendMessage).not.toHaveBeenCalled();
  93. expect(shutdown).toHaveBeenCalledOnce();
  94. expect(processRef.eventNames()).toEqual([]);
  95. },
  96. );
  97. it('cancels an active Run once when the invocation signal and process signal both arrive', async () => {
  98. const processRef = new EventEmitter();
  99. const controller = new AbortController();
  100. let enteredRun!: () => void;
  101. const entered = new Promise<void>((resolve) => {
  102. enteredRun = resolve;
  103. });
  104. const abortSession = vi.fn(async () => true);
  105. const runtime = {
  106. getAccountStatus: async () => ({ status: 'ready', managedTokenPresent: true, warnings: [] }),
  107. createSession: async () => ({ sessionId: 'session-1', workspaceDir: '/workspace' }),
  108. getPendingQuestionnaire: async () => undefined,
  109. listPendingPermissions: async () => [],
  110. async *sendMessage(_request: unknown, signal?: AbortSignal) {
  111. yield { type: 'heartbeat' as const };
  112. enteredRun();
  113. await new Promise<void>((resolve) => {
  114. signal?.addEventListener('abort', () => resolve(), { once: true });
  115. });
  116. },
  117. abortSession,
  118. } as unknown as TuiHeadlessRuntime;
  119. const shutdown = vi.fn(async () => false);
  120. const execution = runTuiExec(
  121. { prompt: 'Fix it', workspaceDir: '/workspace', version: '0.1.0' },
  122. { runtime, processRef, signal: controller.signal, shutdown, stdout: vi.fn(), stderr: vi.fn() },
  123. );
  124. await entered;
  125. controller.abort();
  126. processRef.emit('SIGTERM');
  127. await expect(execution).resolves.toBe(130);
  128. expect(abortSession).toHaveBeenCalledOnce();
  129. expect(shutdown).toHaveBeenCalledOnce();
  130. expect(processRef.eventNames()).toEqual([]);
  131. });
  132. it('stops Session pagination at the next preparation boundary after cancellation', async () => {
  133. const processRef = new EventEmitter();
  134. const listSessionPage = vi.fn(async () => ({ sessions: [], hasMore: false, nextCursor: '' }));
  135. listSessionPage.mockImplementationOnce(async () => {
  136. processRef.emit('SIGTERM');
  137. return { sessions: [], hasMore: true, nextCursor: 'page-2' };
  138. });
  139. const runtime = {
  140. getAccountStatus: async () => ({ status: 'ready', managedTokenPresent: true, warnings: [] }),
  141. listSessionPage,
  142. sendMessage: vi.fn(),
  143. } as unknown as TuiHeadlessRuntime;
  144. const shutdown = vi.fn(async () => false);
  145. await expect(runTuiExec(
  146. { prompt: 'Fix it', workspaceDir: '/workspace', version: '0.1.0', continueSession: true },
  147. { runtime, processRef, shutdown, stdout: vi.fn(), stderr: vi.fn() },
  148. )).resolves.toBe(130);
  149. expect(listSessionPage).toHaveBeenCalledOnce();
  150. expect(runtime.sendMessage).not.toHaveBeenCalled();
  151. expect(shutdown).toHaveBeenCalledOnce();
  152. });
  153. it('keeps a cleanup failure visible when the invocation was already cancelled', async () => {
  154. const controller = new AbortController();
  155. controller.abort();
  156. const getAccountStatus = vi.fn();
  157. const stderr = vi.fn();
  158. const shutdown = vi.fn(async () => true);
  159. await expect(runTuiExec(
  160. { prompt: 'Fix it', workspaceDir: '/workspace', version: '0.1.0' },
  161. {
  162. runtime: { getAccountStatus } as unknown as TuiHeadlessRuntime,
  163. signal: controller.signal,
  164. shutdown,
  165. stdout: vi.fn(),
  166. stderr,
  167. },
  168. )).resolves.toBe(70);
  169. expect(getAccountStatus).not.toHaveBeenCalled();
  170. expect(shutdown).toHaveBeenCalledOnce();
  171. expect(stderr.mock.calls.flat().join('')).toContain('Runtime shutdown did not complete cleanly.');
  172. });
  173. });