local-runtime-host-input-safety-v2.test.ts 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448
  1. import { afterEach, describe, expect, it, vi } from 'vitest';
  2. import { RespDataType } from '@mavis/agent-core/protocol/agent-message';
  3. import { RuntimeEventStatus, RuntimeEventType, type IRuntimeEvent } from '@mavis/protocol';
  4. import { LocalRuntimeHost, type LocalTurnRunner } from '../../src/runtime/host.js';
  5. import { OUTPUT_REVISION_INSTRUCTION } from '../../src/runtime/output-safety-policy.js';
  6. const baseTurn = {
  7. sessionId: 'ses',
  8. turnId: 'turn',
  9. workspaceDir: '/tmp/ws',
  10. systemPrompt: 'base',
  11. userMessage: { text: 'question' },
  12. reviewUserInput: 'question',
  13. llm: { model: { api: 'anthropic-messages', provider: 'minimax', id: 'test' } as never },
  14. };
  15. const finalMessage = (content: string): IRuntimeEvent =>
  16. ({
  17. schema: 'runtime.event/v1',
  18. event_id: 'final',
  19. session_id: 'ses',
  20. turn_id: 'turn',
  21. type: RuntimeEventType.STREAM_RESP,
  22. payload: {
  23. stream_resp: JSON.stringify({
  24. type: RespDataType.AgentMessage,
  25. agent_message: { msg_id: 'answer', msg_content: content },
  26. }),
  27. },
  28. }) as IRuntimeEvent;
  29. const pass = { action: 1 };
  30. function installInputVerdict(verdict: unknown) {
  31. return vi.spyOn(globalThis, 'fetch').mockImplementation(async (_url, init) => {
  32. const body = JSON.parse(String(init?.body));
  33. return Response.json(body.scene === 110 ? verdict : pass);
  34. });
  35. }
  36. afterEach(() => vi.restoreAllMocks());
  37. describe('LocalRuntimeHost V2 input safety', () => {
  38. it('starts generation while input review is pending', async () => {
  39. let resolveReview!: (response: Response) => void;
  40. const pending = new Promise<Response>((resolve) => {
  41. resolveReview = resolve;
  42. });
  43. vi.spyOn(globalThis, 'fetch')
  44. .mockImplementationOnce(() => pending)
  45. .mockImplementation(async () => Response.json(pass));
  46. const runTurn = vi.fn(async (input) => {
  47. await input.eventWriter.pushRuntime(finalMessage('answer'));
  48. });
  49. const run = new LocalRuntimeHost({ safetyApiVersion: 'v2', piRunner: { runTurn } }).runTurn(
  50. baseTurn,
  51. );
  52. await vi.waitFor(() => expect(runTurn).toHaveBeenCalledOnce());
  53. resolveReview(Response.json(pass));
  54. expect((await run).retracted).toBe(false);
  55. expect(runTurn).toHaveBeenCalledOnce();
  56. });
  57. it('cancels a terminal waiting for input review without waiting for its HTTP response', async () => {
  58. let resolveReview!: (response: Response) => void;
  59. const pendingReview = new Promise<Response>((resolve) => {
  60. resolveReview = resolve;
  61. });
  62. vi.spyOn(globalThis, 'fetch').mockImplementation(() => pendingReview);
  63. const abort = new AbortController();
  64. const observer = vi.fn();
  65. const runTurn = vi.fn(async (input) => {
  66. await input.eventWriter.pushRuntime({
  67. schema: 'runtime.event/v1',
  68. event_id: 'held-completed',
  69. session_id: baseTurn.sessionId,
  70. turn_id: baseTurn.turnId,
  71. type: RuntimeEventType.SESSION_STATUS,
  72. payload: { status: RuntimeEventStatus.COMPLETED },
  73. });
  74. });
  75. let output: Awaited<ReturnType<LocalRuntimeHost['runTurn']>> | undefined;
  76. const run = (async () => {
  77. output = await new LocalRuntimeHost({
  78. safetyApiVersion: 'v2',
  79. piRunner: { runTurn },
  80. }).runTurn({
  81. ...baseTurn,
  82. signal: abort.signal,
  83. onInputReviewResolved: observer,
  84. });
  85. })();
  86. try {
  87. await vi.waitFor(() => expect(runTurn).toHaveBeenCalledOnce());
  88. abort.abort();
  89. await vi.waitFor(() => expect(output).toBeDefined(), { timeout: 500 });
  90. expect(
  91. output?.events
  92. .filter((event) => event.type === RuntimeEventType.SESSION_STATUS)
  93. .map((event) => event.payload?.status),
  94. ).toEqual([RuntimeEventStatus.ABORTED]);
  95. expect(observer).not.toHaveBeenCalled();
  96. expect(output?.retracted).toBe(false);
  97. } finally {
  98. resolveReview(
  99. Response.json({
  100. action: 4,
  101. errorCode: 50201,
  102. guide_prompt: 'LATE_GUIDE',
  103. }),
  104. );
  105. await run;
  106. }
  107. expect(observer).not.toHaveBeenCalled();
  108. expect(runTurn).toHaveBeenCalledOnce();
  109. expect(JSON.stringify(output?.events)).not.toContain('LATE_GUIDE');
  110. });
  111. it('keeps an output Block terminal when an input Guide arrives afterward', async () => {
  112. let resolveReview!: (response: Response) => void;
  113. const pendingReview = new Promise<Response>((resolve) => {
  114. resolveReview = resolve;
  115. });
  116. vi.spyOn(globalThis, 'fetch').mockImplementation(async (_url, init) => {
  117. const body = JSON.parse(String(init?.body));
  118. return body.scene === 110
  119. ? pendingReview
  120. : Response.json({ action: 2, errorCode: 50201 });
  121. });
  122. const outputBlocked = vi.fn();
  123. const runTurn = vi.fn(async (input) => {
  124. await input.eventWriter.pushRuntime(finalMessage('BLOCKED_DRAFT'));
  125. expect(input.signal?.aborted).toBe(true);
  126. outputBlocked();
  127. });
  128. const onOutputRecall = vi.fn();
  129. const rewindPiHistory = vi.fn();
  130. const run = new LocalRuntimeHost({ safetyApiVersion: 'v2', piRunner: { runTurn } }).runTurn({
  131. ...baseTurn,
  132. onOutputRecall,
  133. rewindPiHistory,
  134. });
  135. await vi.waitFor(() => expect(outputBlocked).toHaveBeenCalledOnce());
  136. resolveReview(
  137. Response.json({
  138. action: 4,
  139. errorCode: 50201,
  140. guide_prompt: 'LATE_INPUT_GUIDE',
  141. }),
  142. );
  143. const output = await run;
  144. expect(runTurn).toHaveBeenCalledOnce();
  145. expect(onOutputRecall).not.toHaveBeenCalled();
  146. expect(rewindPiHistory).not.toHaveBeenCalled();
  147. expect(output).toMatchObject({ retracted: true, retractionVariant: 'content' });
  148. expect(
  149. output.events
  150. .filter((event) => event.type === RuntimeEventType.SESSION_STATUS)
  151. .map((event) => event.payload?.status),
  152. ).toEqual([RuntimeEventStatus.COMPLETED]);
  153. expect(JSON.stringify(output.events)).not.toMatch(/BLOCKED_DRAFT|LATE_INPUT_GUIDE/);
  154. });
  155. it.each(['chunk', 'final'] as const)(
  156. 'does not release a late-approved output %s after input Block',
  157. async (kind) => {
  158. let resolveInput!: (response: Response) => void;
  159. let resolveOutput!: (response: Response) => void;
  160. const pendingInput = new Promise<Response>((resolve) => {
  161. resolveInput = resolve;
  162. });
  163. const pendingOutput = new Promise<Response>((resolve) => {
  164. resolveOutput = resolve;
  165. });
  166. const outputReviewStarted = vi.fn();
  167. vi.spyOn(globalThis, 'fetch').mockImplementation(async (_url, init) => {
  168. const body = JSON.parse(String(init?.body));
  169. if (body.scene === 110) return pendingInput;
  170. outputReviewStarted();
  171. return pendingOutput;
  172. });
  173. let attemptSignal: AbortSignal | undefined;
  174. const runTurn = vi.fn(async (input) => {
  175. attemptSignal = input.signal;
  176. const event =
  177. kind === 'final'
  178. ? finalMessage('LATE_APPROVED_DRAFT')
  179. : {
  180. ...finalMessage(''),
  181. payload: {
  182. stream_resp: JSON.stringify({
  183. type: RespDataType.AgentMessageChunk,
  184. agent_message_chunk: {
  185. msg_id: 'answer',
  186. msg_content: 'LATE_APPROVED_DRAFT'.repeat(1024),
  187. },
  188. }),
  189. },
  190. };
  191. await input.eventWriter.pushRuntime(event);
  192. });
  193. const run = new LocalRuntimeHost({ safetyApiVersion: 'v2', piRunner: { runTurn } }).runTurn(
  194. baseTurn,
  195. );
  196. await vi.waitFor(() => expect(outputReviewStarted).toHaveBeenCalledOnce());
  197. resolveInput(Response.json({ action: 2, errorCode: 50201 }));
  198. await vi.waitFor(() => expect(attemptSignal?.aborted).toBe(true));
  199. resolveOutput(Response.json(pass));
  200. const output = await run;
  201. expect(output).toMatchObject({ retracted: true, retractionVariant: 'content' });
  202. expect(runTurn).toHaveBeenCalledOnce();
  203. expect(
  204. output.events.filter((event) => event.type === RuntimeEventType.STREAM_RESP),
  205. ).toHaveLength(0);
  206. expect(output.events.at(-1)?.payload?.status).toBe(RuntimeEventStatus.COMPLETED);
  207. },
  208. );
  209. it.each([
  210. [
  211. { action: 4, errorCode: 50201, guide_prompt: 'PRIVATE_INPUT_GUIDE' },
  212. 'PRIVATE_INPUT_GUIDE',
  213. ],
  214. ])('restarts a concurrent draft with the input guide once: %j', async (verdict, instruction) => {
  215. let outputIndex = 0;
  216. vi.spyOn(globalThis, 'fetch').mockImplementation(async (_url, init) => {
  217. const body = JSON.parse(String(init?.body));
  218. return Response.json(
  219. body.scene === 110
  220. ? verdict
  221. : outputIndex++ === 0
  222. ? { action: 4, errorCode: 50201, guide_prompt: '' }
  223. : pass,
  224. );
  225. });
  226. const prompts: string[] = [];
  227. const onInputReviewResolved = vi.fn();
  228. const piRunner: LocalTurnRunner = {
  229. async runTurn(input) {
  230. prompts.push(input.systemPrompt);
  231. if (prompts.length === 1 && !input.signal?.aborted) {
  232. await new Promise<void>((resolve) =>
  233. input.signal?.addEventListener('abort', () => resolve(), { once: true }),
  234. );
  235. }
  236. await input.eventWriter.pushRuntime(finalMessage(`draft-${prompts.length}`));
  237. },
  238. };
  239. const output = await new LocalRuntimeHost({ safetyApiVersion: 'v2', piRunner }).runTurn({
  240. ...baseTurn,
  241. onInputReviewResolved,
  242. rewindPiHistory: vi.fn(),
  243. onOutputRecall: vi.fn(),
  244. });
  245. expect(prompts).toEqual([
  246. 'base',
  247. `base\n\n${instruction}`,
  248. `base\n\n${OUTPUT_REVISION_INSTRUCTION}`,
  249. ]);
  250. expect(onInputReviewResolved).toHaveBeenCalledWith(true);
  251. expect(output.retracted).toBe(false);
  252. expect(JSON.stringify(output.events)).not.toContain('PRIVATE_INPUT_GUIDE');
  253. expect(JSON.stringify(output.events)).not.toContain('draft-1');
  254. });
  255. it.each([undefined, '', ' '])('passes an input guide without text: %j', async (guide) => {
  256. installInputVerdict({ action: 4, errorCode: 50201, ...(guide !== undefined ? { guide_prompt: guide } : {}) });
  257. const onInputReviewResolved = vi.fn();
  258. const onOutputRecall = vi.fn();
  259. const rewindPiHistory = vi.fn();
  260. const runTurn = vi.fn(async (input) => {
  261. await input.eventWriter.pushRuntime(finalMessage('original answer'));
  262. expect(input.signal?.aborted).toBe(false);
  263. });
  264. const output = await new LocalRuntimeHost({ safetyApiVersion: 'v2', piRunner: { runTurn } }).runTurn({
  265. ...baseTurn, onInputReviewResolved, onOutputRecall, rewindPiHistory,
  266. });
  267. expect(runTurn).toHaveBeenCalledOnce();
  268. expect(runTurn.mock.calls[0]?.[0].systemPrompt).toBe('base');
  269. expect(onInputReviewResolved).toHaveBeenCalledWith(false);
  270. expect(onOutputRecall).not.toHaveBeenCalled();
  271. expect(rewindPiHistory).not.toHaveBeenCalled();
  272. expect(output.retracted).toBe(false);
  273. expect(JSON.stringify(output.events)).toContain('original answer');
  274. });
  275. it('replaces the concurrent draft with a persisted input fixed answer', async () => {
  276. const fetchSpy = installInputVerdict({
  277. action: 3,
  278. errorCode: 50201,
  279. suggestion: 'fixed answer',
  280. });
  281. const runTurn = vi.fn();
  282. const history = vi.fn();
  283. const output = await new LocalRuntimeHost({
  284. safetyApiVersion: 'v2',
  285. piRunner: { runTurn },
  286. }).runTurn({
  287. ...baseTurn,
  288. hooks: { onHistoryChangedHook: [history] },
  289. });
  290. expect(runTurn).toHaveBeenCalledOnce();
  291. expect(fetchSpy).toHaveBeenCalledOnce();
  292. expect(output.retracted).toBe(false);
  293. expect(history.mock.calls[0]?.[0]?.messages).toMatchObject([
  294. { role: 'user', content: [{ type: 'text', text: 'question' }] },
  295. { role: 'assistant', content: [{ type: 'text', text: 'fixed answer' }] },
  296. ]);
  297. expect(JSON.stringify(output.events)).toContain('fixed answer');
  298. expect(JSON.stringify(output.events)).not.toContain('PRIVATE_UNUSED_GUIDE');
  299. expect(output.events.at(-1)?.payload?.status).toBe(RuntimeEventStatus.COMPLETED);
  300. });
  301. it('retracts a concurrent draft on input block without retry', async () => {
  302. installInputVerdict({
  303. action: 2,
  304. errorCode: 50201,
  305. });
  306. const runTurn = vi.fn();
  307. const onInputReviewResolved = vi.fn();
  308. const output = await new LocalRuntimeHost({
  309. safetyApiVersion: 'v2',
  310. piRunner: { runTurn },
  311. }).runTurn({
  312. ...baseTurn,
  313. onInputReviewResolved,
  314. });
  315. expect(runTurn).toHaveBeenCalledOnce();
  316. expect(onInputReviewResolved).toHaveBeenCalledWith(true);
  317. expect(output).toMatchObject({ retracted: true, retractionVariant: 'content' });
  318. expect(output.events.filter((event) => event.type === RuntimeEventType.STREAM_RESP)).toEqual(
  319. [],
  320. );
  321. });
  322. it.each([401, 503, 200])(
  323. 'fails closed without a usable input verdict (HTTP %s)',
  324. async (status) => {
  325. vi.spyOn(globalThis, 'fetch').mockImplementation(
  326. async () => new Response('invalid', { status }),
  327. );
  328. const runTurn = vi.fn();
  329. const output = await new LocalRuntimeHost({
  330. safetyApiVersion: 'v2',
  331. piRunner: { runTurn },
  332. }).runTurn(baseTurn);
  333. expect(runTurn).toHaveBeenCalledOnce();
  334. expect(output).toMatchObject({ retracted: true, retractionVariant: 'network' });
  335. },
  336. );
  337. it('retracts the concurrent draft when input review is unavailable', async () => {
  338. vi.spyOn(globalThis, 'fetch').mockRejectedValue(new Error('offline'));
  339. const runTurn = vi.fn();
  340. const onInputReviewResolved = vi.fn();
  341. const output = await new LocalRuntimeHost({
  342. safetyApiVersion: 'v2',
  343. piRunner: { runTurn },
  344. }).runTurn({
  345. ...baseTurn,
  346. onInputReviewResolved,
  347. });
  348. expect(onInputReviewResolved).toHaveBeenCalledWith(true);
  349. expect(runTurn).toHaveBeenCalledOnce();
  350. expect(output).toMatchObject({ retracted: true, retractionVariant: 'network' });
  351. });
  352. it.each([
  353. { action: 1 },
  354. { action: 4, errorCode: 50201, guide_prompt: 'PRIVATE_GUIDE' },
  355. { action: 3, errorCode: 50201, suggestion: 'FIXED' },
  356. ])('does not deliver a late verdict after cancellation: %j', async (verdict) => {
  357. let resolveReview!: (response: Response) => void;
  358. const pending = new Promise<Response>((resolve) => {
  359. resolveReview = resolve;
  360. });
  361. vi.spyOn(globalThis, 'fetch').mockImplementation(() => pending);
  362. const runTurn = vi.fn();
  363. const history = vi.fn();
  364. const observer = vi.fn();
  365. const abort = new AbortController();
  366. const run = new LocalRuntimeHost({ safetyApiVersion: 'v2', piRunner: { runTurn } }).runTurn({
  367. ...baseTurn,
  368. signal: abort.signal,
  369. onInputReviewResolved: observer,
  370. hooks: { onHistoryChangedHook: [history] },
  371. });
  372. abort.abort();
  373. resolveReview(Response.json(verdict));
  374. const output = await run;
  375. expect(runTurn).toHaveBeenCalledOnce();
  376. expect(history).not.toHaveBeenCalled();
  377. expect(observer).not.toHaveBeenCalled();
  378. expect(output.events.at(-1)?.payload?.status).toBe(RuntimeEventStatus.ABORTED);
  379. expect(JSON.stringify(output.events)).not.toMatch(/FIXED|PRIVATE_GUIDE/);
  380. });
  381. it('restores canonical history when cancellation wins during fixed-answer persistence', async () => {
  382. installInputVerdict({ action: 3, errorCode: 50201, suggestion: 'FIXED' });
  383. let enterHistory!: () => void;
  384. let releaseHistory!: () => void;
  385. const entered = new Promise<void>((resolve) => {
  386. enterHistory = resolve;
  387. });
  388. const held = new Promise<void>((resolve) => {
  389. releaseHistory = resolve;
  390. });
  391. const history = vi.fn().mockImplementationOnce(async () => {
  392. enterHistory();
  393. await held;
  394. });
  395. const runTurn = vi.fn();
  396. const abort = new AbortController();
  397. const baseline = [{ role: 'user' as const, content: 'PRIOR', timestamp: 1 }];
  398. const pending = new LocalRuntimeHost({ safetyApiVersion: 'v2', piRunner: { runTurn } }).runTurn(
  399. {
  400. ...baseTurn,
  401. history: baseline,
  402. signal: abort.signal,
  403. hooks: { onHistoryChangedHook: [history] },
  404. },
  405. );
  406. await entered;
  407. abort.abort();
  408. releaseHistory();
  409. const output = await pending;
  410. expect(history).toHaveBeenCalledTimes(2);
  411. expect(history.mock.calls[1]?.[0]).toMatchObject({
  412. reason: 'replaceMessages',
  413. messages: baseline,
  414. });
  415. expect(runTurn).toHaveBeenCalledOnce();
  416. expect(JSON.stringify(output.events)).not.toContain('FIXED');
  417. expect(output.events.at(-1)?.payload?.status).toBe(RuntimeEventStatus.ABORTED);
  418. });
  419. it('does not review absent input on continuation turns', async () => {
  420. const fetchSpy = installInputVerdict({ action: 2, errorCode: 50201 });
  421. const runTurn = vi.fn(async (input) => {
  422. await input.eventWriter.pushRuntime(finalMessage('answer'));
  423. });
  424. const { reviewUserInput: _, ...continuation } = baseTurn;
  425. const output = await new LocalRuntimeHost({
  426. safetyApiVersion: 'v2',
  427. piRunner: { runTurn },
  428. }).runTurn(continuation);
  429. expect(output.retracted).toBe(false);
  430. expect(
  431. fetchSpy.mock.calls.every(([, init]) => JSON.parse(String(init?.body)).scene === 11),
  432. ).toBe(true);
  433. });
  434. });