headless-runner.test.ts 43 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202
  1. import { EventEmitter } from 'node:events';
  2. import { mkdtemp, readFile, 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 } from '../../src/headless/runner.js';
  7. import type { TuiMessage, TuiStreamEvent } from '../../src/runtime/stream-events.js';
  8. const successEvents: readonly TuiStreamEvent[] = [
  9. { type: 'message', message: { id: 'assistant-1', role: 'assistant', content: 'fixed' } },
  10. { type: 'session-status', status: 'finished' },
  11. ];
  12. const reviewXml = `<annotation-result version="2" source="code-review" review-run-id="review_1" trigger="slash" mode="inline" verdict="needs-changes"><summary>Found one issue.</summary><annotations><annotation id="annotation_1" kind="code-review" priority="P1"><target type="file" uri="src/demo.ts"><selector type="line-range" side="new" start-line="10" end-line="10" anchor-revision="sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" context-before="1" context-after="1" /></target><title>Guard the value</title><content>This value can be undefined.</content></annotation></annotations></annotation-result>`;
  13. function accountReady() {
  14. return Promise.resolve({
  15. status: 'ready' as const,
  16. managedTokenPresent: true,
  17. warnings: [],
  18. });
  19. }
  20. function runtimeWith(events: readonly TuiStreamEvent[] = successEvents) {
  21. return {
  22. getAccountStatus: vi.fn(accountReady),
  23. listModels: vi.fn(async () => [
  24. {
  25. providerId: 'default-provider',
  26. modelId: 'default-model',
  27. variant: 'balanced',
  28. selected: true,
  29. },
  30. ]),
  31. setPermissionMode: vi.fn(async (mode) => mode),
  32. createSession: vi.fn(async () => ({
  33. sessionId: 'session-1',
  34. workspaceDir: '/tmp/workspace',
  35. })),
  36. getSession: vi.fn(async () => ({
  37. sessionId: 'session-1',
  38. workspaceDir: '/tmp/workspace',
  39. archived: false,
  40. })),
  41. listSessionPage: vi.fn(async () => ({ sessions: [], hasMore: false })),
  42. getPendingQuestionnaire: vi.fn(async () => undefined),
  43. listPendingPermissions: vi.fn(async () => []),
  44. getSessionUsage: vi.fn(async () => ({ rows: [] })),
  45. listMessagePage: vi.fn(async () => ({ messages: [], hasMore: false })),
  46. getActiveRun: vi.fn(async () => ({
  47. schemaVersion: 1 as const,
  48. sessionId: 'session-1',
  49. state: 'running' as const,
  50. turnId: 'turn-1',
  51. actions: { steer: true },
  52. })),
  53. sendMessage: vi.fn(async function* () {
  54. for (const event of events) yield event;
  55. }),
  56. watchSessionTurn: vi.fn(async function* () {
  57. yield { type: 'session-status' as const, status: 'finished' as const };
  58. }),
  59. abortSession: vi.fn(async () => true),
  60. steer: vi.fn(async () => ({ queueItemId: 'queue-1' })),
  61. };
  62. }
  63. describe('runTuiExec response usage', () => {
  64. const completed: TuiMessage = { id: 'first', turnId: 'turn-1', role: 'assistant', kind: 'final', content: 'fixed', usage: { inputTokens: 10, outputTokens: 4, cacheReadTokens: 50, reasoningTokens: 2, totalTokens: 64 } };
  65. function usageRuntime(messages: TuiMessage[], terminal: TuiStreamEvent = { type: 'session-status', status: 'finished' }) {
  66. const runtime = runtimeWith([...messages.map((message) => ({ type: 'message' as const, message })), terminal]);
  67. runtime.listMessagePage.mockResolvedValue({ messages, hasMore: false } as never);
  68. return runtime;
  69. }
  70. async function resultFor(runtime: ReturnType<typeof runtimeWith>, format: 'json' | 'stream-json' = 'json') {
  71. const stdout = vi.fn();
  72. await runTuiExec(
  73. { prompt: 'Fix it', workspaceDir: '/tmp/workspace', version: '0.1.0', format },
  74. { runtime, stdout, stderr: vi.fn(), shutdown: async () => undefined, createTurnId: () => 'turn-1' },
  75. );
  76. const records = stdout.mock.calls.map(([line]) => JSON.parse(line));
  77. return format === 'json' ? records[0] : records;
  78. }
  79. it('keeps both completed responses when the analytics projection only contains the first', async () => {
  80. const messages = [
  81. { id: 'first', turnId: 'turn-1', role: 'assistant' as const, toolCalls: [{ id: 'tool-1', name: 'read', arguments: '{}' }], usage: { inputTokens: 10, outputTokens: 2, cacheReadTokens: 50, totalTokens: 62 } },
  82. { id: 'second', turnId: 'turn-1', role: 'assistant' as const, content: 'fixed', usage: { inputTokens: 20, outputTokens: 3, totalTokens: 23 } },
  83. ];
  84. const runtime = runtimeWith([
  85. ...messages.map((message) => ({ type: 'message' as const, message })),
  86. { type: 'session-status', status: 'finished' },
  87. ]);
  88. runtime.listMessagePage.mockResolvedValue({ messages, hasMore: false } as never);
  89. runtime.getSessionUsage.mockResolvedValue({ rows: [{ id: 1, turnId: 'turn-1', inputTokens: 10, outputTokens: 2, cacheReadTokens: 50 }] } as never);
  90. const stdout = vi.fn();
  91. await expect(runTuiExec(
  92. { prompt: 'Fix it', workspaceDir: '/tmp/workspace', version: '0.1.0', format: 'json' },
  93. { runtime, stdout, stderr: vi.fn(), shutdown: async () => undefined, createTurnId: () => 'turn-1' },
  94. )).resolves.toBe(0);
  95. expect(JSON.parse(stdout.mock.calls[0]?.[0] ?? '')).toMatchObject({
  96. usage: { inputTokens: 30, outputTokens: 5, cacheReadTokens: 50, totalTokens: 35 },
  97. usageSource: 'completed_responses',
  98. usageIncomplete: false,
  99. });
  100. });
  101. it('merges corrected saved usage by response ID without erasing earlier buckets', async () => {
  102. const runtime = usageRuntime([completed, completed]);
  103. runtime.listMessagePage.mockResolvedValue({ messages: [{ ...completed, usage: { inputTokens: 6 } }], hasMore: false } as never);
  104. expect(await resultFor(runtime)).toMatchObject({
  105. usage: { inputTokens: 6, outputTokens: 4, reasoningTokens: 2, cacheReadTokens: 50, totalTokens: 10 },
  106. usageSource: 'completed_responses', usageIncomplete: false,
  107. });
  108. });
  109. it.each(['inputTokens', 'outputTokens'] as const)(
  110. 'marks a response missing %s incomplete even when other responses supply that bucket',
  111. async (missingField) => {
  112. const partial = {
  113. ...completed,
  114. id: 'partial',
  115. usage: missingField === 'inputTokens' ? { outputTokens: 0 } : { inputTokens: 0 },
  116. };
  117. expect(await resultFor(usageRuntime([completed, partial]))).toMatchObject({
  118. status: 'succeeded',
  119. usage: { inputTokens: 10, outputTokens: 4, totalTokens: 14 },
  120. usageSource: 'completed_responses',
  121. usageIncomplete: true,
  122. });
  123. },
  124. );
  125. it('treats explicit zero input and output as known complete usage', async () => {
  126. const response = { ...completed, usage: { inputTokens: 0, outputTokens: 0 } };
  127. expect(await resultFor(usageRuntime([response]))).toMatchObject({
  128. usage: { inputTokens: 0, outputTokens: 0, totalTokens: 0 },
  129. usageSource: 'completed_responses',
  130. usageIncomplete: false,
  131. });
  132. });
  133. it('includes saved responses absent from the live stream and reads every history page', async () => {
  134. const second = { ...completed, id: 'second', usage: { inputTokens: 20, outputTokens: 3 } };
  135. const runtime = usageRuntime([second]);
  136. runtime.listMessagePage.mockResolvedValueOnce({ messages: [second], hasMore: true, nextCursor: 'older' } as never)
  137. .mockResolvedValueOnce({ messages: [completed, { ...completed, id: 'old-turn', turnId: 'turn-old' }], hasMore: false } as never);
  138. expect(await resultFor(runtime)).toMatchObject({ usage: { inputTokens: 30, outputTokens: 7, cacheReadTokens: 50, totalTokens: 37 }, usageIncomplete: false });
  139. expect(runtime.listMessagePage).toHaveBeenCalledTimes(2);
  140. expect(runtime.listMessagePage).toHaveBeenLastCalledWith('session-1', { limit: 200, before: 'older' });
  141. });
  142. it('reports complete response coverage after terminal history recovery', async () => {
  143. const runtime = usageRuntime([]);
  144. runtime.sendMessage.mockImplementation(async function* () { yield* []; });
  145. runtime.getActiveRun.mockResolvedValue({ schemaVersion: 1, sessionId: 'session-1', state: 'idle', actions: {} } as never);
  146. runtime.getSession.mockResolvedValue({ sessionId: 'session-1', workspaceDir: '/tmp/workspace', status: 'idle' } as never);
  147. runtime.listMessagePage.mockResolvedValue({ messages: [completed], hasMore: false } as never);
  148. expect(await resultFor(runtime)).toMatchObject({ usage: { inputTokens: 10, outputTokens: 4, totalTokens: 14 }, usageIncomplete: false });
  149. });
  150. it.each([
  151. { name: 'missing usage', message: { ...completed, id: 'missing', usage: undefined } },
  152. { name: 'missing identity', message: { ...completed, id: undefined, usage: { inputTokens: 3 } } },
  153. { name: 'invalid usage', message: { ...completed, id: 'invalid', usage: { inputTokens: -1, outputTokens: 1 } } },
  154. ])('preserves known usage but marks $name incomplete', async ({ message }) => {
  155. const result = await resultFor(usageRuntime([completed, message]));
  156. expect(result).toMatchObject({ usageSource: 'completed_responses', usageIncomplete: true });
  157. expect(result.usage.inputTokens).toBeGreaterThanOrEqual(10);
  158. expect(result.usage.cacheReadTokens).toBe(50);
  159. });
  160. it.each(['aborted', 'error'] as const)('keeps completed usage after an %s terminal without claiming complete billing', async (status) => {
  161. expect(await resultFor(usageRuntime([completed], { type: 'session-status', status }))).toMatchObject({
  162. status: status === 'aborted' ? 'cancelled' : 'failed',
  163. usage: { inputTokens: 10, outputTokens: 4, totalTokens: 14 },
  164. usageSource: 'completed_responses', usageIncomplete: true,
  165. });
  166. });
  167. it('keeps known stream usage when final history inspection fails', async () => {
  168. const runtime = usageRuntime([completed]);
  169. runtime.listMessagePage.mockRejectedValue(new Error('inspection unavailable'));
  170. expect(await resultFor(runtime)).toMatchObject({ usage: { inputTokens: 10, outputTokens: 4, totalTokens: 14 }, usageSource: 'completed_responses', usageIncomplete: true });
  171. });
  172. it('bounds final inspection time and does not let stalled analytics hide stream usage', async () => {
  173. vi.useFakeTimers();
  174. try {
  175. const runtime = usageRuntime([completed]);
  176. let finishPage: (page: unknown) => void = () => undefined;
  177. runtime.listMessagePage.mockImplementation(() => new Promise((resolve) => { finishPage = resolve as (page: unknown) => void; }));
  178. runtime.getSessionUsage.mockImplementation(() => new Promise(() => undefined));
  179. const result = resultFor(runtime);
  180. await vi.advanceTimersByTimeAsync(1_001);
  181. expect(await result).toMatchObject({ status: 'succeeded', usage: { totalTokens: 14 }, usageSource: 'completed_responses', usageIncomplete: true });
  182. finishPage({ messages: [completed], hasMore: true, nextCursor: 'late-page' });
  183. await vi.advanceTimersByTimeAsync(0);
  184. expect(runtime.listMessagePage).toHaveBeenCalledTimes(1);
  185. } finally {
  186. vi.useRealTimers();
  187. }
  188. });
  189. it('does not claim completeness when history pagination stalls', async () => {
  190. const runtime = usageRuntime([completed]);
  191. runtime.listMessagePage.mockResolvedValue({ messages: [completed], hasMore: true, nextCursor: 'same' } as never);
  192. expect(await resultFor(runtime)).toMatchObject({ usage: { totalTokens: 14 }, usageIncomplete: true });
  193. expect(runtime.listMessagePage).toHaveBeenCalledTimes(2);
  194. });
  195. it('marks incomplete history with a missing cursor or exhausted page limit', async () => {
  196. for (const mode of ['missing-cursor', 'page-limit']) {
  197. const runtime = usageRuntime([completed]);
  198. let page = 0;
  199. runtime.listMessagePage.mockImplementation(async () => ({ messages: [completed], hasMore: true, ...(mode === 'page-limit' ? { nextCursor: String(++page) } : {}) }) as never);
  200. expect(await resultFor(runtime)).toMatchObject({ usage: { totalTokens: 14 }, usageIncomplete: true });
  201. expect(runtime.listMessagePage).toHaveBeenCalledTimes(mode === 'page-limit' ? 100 : 1);
  202. }
  203. });
  204. it.each(['bucket', 'total'])('omits a non-finite %s sum and marks usage incomplete', async (kind) => {
  205. const messages = kind === 'bucket'
  206. ? [{ ...completed, usage: { inputTokens: Number.MAX_VALUE, outputTokens: 2 } }, { ...completed, id: 'second', usage: { inputTokens: Number.MAX_VALUE, outputTokens: 2 } }]
  207. : [{ ...completed, usage: { inputTokens: Number.MAX_VALUE, outputTokens: Number.MAX_VALUE } }];
  208. const result = await resultFor(usageRuntime(messages));
  209. expect(result).toMatchObject({ usageSource: 'completed_responses', usageIncomplete: true });
  210. expect(Object.values(result.usage).every((value) => typeof value === 'number' && Number.isFinite(value))).toBe(true);
  211. expect(result.usage).not.toHaveProperty(kind === 'bucket' ? 'inputTokens' : 'totalTokens');
  212. });
  213. it('labels deduplicated analytics-only usage as a partial fallback and leaves missing fields absent', async () => {
  214. const runtime = runtimeWith();
  215. const row = { id: 1, turnId: 'turn-1', inputTokens: 8 };
  216. runtime.getSessionUsage.mockResolvedValue({ rows: [row, row, { ...row, turnId: 'other', id: 2 }] } as never);
  217. const result = await resultFor(runtime);
  218. expect(result).toMatchObject({ usage: { inputTokens: 8, totalTokens: 8 }, usageSource: 'analytics_fallback', usageIncomplete: true });
  219. expect(result.usage).not.toHaveProperty('outputTokens');
  220. });
  221. it('leaves unavailable usage absent instead of fabricating zero', async () => {
  222. const result = await resultFor(runtimeWith());
  223. expect(result).toMatchObject({ usageSource: 'unavailable', usageIncomplete: true });
  224. expect(result).not.toHaveProperty('usage');
  225. });
  226. it('preserves usage completeness metadata in both JSONL terminal records', async () => {
  227. const records = await resultFor(usageRuntime([completed]), 'stream-json');
  228. expect(records.find((record: { type: string }) => record.type === 'turn.completed')).toMatchObject({ usage: { totalTokens: 14 }, usageSource: 'completed_responses', usageIncomplete: false });
  229. expect(records.at(-1).result).toMatchObject({ usage: { totalTokens: 14 }, usageSource: 'completed_responses', usageIncomplete: false });
  230. });
  231. it.each(['stream', 'history'] as const)('marks compaction usage unavailable through %s without changing response totals', async (source) => {
  232. const marker: TuiMessage = { id: 'compaction-attempt', turnId: 'turn-1', role: 'assistant', kind: 'compaction' };
  233. const runtime = usageRuntime(source === 'stream' ? [marker, completed] : [completed]);
  234. runtime.listMessagePage.mockResolvedValue({ messages: source === 'history' ? [marker, completed] : [completed], hasMore: false } as never);
  235. const result = await resultFor(runtime);
  236. expect(result).toMatchObject({ status: 'succeeded', usageSource: 'completed_responses', usageIncomplete: true });
  237. expect(result.usage).toEqual({ inputTokens: 10, outputTokens: 4, cacheReadTokens: 50, reasoningTokens: 2, totalTokens: 14 });
  238. });
  239. });
  240. describe('runTuiExec', () => {
  241. it('sends a structured Review request and returns a pass result', async () => {
  242. const stdout = vi.fn();
  243. const runtime = runtimeWith([
  244. {
  245. type: 'message',
  246. message: {
  247. id: 'review-pass',
  248. role: 'assistant',
  249. content: 'No reportable issues were found.',
  250. origin: { reviewOutcome: 'pass' },
  251. },
  252. },
  253. { type: 'session-status', status: 'finished' },
  254. ]);
  255. await expect(
  256. runTuiExec(
  257. {
  258. prompt: 'Please review my uncommitted changes.',
  259. workspaceDir: '/tmp/workspace',
  260. version: '0.1.0',
  261. format: 'json',
  262. reviewRequest: { scope: 'local_changes' },
  263. },
  264. {
  265. runtime,
  266. stdout,
  267. stderr: vi.fn(),
  268. shutdown: async () => undefined,
  269. createTurnId: () => 'turn-1',
  270. },
  271. ),
  272. ).resolves.toBe(0);
  273. expect(runtime.sendMessage).toHaveBeenCalledWith(
  274. expect.objectContaining({ reviewRequest: { scope: 'local_changes' } }),
  275. expect.any(AbortSignal),
  276. );
  277. expect(JSON.parse(stdout.mock.calls[0]?.[0] ?? '')).toMatchObject({
  278. status: 'succeeded',
  279. output: {
  280. schemaVersion: 1,
  281. type: 'review.result',
  282. scope: 'local_changes',
  283. verdict: 'pass',
  284. summary: 'No reportable issues were found.',
  285. findings: [],
  286. },
  287. });
  288. });
  289. it('renders validated findings as comments and keeps exit code zero', async () => {
  290. const root = await mkdtemp(join(tmpdir(), 'mcode-exec-review-'));
  291. try {
  292. const stdout = vi.fn();
  293. const runtime = runtimeWith([
  294. {
  295. type: 'message',
  296. message: {
  297. id: 'review-findings',
  298. role: 'assistant',
  299. content: reviewXml,
  300. origin: { reviewOutcome: 'needs_changes' },
  301. },
  302. },
  303. { type: 'session-status', status: 'finished' },
  304. ]);
  305. const lastMessage = join(root, 'review.txt');
  306. await expect(
  307. runTuiExec(
  308. {
  309. prompt: 'Please review my uncommitted changes.',
  310. workspaceDir: '/tmp/workspace',
  311. version: '0.1.0',
  312. format: 'text',
  313. outputLastMessagePath: lastMessage,
  314. reviewRequest: { scope: 'local_changes' },
  315. },
  316. { runtime, stdout, stderr: vi.fn(), shutdown: async () => undefined },
  317. ),
  318. ).resolves.toBe(0);
  319. expect(stdout).toHaveBeenCalledWith(expect.stringContaining('[P1] Guard the value'));
  320. expect(stdout).toHaveBeenCalledWith(expect.stringContaining('src/demo.ts:10 (new)'));
  321. expect(stdout).not.toHaveBeenCalledWith(expect.stringContaining('<annotation-result'));
  322. expect(await readFile(lastMessage, 'utf8')).toContain('[P1] Guard the value');
  323. expect(await readFile(lastMessage, 'utf8')).not.toContain('<annotation-result');
  324. } finally {
  325. await rm(root, { recursive: true, force: true });
  326. }
  327. });
  328. it('retains invalid JSON and its selected message without polluting stdout', async () => {
  329. const root = await mkdtemp(join(tmpdir(), 'mcode-runner-diagnostics-'));
  330. try {
  331. const stdout = vi.fn();
  332. const runtime = runtimeWith();
  333. const code = await runTuiExec({
  334. prompt: 'Review', workspaceDir: '/tmp/workspace', version: 'test',
  335. format: 'json', outputSchema: { type: 'object' }, diagnosticsDir: root,
  336. outputLastMessagePath: join(root, 'success.txt'),
  337. }, { runtime, stdout, stderr: vi.fn(), shutdown: async () => false });
  338. expect(code).not.toBe(0);
  339. const result = JSON.parse(stdout.mock.calls.map(([chunk]) => chunk).join(''));
  340. expect(result).toMatchObject({ status: 'failed', error: { code: 'STRUCTURED_OUTPUT_INVALID' } });
  341. expect(await readFile(join(root, 'failure-answer.txt'), 'utf8')).toBe('fixed');
  342. expect(JSON.parse(await readFile(join(root, 'failure.json'), 'utf8'))).toMatchObject({
  343. validationKind: 'invalid_json', answerSource: 'completed_message', messageId: 'assistant-1',
  344. });
  345. await expect(readFile(join(root, 'success.txt'))).rejects.toMatchObject({ code: 'ENOENT' });
  346. } finally {
  347. await rm(root, { recursive: true, force: true });
  348. }
  349. });
  350. it('streams rendered Review comments without exposing annotation XML', async () => {
  351. const stdout: string[] = [];
  352. const runtime = runtimeWith([
  353. {
  354. type: 'message',
  355. message: {
  356. id: 'review-findings',
  357. role: 'assistant',
  358. content: reviewXml,
  359. origin: { reviewOutcome: 'needs_changes' },
  360. },
  361. },
  362. { type: 'session-status', status: 'finished' },
  363. ]);
  364. await expect(
  365. runTuiExec(
  366. {
  367. prompt: 'Please review my uncommitted changes.',
  368. workspaceDir: '/tmp/workspace',
  369. version: '0.1.0',
  370. format: 'stream-json',
  371. reviewRequest: { scope: 'local_changes' },
  372. },
  373. {
  374. runtime,
  375. stdout: (value) => stdout.push(value),
  376. stderr: vi.fn(),
  377. shutdown: async () => undefined,
  378. createTurnId: () => 'turn-1',
  379. },
  380. ),
  381. ).resolves.toBe(0);
  382. const records = stdout
  383. .join('')
  384. .trim()
  385. .split('\n')
  386. .map((line) => JSON.parse(line));
  387. expect(records).toContainEqual(
  388. expect.objectContaining({
  389. type: 'item.completed',
  390. item: expect.objectContaining({
  391. type: 'agent_message',
  392. content: expect.stringContaining('[P1] Guard the value'),
  393. }),
  394. }),
  395. );
  396. expect(stdout.join('')).not.toContain('<annotation-result');
  397. expect(records.at(-1)).toMatchObject({
  398. type: 'exec.completed',
  399. result: {
  400. status: 'succeeded',
  401. output: { type: 'review.result', verdict: 'needs_changes' },
  402. },
  403. });
  404. });
  405. it('fails when Runtime marks the Review result invalid', async () => {
  406. const stdout = vi.fn();
  407. const stderr = vi.fn();
  408. const runtime = runtimeWith([
  409. {
  410. type: 'message',
  411. message: {
  412. id: 'review-invalid',
  413. role: 'assistant',
  414. content: 'The model returned an invalid review result.',
  415. origin: { reviewOutcome: 'failed' },
  416. },
  417. },
  418. { type: 'session-status', status: 'finished' },
  419. ]);
  420. await expect(
  421. runTuiExec(
  422. {
  423. prompt: 'Please review my uncommitted changes.',
  424. workspaceDir: '/tmp/workspace',
  425. version: '0.1.0',
  426. format: 'json',
  427. reviewRequest: { scope: 'local_changes' },
  428. },
  429. { runtime, stdout, stderr, shutdown: async () => undefined },
  430. ),
  431. ).resolves.toBe(4);
  432. expect(JSON.parse(stdout.mock.calls[0]?.[0] ?? '')).toMatchObject({
  433. status: 'failed',
  434. error: { code: 'REVIEW_RESULT_INVALID' },
  435. });
  436. expect(stderr).toHaveBeenCalledWith(expect.stringContaining('mcode exec failed'));
  437. });
  438. it('writes the raw final message and reports durable per-Turn model and usage facts', async () => {
  439. const root = await mkdtemp(join(tmpdir(), 'mcode-exec-result-'));
  440. try {
  441. const stdout = vi.fn();
  442. const runtime = runtimeWith();
  443. runtime.getSessionUsage.mockResolvedValue({
  444. rows: [
  445. {
  446. turnId: 'turn-1',
  447. model: 'custom_provider:review/gpt',
  448. inputTokens: 10,
  449. outputTokens: 4,
  450. reasoningTokens: 2,
  451. cacheReadTokens: 3,
  452. },
  453. ],
  454. });
  455. runtime.listModels.mockResolvedValue([
  456. {
  457. providerId: 'custom_provider:review',
  458. modelId: 'gpt',
  459. selected: true,
  460. providerSource: 'custom_provider',
  461. providerKind: 'custom',
  462. apiFormat: 'openai-responses',
  463. },
  464. ]);
  465. const lastMessage = join(root, 'last-message.txt');
  466. await expect(
  467. runTuiExec(
  468. {
  469. prompt: 'Fix it',
  470. workspaceDir: '/tmp/workspace',
  471. version: '0.1.0',
  472. format: 'json',
  473. outputLastMessagePath: lastMessage,
  474. },
  475. {
  476. runtime,
  477. stdout,
  478. stderr: vi.fn(),
  479. shutdown: async () => undefined,
  480. createTurnId: () => 'turn-1',
  481. },
  482. ),
  483. ).resolves.toBe(0);
  484. expect(await readFile(lastMessage, 'utf8')).toBe('fixed');
  485. expect(JSON.parse(stdout.mock.calls[0]?.[0] ?? '')).toMatchObject({
  486. model: {
  487. providerId: 'custom_provider:review',
  488. modelId: 'gpt',
  489. providerSource: 'custom_provider',
  490. providerKind: 'custom',
  491. protocol: 'openai-responses',
  492. },
  493. usage: {
  494. inputTokens: 10,
  495. outputTokens: 4,
  496. reasoningTokens: 2,
  497. cacheReadTokens: 3,
  498. totalTokens: 14,
  499. },
  500. });
  501. } finally {
  502. await rm(root, { recursive: true, force: true });
  503. }
  504. });
  505. it('publishes shutdown failure as the terminal result before writing the final message', async () => {
  506. const root = await mkdtemp(join(tmpdir(), 'mcode-exec-shutdown-'));
  507. try {
  508. const stdout = vi.fn();
  509. const lastMessage = join(root, 'last-message.txt');
  510. await expect(
  511. runTuiExec(
  512. {
  513. prompt: 'Fix it',
  514. workspaceDir: '/tmp/workspace',
  515. version: '0.1.0',
  516. format: 'json',
  517. outputLastMessagePath: lastMessage,
  518. },
  519. {
  520. runtime: runtimeWith(),
  521. stdout,
  522. stderr: vi.fn(),
  523. shutdown: async () => true,
  524. createTurnId: () => 'turn-1',
  525. },
  526. ),
  527. ).resolves.toBe(70);
  528. expect(JSON.parse(stdout.mock.calls[0]?.[0] ?? '')).toMatchObject({
  529. status: 'failed',
  530. error: { category: 'internal', code: 'RUNTIME_SHUTDOWN_FAILED' },
  531. });
  532. await expect(readFile(lastMessage, 'utf8')).rejects.toMatchObject({ code: 'ENOENT' });
  533. } finally {
  534. await rm(root, { recursive: true, force: true });
  535. }
  536. });
  537. it('fails authentication before creating a Session or sending a message', async () => {
  538. const stderr = vi.fn();
  539. const runtime = runtimeWith();
  540. runtime.getAccountStatus.mockResolvedValue({
  541. status: 'needs-login',
  542. authMode: 'managed-login',
  543. modelSource: 'token-plan',
  544. managedTokenPresent: false,
  545. warnings: [],
  546. } as never);
  547. await expect(
  548. runTuiExec(
  549. { prompt: 'Fix it', workspaceDir: '/tmp/workspace', version: '0.1.0' },
  550. { runtime, stdout: vi.fn(), stderr, shutdown: async () => undefined },
  551. ),
  552. ).resolves.toBe(3);
  553. expect(runtime.createSession).not.toHaveBeenCalled();
  554. expect(runtime.sendMessage).not.toHaveBeenCalled();
  555. expect(stderr).toHaveBeenCalledWith(
  556. 'mcode exec failed: Sign in to MiniMax to use Agent features. Run `mcode login`, then retry.\n',
  557. );
  558. });
  559. it('uses the process-local conversation request and assembles the public ExecResult', async () => {
  560. const stdout = vi.fn();
  561. const runtime = runtimeWith([
  562. {
  563. type: 'message',
  564. message: { id: 'assistant-1', role: 'assistant', content: '{"status":"fixed"}' },
  565. },
  566. { type: 'session-status', status: 'finished' },
  567. ]);
  568. runtime.listModels.mockResolvedValue([
  569. {
  570. providerId: 'provider',
  571. modelId: 'model',
  572. variant: 'fast',
  573. selected: true,
  574. providerSource: 'custom_provider',
  575. providerKind: 'custom',
  576. apiFormat: 'openai-responses',
  577. },
  578. ]);
  579. const outputSchema = {
  580. type: 'object',
  581. properties: { status: { const: 'fixed' } },
  582. required: ['status'],
  583. additionalProperties: false,
  584. };
  585. await expect(
  586. runTuiExec(
  587. {
  588. prompt: 'Fix it',
  589. workspaceDir: '/tmp/workspace',
  590. version: '0.1.0',
  591. model: 'provider/model#fast',
  592. permission: 'full',
  593. timeoutMs: 1_000,
  594. maxSteps: 3,
  595. format: 'json',
  596. outputSchema,
  597. },
  598. {
  599. runtime,
  600. stdout,
  601. stderr: vi.fn(),
  602. shutdown: async () => undefined,
  603. createTurnId: () => 'turn-1',
  604. },
  605. ),
  606. ).resolves.toBe(0);
  607. expect(runtime.setPermissionMode).not.toHaveBeenCalled();
  608. expect(runtime.sendMessage).toHaveBeenCalledWith(
  609. {
  610. id: 'session-1',
  611. turnId: 'turn-1',
  612. content: 'Fix it',
  613. model: { providerId: 'provider', modelId: 'model', variant: 'fast' },
  614. outputSchema,
  615. executionDeadlineAtMs: expect.any(Number),
  616. },
  617. expect.any(AbortSignal),
  618. );
  619. expect(JSON.parse(stdout.mock.calls[0]?.[0] ?? '')).toMatchObject({
  620. schemaVersion: 1,
  621. type: 'exec.result',
  622. runId: 'exec_turn-1',
  623. sessionId: 'session-1',
  624. turnId: 'turn-1',
  625. status: 'succeeded',
  626. output: { status: 'fixed' },
  627. model: {
  628. providerId: 'provider',
  629. modelId: 'model',
  630. variant: 'fast',
  631. providerSource: 'custom_provider',
  632. providerKind: 'custom',
  633. protocol: 'openai-responses',
  634. structuredOutputMode: 'native_strict',
  635. },
  636. });
  637. });
  638. it('sends an explicit --effort as a per-Turn thinking selection', async () => {
  639. const stdout = vi.fn();
  640. const runtime = runtimeWith();
  641. runtime.listModels.mockResolvedValue([
  642. {
  643. providerId: 'custom_provider:work',
  644. modelId: 'deep-reasoner-1',
  645. selected: true,
  646. effortOptions: ['low', 'medium', 'high', 'xhigh'],
  647. },
  648. ]);
  649. await expect(
  650. runTuiExec(
  651. {
  652. prompt: 'Fix it',
  653. workspaceDir: '/tmp/workspace',
  654. version: '0.1.0',
  655. model: 'custom_provider:work/deep-reasoner-1',
  656. effort: 'xhigh',
  657. format: 'json',
  658. },
  659. {
  660. runtime,
  661. stdout,
  662. stderr: vi.fn(),
  663. shutdown: async () => undefined,
  664. createTurnId: () => 'turn-1',
  665. },
  666. ),
  667. ).resolves.toBe(0);
  668. expect(runtime.sendMessage).toHaveBeenCalledWith(
  669. {
  670. id: 'session-1',
  671. turnId: 'turn-1',
  672. content: 'Fix it',
  673. model: {
  674. providerId: 'custom_provider:work',
  675. modelId: 'deep-reasoner-1',
  676. thinking: { effort: 'xhigh' },
  677. },
  678. },
  679. expect.any(AbortSignal),
  680. );
  681. // The applied effort is Runtime-resolved and is not echoed back on any
  682. // headless channel, so the public result must not claim one.
  683. expect(JSON.parse(stdout.mock.calls[0]?.[0] ?? '').model).not.toHaveProperty('effort');
  684. });
  685. it('applies --effort to the Session model when --model is omitted', async () => {
  686. const runtime = runtimeWith();
  687. runtime.listModels.mockResolvedValue([
  688. {
  689. providerId: 'default-provider',
  690. modelId: 'default-model',
  691. selected: true,
  692. effortOptions: ['low', 'high'],
  693. },
  694. ]);
  695. await expect(
  696. runTuiExec(
  697. { prompt: 'Fix it', workspaceDir: '/tmp/workspace', version: '0.1.0', effort: 'high' },
  698. {
  699. runtime,
  700. stdout: vi.fn(),
  701. stderr: vi.fn(),
  702. shutdown: async () => undefined,
  703. createTurnId: () => 'turn-1',
  704. },
  705. ),
  706. ).resolves.toBe(0);
  707. expect(runtime.sendMessage).toHaveBeenCalledWith(
  708. expect.objectContaining({
  709. model: {
  710. providerId: 'default-provider',
  711. modelId: 'default-model',
  712. thinking: { effort: 'high' },
  713. },
  714. }),
  715. expect.any(AbortSignal),
  716. );
  717. });
  718. /**
  719. * Legacy compatibility. `--model p/m#xhigh` predates `--effort`; Runtime reads
  720. * the suffix as a model variant and quietly applies its own strength. Callers
  721. * already depend on that Run starting, so it keeps running as a variant.
  722. */
  723. it('still runs a legacy effort-shaped #variant as a variant', async () => {
  724. const stderr = vi.fn();
  725. const runtime = runtimeWith();
  726. runtime.listModels.mockResolvedValue([
  727. {
  728. providerId: 'provider',
  729. modelId: 'model',
  730. selected: true,
  731. effortOptions: ['medium', 'xhigh'],
  732. },
  733. ]);
  734. await expect(
  735. runTuiExec(
  736. {
  737. prompt: 'Fix it',
  738. workspaceDir: '/tmp/workspace',
  739. version: '0.1.0',
  740. model: 'provider/model#xhigh',
  741. },
  742. { runtime, stdout: vi.fn(), stderr, shutdown: async () => undefined },
  743. ),
  744. ).resolves.toBe(0);
  745. expect(stderr).not.toHaveBeenCalled();
  746. expect(runtime.sendMessage).toHaveBeenCalledWith(
  747. expect.objectContaining({
  748. model: { providerId: 'provider', modelId: 'model', variant: 'xhigh' },
  749. }),
  750. expect.any(AbortSignal),
  751. );
  752. });
  753. it('refuses --effort on a model whose thinking default is off before starting the Turn', async () => {
  754. const stderr = vi.fn();
  755. const runtime = runtimeWith();
  756. runtime.listModels.mockResolvedValue([
  757. {
  758. providerId: 'minimax',
  759. modelId: 'Official-M4',
  760. selected: true,
  761. variant: '',
  762. thinkingConfig: { mode: 'switchable', defaultValue: 'false' },
  763. effortOptions: ['low', 'high'],
  764. },
  765. ]);
  766. await expect(
  767. runTuiExec(
  768. {
  769. prompt: 'Fix it',
  770. workspaceDir: '/tmp/workspace',
  771. version: '0.1.0',
  772. model: 'minimax/Official-M4',
  773. effort: 'high',
  774. },
  775. { runtime, stdout: vi.fn(), stderr, shutdown: async () => undefined },
  776. ),
  777. ).resolves.toBe(2);
  778. expect(runtime.sendMessage).not.toHaveBeenCalled();
  779. expect(stderr).toHaveBeenCalledWith(
  780. expect.stringContaining('runs with thinking off by default'),
  781. );
  782. });
  783. it('rejects an unsupported effort level before starting the Turn', async () => {
  784. const stderr = vi.fn();
  785. const runtime = runtimeWith();
  786. runtime.listModels.mockResolvedValue([
  787. { providerId: 'provider', modelId: 'model', selected: true, effortOptions: ['low', 'high'] },
  788. ]);
  789. await expect(
  790. runTuiExec(
  791. {
  792. prompt: 'Fix it',
  793. workspaceDir: '/tmp/workspace',
  794. version: '0.1.0',
  795. model: 'provider/model',
  796. effort: 'xhigh',
  797. },
  798. { runtime, stdout: vi.fn(), stderr, shutdown: async () => undefined },
  799. ),
  800. ).resolves.toBe(2);
  801. expect(runtime.sendMessage).not.toHaveBeenCalled();
  802. expect(stderr).toHaveBeenCalledWith(expect.stringContaining('Available levels: low, high'));
  803. });
  804. it('streams only the versioned ExecEvent contract with one terminal result', async () => {
  805. const stdout: string[] = [];
  806. const runtime = runtimeWith();
  807. await expect(
  808. runTuiExec(
  809. {
  810. prompt: 'Fix it',
  811. workspaceDir: '/tmp/workspace',
  812. version: '0.1.0',
  813. format: 'stream-json',
  814. },
  815. {
  816. runtime,
  817. stdout: (value) => stdout.push(value),
  818. stderr: vi.fn(),
  819. shutdown: async () => undefined,
  820. createTurnId: () => 'turn-1',
  821. },
  822. ),
  823. ).resolves.toBe(0);
  824. const records = stdout.join('').trim().split('\n').map((line) => JSON.parse(line));
  825. expect(records.map((record) => record.type)).toEqual([
  826. 'exec.started',
  827. 'session.started',
  828. 'turn.started',
  829. 'item.completed',
  830. 'turn.completed',
  831. 'exec.completed',
  832. ]);
  833. expect(records.at(-1)).toMatchObject({
  834. type: 'exec.completed',
  835. result: {
  836. status: 'succeeded',
  837. model: {
  838. providerId: 'default-provider',
  839. modelId: 'default-model',
  840. variant: 'balanced',
  841. },
  842. },
  843. });
  844. expect(runtime.sendMessage).toHaveBeenCalledWith(
  845. {
  846. id: 'session-1',
  847. turnId: 'turn-1',
  848. content: 'Fix it',
  849. },
  850. expect.any(AbortSignal),
  851. );
  852. });
  853. it('preserves an empty selected-model variant in machine output', async () => {
  854. const stdout = vi.fn();
  855. const runtime = runtimeWith();
  856. runtime.listModels.mockResolvedValue([
  857. {
  858. providerId: 'default-provider',
  859. modelId: 'default-model',
  860. variant: '',
  861. selected: true,
  862. },
  863. ]);
  864. await expect(
  865. runTuiExec(
  866. {
  867. prompt: 'Fix it',
  868. workspaceDir: '/tmp/workspace',
  869. version: '0.1.0',
  870. format: 'json',
  871. },
  872. { runtime, stdout, stderr: vi.fn(), shutdown: async () => undefined },
  873. ),
  874. ).resolves.toBe(0);
  875. expect(JSON.parse(stdout.mock.calls[0]?.[0] ?? '')).toMatchObject({
  876. model: {
  877. providerId: 'default-provider',
  878. modelId: 'default-model',
  879. variant: '',
  880. },
  881. });
  882. });
  883. it('keeps execution successful when selected-model inspection is unavailable', async () => {
  884. const stdout = vi.fn();
  885. const runtime = runtimeWith();
  886. runtime.listModels.mockRejectedValue(new Error('model catalog unavailable'));
  887. await expect(
  888. runTuiExec(
  889. {
  890. prompt: 'Fix it',
  891. workspaceDir: '/tmp/workspace',
  892. version: '0.1.0',
  893. format: 'json',
  894. },
  895. { runtime, stdout, stderr: vi.fn(), shutdown: async () => undefined },
  896. ),
  897. ).resolves.toBe(0);
  898. expect(JSON.parse(stdout.mock.calls[0]?.[0] ?? '')).not.toHaveProperty('model');
  899. });
  900. it('fails without aborting when Runtime bypasses the non-interactive Host gate', async () => {
  901. const stderr = vi.fn();
  902. const runtime = runtimeWith([
  903. { type: 'generic', eventType: 'runtime.action-required', data: { kind: 'questionnaire' } },
  904. ]);
  905. await expect(
  906. runTuiExec(
  907. { prompt: 'Fix it', workspaceDir: '/tmp/workspace', version: '0.1.0' },
  908. { runtime, stdout: vi.fn(), stderr, shutdown: async () => undefined },
  909. ),
  910. ).resolves.toBe(4);
  911. expect(runtime.abortSession).not.toHaveBeenCalled();
  912. expect(stderr).toHaveBeenCalledWith(
  913. expect.stringContaining('requested user interaction from a non-interactive Exec host'),
  914. );
  915. });
  916. it('maps Runtime failure and cancellation outcomes to stable exit codes', async () => {
  917. const cases: Array<[readonly TuiStreamEvent[], number]> = [
  918. [[{ type: 'error', message: 'failed' }], 4],
  919. [[{ type: 'session-status', status: 'aborted' }], 130],
  920. ];
  921. for (const [events, exitCode] of cases) {
  922. const runtime = runtimeWith(events);
  923. await expect(
  924. runTuiExec(
  925. { prompt: 'Fix it', workspaceDir: '/tmp/workspace', version: '0.1.0' },
  926. { runtime, stdout: vi.fn(), stderr: vi.fn(), shutdown: async () => undefined },
  927. ),
  928. ).resolves.toBe(exitCode);
  929. }
  930. });
  931. it('aborts the exact Turn when stream-json stdout closes', async () => {
  932. const runtime = runtimeWith();
  933. runtime.sendMessage.mockImplementation(async function* (_request, signal?: AbortSignal) {
  934. yield { type: 'heartbeat', turnId: 'turn-1', cursor: 'c1' };
  935. if (!signal?.aborted) {
  936. await new Promise<void>((resolve) =>
  937. signal?.addEventListener('abort', () => resolve(), { once: true }),
  938. );
  939. }
  940. });
  941. const stdout = vi.fn(async () => {
  942. throw Object.assign(new Error('closed'), { code: 'EPIPE' });
  943. });
  944. await expect(
  945. runTuiExec(
  946. {
  947. prompt: 'Fix it',
  948. workspaceDir: '/tmp/workspace',
  949. version: '0.1.0',
  950. format: 'stream-json',
  951. },
  952. {
  953. runtime,
  954. stdout,
  955. stderr: vi.fn(),
  956. shutdown: async () => undefined,
  957. createTurnId: () => 'turn-1',
  958. },
  959. ),
  960. ).resolves.toBe(141);
  961. expect(runtime.abortSession).toHaveBeenCalledWith({
  962. id: 'session-1',
  963. turnId: 'turn-1',
  964. reason: 'user_stop',
  965. });
  966. });
  967. it('aborts the Runtime conversation when the process receives SIGINT', async () => {
  968. const processRef = new EventEmitter();
  969. const started = vi.fn();
  970. const runtime = runtimeWith();
  971. runtime.sendMessage.mockImplementation(async function* pendingMessage(
  972. _req,
  973. signal?: AbortSignal,
  974. ) {
  975. yield* [];
  976. started();
  977. await new Promise<void>((resolve) => signal?.addEventListener('abort', () => resolve()));
  978. });
  979. const executing = runTuiExec(
  980. { prompt: 'Fix it', workspaceDir: '/tmp/workspace', version: '0.1.0' },
  981. {
  982. runtime,
  983. processRef: processRef as unknown as Pick<NodeJS.Process, 'once' | 'off'>,
  984. stderr: vi.fn(),
  985. shutdown: async () => undefined,
  986. },
  987. );
  988. await vi.waitFor(() => expect(started).toHaveBeenCalledOnce());
  989. processRef.emit('SIGINT');
  990. await expect(executing).resolves.toBe(130);
  991. expect(runtime.abortSession).toHaveBeenCalledWith(
  992. expect.objectContaining({ id: 'session-1', reason: 'user_stop' }),
  993. );
  994. });
  995. it('reuses a valid Session and continues the latest workspace Session', async () => {
  996. const direct = runtimeWith();
  997. await runTuiExec(
  998. {
  999. prompt: 'Continue',
  1000. workspaceDir: '/tmp/workspace',
  1001. version: '0.1.0',
  1002. sessionId: 'session-1',
  1003. },
  1004. { runtime: direct, stdout: vi.fn(), stderr: vi.fn(), shutdown: async () => undefined },
  1005. );
  1006. expect(direct.createSession).not.toHaveBeenCalled();
  1007. const continued = runtimeWith();
  1008. continued.listSessionPage
  1009. .mockResolvedValueOnce({
  1010. sessions: [{ sessionId: 'other', workspaceDir: '/tmp/other' }],
  1011. hasMore: true,
  1012. nextCursor: 'page-2',
  1013. })
  1014. .mockResolvedValueOnce({
  1015. sessions: [{ sessionId: 'session-1', workspaceDir: '/tmp/workspace' }],
  1016. hasMore: false,
  1017. });
  1018. await runTuiExec(
  1019. {
  1020. prompt: 'Continue',
  1021. workspaceDir: '/tmp/workspace',
  1022. version: '0.1.0',
  1023. continueSession: true,
  1024. },
  1025. { runtime: continued, stdout: vi.fn(), stderr: vi.fn(), shutdown: async () => undefined },
  1026. );
  1027. expect(continued.sendMessage).toHaveBeenCalledWith(
  1028. expect.objectContaining({ id: 'session-1' }),
  1029. expect.any(AbortSignal),
  1030. );
  1031. });
  1032. it.each([
  1033. ['questionnaire', { questionnaire: true, permission: false }],
  1034. ['permission', { questionnaire: false, permission: true }],
  1035. ] as const)(
  1036. 'refuses a resumed Session with a pending %s without mutating it',
  1037. async (_interaction, pending) => {
  1038. const stderr = vi.fn();
  1039. const runtime = runtimeWith();
  1040. if (pending.questionnaire) {
  1041. runtime.getPendingQuestionnaire.mockResolvedValue({
  1042. requestId: 'question-1',
  1043. sessionId: 'session-1',
  1044. } as never);
  1045. }
  1046. if (pending.permission) {
  1047. runtime.listPendingPermissions.mockResolvedValue([
  1048. { requestId: 'permission-1', sessionId: 'session-1' },
  1049. ]);
  1050. }
  1051. await expect(
  1052. runTuiExec(
  1053. {
  1054. prompt: 'Continue',
  1055. workspaceDir: '/tmp/workspace',
  1056. version: '0.1.0',
  1057. sessionId: 'session-1',
  1058. },
  1059. { runtime, stdout: vi.fn(), stderr, shutdown: async () => undefined },
  1060. ),
  1061. ).resolves.toBe(4);
  1062. expect(runtime.sendMessage).not.toHaveBeenCalled();
  1063. expect(runtime.abortSession).not.toHaveBeenCalled();
  1064. expect(stderr).toHaveBeenCalledWith(
  1065. expect.stringContaining('requires an interactive host'),
  1066. );
  1067. },
  1068. );
  1069. it('rejects archived, cross-workspace, and internal Sessions before send', async () => {
  1070. for (const session of [
  1071. { sessionId: 'session-1', workspaceDir: '/tmp/workspace', archived: true },
  1072. { sessionId: 'session-1', workspaceDir: '/tmp/other', archived: false },
  1073. {
  1074. sessionId: 'session-1',
  1075. agentName: 'explore',
  1076. sessionType: 'root' as const,
  1077. workspaceDir: '/tmp/workspace',
  1078. },
  1079. ]) {
  1080. const runtime = runtimeWith();
  1081. runtime.getSession.mockResolvedValue(session);
  1082. const code = await runTuiExec(
  1083. {
  1084. prompt: 'Continue',
  1085. workspaceDir: '/tmp/workspace',
  1086. version: '0.1.0',
  1087. sessionId: 'session-1',
  1088. },
  1089. { runtime, stdout: vi.fn(), stderr: vi.fn(), shutdown: async () => undefined },
  1090. );
  1091. expect(code).not.toBe(0);
  1092. expect(runtime.sendMessage).not.toHaveBeenCalled();
  1093. }
  1094. });
  1095. it('does not replace a missing explicit session with a new or recent session', async () => {
  1096. const runtime = runtimeWith();
  1097. runtime.getSession.mockRejectedValue(new Error('Session does not exist'));
  1098. const code = await runTuiExec({
  1099. prompt: 'Summarize', workspaceDir: '/tmp/workspace', version: 'test', sessionId: 'missing',
  1100. }, { runtime, stdout: vi.fn(), stderr: vi.fn(), shutdown: async () => undefined });
  1101. expect(code).not.toBe(0);
  1102. expect(runtime.createSession).not.toHaveBeenCalled();
  1103. expect(runtime.listSessionPage).not.toHaveBeenCalled();
  1104. expect(runtime.sendMessage).not.toHaveBeenCalled();
  1105. });
  1106. });