run-coordinator.test.ts 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482
  1. import { describe, expect, it, vi } from 'vitest';
  2. import { TuiRunCoordinator, type TuiRunRuntime } from '../../src/application/run-coordinator.js';
  3. import { TuiFailure } from '../../src/failure.js';
  4. describe('TuiRunCoordinator', () => {
  5. it.each([
  6. ['keep', undefined], ['clear', undefined],
  7. ['keep', 'plan-entry'], ['clear', 'plan-entry'],
  8. ['keep', 'plan-exit'], ['clear', 'plan-exit'],
  9. ] as const)('recovers rejected Queue admission with %s while preserving intent %s', async (action, clientIntent) => {
  10. const runtime = createRuntime(async function* (_submission, _signal, options) {
  11. if (!options?.pausedQueueAction) throw new TuiFailure('runtime', 'Queue paused', { code: 'local_session_queue_paused' });
  12. yield { type: 'done' } as const;
  13. });
  14. const onQueuePaused = vi.fn(async () => action === 'clear' ? 'paused-queue-clear' as const : 'paused-queue-keep' as const);
  15. const onAccepted = vi.fn();
  16. const result = await new TuiRunCoordinator(runtime).execute({
  17. turnId: 'turn-1', session: Promise.resolve({ sessionId: 'session-1' }),
  18. content: 'Continue with this instruction', workspace: '/repo', version: 'test', onQueuePaused,
  19. ...(clientIntent ? { clientIntent } : {}),
  20. attachments: [{ type: 'file', fileName: 'input.txt', filePath: '/repo/input.txt', mimeType: 'text/plain' }],
  21. }, undefined, onAccepted);
  22. expect(result.status).toBe('succeeded');
  23. expect(onQueuePaused).toHaveBeenCalledOnce();
  24. expect(onAccepted).toHaveBeenCalledOnce();
  25. expect(runtime.sendMessage).toHaveBeenCalledTimes(2);
  26. expect(runtime.sendMessage.mock.calls[1]?.[0]).toEqual(runtime.sendMessage.mock.calls[0]?.[0]);
  27. expect(runtime.sendMessage.mock.calls[1]?.[2]).toEqual({ pausedQueueAction: action });
  28. });
  29. it('keeps budgeted Queue admission immediate without prompting for recovery', async () => {
  30. const runtime = createRuntime(async function* () {
  31. yield await Promise.reject<never>(new TuiFailure('runtime', 'Queue paused', {
  32. code: 'local_session_queue_paused',
  33. }));
  34. });
  35. const onQueuePaused = vi.fn(async () => 'paused-queue-keep' as const);
  36. const result = await new TuiRunCoordinator(runtime, { nowMs: () => 1_000 }).execute({
  37. ...request('turn-budget'),
  38. policy: { timeoutMs: 60_000 },
  39. onQueuePaused,
  40. });
  41. expect(result.outcome.error?.code).toBe('local_session_queue_paused');
  42. expect(runtime.sendMessage).toHaveBeenCalledOnce();
  43. expect(runtime.sendMessage.mock.calls[0]?.[0]).toMatchObject({ executionDeadlineAtMs: 61_000 });
  44. expect(onQueuePaused).not.toHaveBeenCalled();
  45. });
  46. it('keeps a cancelled paused submission unaccepted and does not resend it', async () => {
  47. const runtime = createRuntime(async function* () {
  48. yield await Promise.reject<never>(new TuiFailure('runtime', 'Queue paused', { code: 'local_session_queue_paused' }));
  49. });
  50. const onAccepted = vi.fn();
  51. const result = await new TuiRunCoordinator(runtime).execute({
  52. turnId: 'turn-1', session: Promise.resolve({ sessionId: 'session-1' }),
  53. content: 'Keep this draft', workspace: '/repo', version: 'test', onQueuePaused: async () => 'cancel',
  54. }, undefined, onAccepted);
  55. expect(result.outcome.error?.code).toBe('PAUSED_QUEUE_SEND_CANCELLED');
  56. expect(runtime.sendMessage).toHaveBeenCalledOnce();
  57. expect(onAccepted).not.toHaveBeenCalled();
  58. });
  59. it('does not retry a Queue error after any frame was accepted', async () => {
  60. const runtime = createRuntime(async function* () {
  61. yield { type: 'heartbeat' } as const;
  62. throw new TuiFailure('runtime', 'Queue paused', { code: 'local_session_queue_paused' });
  63. });
  64. const onQueuePaused = vi.fn(async () => 'paused-queue-keep' as const);
  65. await new TuiRunCoordinator(runtime).execute({
  66. turnId: 'turn-1', session: Promise.resolve({ sessionId: 'session-1' }), content: 'Send once',
  67. workspace: '/repo', version: 'test', onQueuePaused,
  68. });
  69. expect(runtime.sendMessage).toHaveBeenCalledOnce();
  70. expect(onQueuePaused).not.toHaveBeenCalled();
  71. });
  72. it('uses generated sendMessage input and assembles an application-neutral outcome', async () => {
  73. const runtime = createRuntime(async function* () {
  74. yield { type: 'heartbeat' } as const;
  75. yield {
  76. type: 'message',
  77. message: {
  78. id: 'answer-1',
  79. role: 'assistant',
  80. content: 'done',
  81. usage: { inputTokens: 10, outputTokens: 2, reasoningTokens: 1 },
  82. },
  83. } as const;
  84. yield { type: 'session-status', status: 'finished' } as const;
  85. yield { type: 'done' } as const;
  86. });
  87. const observed: string[] = [];
  88. const accepted = vi.fn();
  89. const coordinator = new TuiRunCoordinator(runtime, { nowMs: () => 1_200 });
  90. await expect(
  91. coordinator.execute(
  92. {
  93. turnId: 'turn-1',
  94. session: Promise.resolve({ sessionId: 'session-1' }),
  95. content: 'Fix it',
  96. clientIntent: 'plan-entry',
  97. workspace: '/repo',
  98. version: 'test',
  99. model: { providerId: 'provider', modelId: 'model', variant: 'fast' },
  100. attachments: [
  101. {
  102. type: 'file',
  103. filePath: '/repo/input.txt',
  104. fileName: 'input.txt',
  105. mimeType: 'text/plain',
  106. sizeBytes: 4,
  107. },
  108. ],
  109. },
  110. (event) => observed.push(event.type),
  111. accepted,
  112. ),
  113. ).resolves.toMatchObject({
  114. status: 'succeeded',
  115. outcome: {
  116. sessionId: 'session-1',
  117. turnId: 'turn-1',
  118. status: 'succeeded',
  119. answer: 'done',
  120. model: { providerId: 'provider', modelId: 'model', variant: 'fast' },
  121. usage: { inputTokens: 10, outputTokens: 2, reasoningTokens: 1 },
  122. },
  123. });
  124. expect(runtime.sendMessage).toHaveBeenCalledWith(
  125. {
  126. id: 'session-1',
  127. turnId: 'turn-1',
  128. content: 'Fix it',
  129. clientIntent: 'plan-entry',
  130. model: { providerId: 'provider', modelId: 'model', variant: 'fast' },
  131. attachments: [
  132. {
  133. meta: {
  134. attachmentType: 'file',
  135. fileName: 'input.txt',
  136. mimeType: 'text/plain',
  137. sizeBytes: 4,
  138. },
  139. local: { filePath: '/repo/input.txt' },
  140. },
  141. ],
  142. },
  143. expect.any(AbortSignal),
  144. );
  145. expect(observed).toEqual(['heartbeat', 'message', 'session-status', 'done']);
  146. expect(accepted).toHaveBeenCalledOnce();
  147. });
  148. it('preserves generated admission error keys for queue fallback decisions', async () => {
  149. const runtime = createRuntime(async function* rejectedAdmission() {
  150. yield* [];
  151. throw Object.assign(new Error('Session is busy'), {
  152. category: 'runtime',
  153. code: 'local_session_busy',
  154. retryable: false,
  155. });
  156. });
  157. const coordinator = new TuiRunCoordinator(runtime);
  158. await expect(coordinator.execute(request('turn-busy'))).resolves.toMatchObject({
  159. status: 'failed',
  160. outcome: { error: { code: 'local_session_busy', message: 'Session is busy' } },
  161. });
  162. });
  163. it('aborts the Runtime Session and reports cancellation', async () => {
  164. let started = () => undefined;
  165. const streamStarted = new Promise<void>((resolve) => {
  166. started = resolve;
  167. });
  168. const runtime = createRuntime(async function* pendingCancellation(_req, signal) {
  169. yield* [];
  170. started();
  171. await new Promise<void>((resolve) =>
  172. signal?.addEventListener('abort', () => resolve(), { once: true }),
  173. );
  174. });
  175. const coordinator = new TuiRunCoordinator(runtime);
  176. const running = coordinator.execute(request('turn-cancel'));
  177. await streamStarted;
  178. await expect(coordinator.abort()).resolves.toBe(true);
  179. await expect(running).resolves.toMatchObject({ status: 'cancelled' });
  180. expect(runtime.abortSession).toHaveBeenCalledWith({
  181. id: 'session-1',
  182. turnId: 'turn-cancel',
  183. reason: 'user_stop',
  184. });
  185. });
  186. it('keeps timeout and maxSteps in the process-local coordinator', async () => {
  187. vi.useFakeTimers();
  188. try {
  189. const timeoutRuntime = createRuntime(async function* pendingTimeout(_req, signal) {
  190. yield* [];
  191. await new Promise<void>((resolve) =>
  192. signal?.addEventListener('abort', () => resolve(), { once: true }),
  193. );
  194. });
  195. const timed = new TuiRunCoordinator(timeoutRuntime, { nowMs: () => 1_000 }).execute({
  196. ...request('turn-timeout'),
  197. policy: { timeoutMs: 20 },
  198. });
  199. await vi.advanceTimersByTimeAsync(19);
  200. expect(timeoutRuntime.sendMessage).toHaveBeenCalledWith(
  201. expect.objectContaining({ executionDeadlineAtMs: 1_020 }),
  202. expect.any(AbortSignal),
  203. );
  204. expect(timeoutRuntime.abortSession).not.toHaveBeenCalled();
  205. await vi.advanceTimersByTimeAsync(1);
  206. await expect(timed).resolves.toMatchObject({ status: 'timeout' });
  207. expect(timeoutRuntime.abortSession).toHaveBeenCalledWith(
  208. expect.objectContaining({ reason: 'timeout' }),
  209. );
  210. } finally {
  211. vi.useRealTimers();
  212. }
  213. const limitRuntime = createRuntime(async function* () {
  214. yield { type: 'message', message: { role: 'assistant', content: 'first' } } as const;
  215. yield { type: 'message', message: { role: 'assistant', content: 'second' } } as const;
  216. });
  217. await expect(
  218. new TuiRunCoordinator(limitRuntime).execute({
  219. ...request('turn-limit'),
  220. policy: { maxSteps: 1 },
  221. }),
  222. ).resolves.toMatchObject({ status: 'limit_exceeded', outcome: { answer: 'first' } });
  223. expect(limitRuntime.abortSession).toHaveBeenCalledWith(
  224. expect.objectContaining({ reason: 'max_steps' }),
  225. );
  226. });
  227. it('reports a Runtime questionnaire as awaiting continuation without aborting it', async () => {
  228. const runtime = createRuntime(async function* () {
  229. yield {
  230. type: 'generic',
  231. eventType: 'runtime.action-required',
  232. data: { kind: 'questionnaire' },
  233. } as const;
  234. });
  235. await expect(
  236. new TuiRunCoordinator(runtime).execute(request('turn-questionnaire')),
  237. ).resolves.toMatchObject({
  238. status: 'awaiting-user-continuation',
  239. outcome: { error: { code: 'QUESTIONNAIRE_REQUIRED' } },
  240. });
  241. expect(runtime.abortSession).not.toHaveBeenCalled();
  242. });
  243. it('leaves permission interaction ownership to the active surface', async () => {
  244. const runtime = createRuntime(async function* () {
  245. yield {
  246. type: 'generic',
  247. eventType: 'permission.ask',
  248. data: { requestId: 'permission-1' },
  249. } as const;
  250. yield {
  251. type: 'message',
  252. message: { id: 'answer-1', role: 'assistant', content: 'continued' },
  253. } as const;
  254. yield { type: 'done' } as const;
  255. });
  256. const observed: string[] = [];
  257. await expect(
  258. new TuiRunCoordinator(runtime).execute(request('turn-permission'), (event) =>
  259. observed.push(event.type === 'generic' ? event.eventType : event.type),
  260. ),
  261. ).resolves.toMatchObject({
  262. status: 'succeeded',
  263. outcome: { answer: 'continued' },
  264. });
  265. expect(observed).toEqual(['permission.ask', 'message', 'done']);
  266. expect(runtime.abortSession).not.toHaveBeenCalled();
  267. });
  268. it('fails a Headless execution that completes without a final assistant response', async () => {
  269. const runtime = createRuntime(async function* () {
  270. yield { type: 'session-status', status: 'finished' } as const;
  271. yield { type: 'done' } as const;
  272. });
  273. await expect(
  274. new TuiRunCoordinator(runtime).execute({
  275. ...request('turn-empty'),
  276. policy: { requireAnswer: true },
  277. }),
  278. ).resolves.toMatchObject({
  279. status: 'failed',
  280. outcome: { error: { code: 'EMPTY_RESPONSE' } },
  281. });
  282. });
  283. it('accepts a final assistant response delivered only as text deltas', async () => {
  284. const runtime = createRuntime(async function* () {
  285. yield { type: 'delta', role: 'assistant', content: 'delta ' } as const;
  286. yield { type: 'delta', role: 'assistant', content: 'answer' } as const;
  287. yield { type: 'session-status', status: 'finished' } as const;
  288. });
  289. await expect(
  290. new TuiRunCoordinator(runtime).execute({
  291. ...request('turn-delta-answer'),
  292. policy: { requireAnswer: true },
  293. }),
  294. ).resolves.toMatchObject({
  295. status: 'succeeded',
  296. outcome: { answer: 'delta answer' },
  297. });
  298. });
  299. it('records answer selection and replacement without storing the answer', async () => {
  300. const runtime = createRuntime(async function* () {
  301. yield { type: 'message', message: { id: 'pre-tool', role: 'assistant', content: 'private prelude',
  302. toolCalls: [{ id: 'tool-1', name: 'read', status: 2 }],
  303. } } as const;
  304. yield { type: 'message', message: { id: 'final-1', role: 'assistant', content: 'private completed' } } as const;
  305. yield { type: 'delta', role: 'assistant', content: 'private trailing draft' } as const;
  306. });
  307. const selected = vi.fn();
  308. const result = await new TuiRunCoordinator(runtime, { onAnswerSelection: selected }).execute(request('selection'));
  309. expect(result.outcome.answer).toBe('private trailing draft');
  310. expect(selected.mock.calls.map(([event]) => event)).toEqual([
  311. expect.objectContaining({ kind: 'answer_excluded', messageId: 'pre-tool', reason: 'tool_calls' }),
  312. expect.objectContaining({ kind: 'answer_selected', messageId: 'final-1', answerSource: 'completed_message' }),
  313. expect.objectContaining({ kind: 'answer_selected', answerSource: 'trailing_draft', replacedAnswer: true }),
  314. ]);
  315. expect(JSON.stringify(selected.mock.calls)).not.toContain('private');
  316. });
  317. it('keeps streamed final text when the completion event has an empty content field', async () => {
  318. const runtime = createRuntime(async function* () {
  319. yield { type: 'delta', role: 'assistant', content: 'streamed answer' } as const;
  320. yield {
  321. type: 'message',
  322. message: { role: 'assistant', kind: 'final', content: '' },
  323. } as const;
  324. });
  325. await expect(
  326. new TuiRunCoordinator(runtime).execute({
  327. ...request('turn-empty-completion'),
  328. policy: { requireAnswer: true },
  329. }),
  330. ).resolves.toMatchObject({
  331. status: 'succeeded',
  332. outcome: { answer: 'streamed answer' },
  333. });
  334. });
  335. it('publishes only the final assistant response after a tool call', async () => {
  336. const runtime = createRuntime(async function* () {
  337. yield { type: 'delta', role: 'assistant', content: 'I will inspect it.' } as const;
  338. yield {
  339. type: 'message',
  340. message: {
  341. role: 'assistant',
  342. content: 'I will inspect it.',
  343. toolCalls: [{ id: 'read-1', name: 'read', status: 'completed' }],
  344. },
  345. } as const;
  346. yield { type: 'delta', role: 'assistant', content: 'The final answer.' } as const;
  347. yield {
  348. type: 'message',
  349. message: { role: 'assistant', kind: 'final', content: 'The final answer.' },
  350. } as const;
  351. });
  352. const onOutcome = vi.fn();
  353. await expect(
  354. new TuiRunCoordinator(runtime).execute(
  355. { ...request('turn-tool-final'), policy: { requireAnswer: true } },
  356. undefined,
  357. undefined,
  358. onOutcome,
  359. ),
  360. ).resolves.toMatchObject({
  361. status: 'succeeded',
  362. outcome: { answer: 'The final answer.' },
  363. });
  364. expect(onOutcome).toHaveBeenCalledWith(
  365. expect.objectContaining({ status: 'succeeded', answer: 'The final answer.' }),
  366. );
  367. });
  368. it('fails automation when a tool call has no final assistant response', async () => {
  369. const runtime = createRuntime(async function* () {
  370. yield { type: 'delta', role: 'assistant', content: 'I will inspect it.' } as const;
  371. yield {
  372. type: 'message',
  373. message: {
  374. role: 'assistant',
  375. content: 'I will inspect it.',
  376. toolCalls: [{ id: 'read-1', name: 'read', status: 'completed' }],
  377. },
  378. } as const;
  379. yield { type: 'done' } as const;
  380. });
  381. const onOutcome = vi.fn();
  382. await expect(
  383. new TuiRunCoordinator(runtime).execute(
  384. { ...request('turn-tool-empty'), policy: { requireAnswer: true } },
  385. undefined,
  386. undefined,
  387. onOutcome,
  388. ),
  389. ).resolves.toMatchObject({
  390. status: 'failed',
  391. outcome: { answer: null, error: { code: 'EMPTY_RESPONSE' } },
  392. });
  393. expect(onOutcome).toHaveBeenCalledWith(
  394. expect.objectContaining({
  395. status: 'failed',
  396. error: expect.objectContaining({ code: 'EMPTY_RESPONSE' }),
  397. }),
  398. );
  399. });
  400. it('turns an automation result write failure into a turn failure', async () => {
  401. const runtime = createRuntime(async function* () {
  402. yield { type: 'message', message: { role: 'assistant', content: 'answer' } } as const;
  403. });
  404. await expect(
  405. new TuiRunCoordinator(runtime).execute(
  406. request('turn-write-failed'),
  407. undefined,
  408. undefined,
  409. async () => {
  410. throw new Error('disk full');
  411. },
  412. ),
  413. ).resolves.toMatchObject({
  414. status: 'failed',
  415. outcome: { error: { code: 'AUTOMATION_RESULT_WRITE_FAILED' } },
  416. });
  417. });
  418. it('maps a Runtime rewind during Headless execution to a content-review block', async () => {
  419. const runtime = createRuntime(async function* () {
  420. yield { type: 'generic', eventType: 'messages-rewound', data: {} } as const;
  421. yield { type: 'session-status', status: 'finished' } as const;
  422. yield { type: 'done' } as const;
  423. });
  424. await expect(
  425. new TuiRunCoordinator(runtime).execute(request('turn-content-blocked')),
  426. ).resolves.toMatchObject({
  427. status: 'failed',
  428. outcome: { error: { code: 'CONTENT_REVIEW_BLOCKED' } },
  429. });
  430. });
  431. });
  432. function request(turnId: string) {
  433. return {
  434. turnId,
  435. session: Promise.resolve({ sessionId: 'session-1' }),
  436. content: 'Continue',
  437. workspace: '/repo',
  438. version: 'test',
  439. };
  440. }
  441. function createRuntime(send: TuiRunRuntime['sendMessage']): TuiRunRuntime & {
  442. sendMessage: ReturnType<typeof vi.fn<TuiRunRuntime['sendMessage']>>;
  443. abortSession: ReturnType<typeof vi.fn<TuiRunRuntime['abortSession']>>;
  444. } {
  445. return {
  446. sendMessage: vi.fn(send),
  447. abortSession: vi.fn(async () => true),
  448. };
  449. }