content-safety-turn-v2.test.ts 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393
  1. import { LocalOutputSafetyEventWriter } from '../../src/runtime/output-safety-writer.js';
  2. import { RuntimeEventType, type IRuntimeEvent } from '@mavis/protocol';
  3. import { RespDataType } from '@mavis/agent-core/protocol/agent-message';
  4. import { describe, expect, it, vi } from 'vitest';
  5. import { createContentSafetyChecker, SAFETY_SCENE } from '../../src/content-safety/api.js';
  6. const deps = {
  7. apiVersion: 'v2' as const,
  8. region: () => 'cn' as const,
  9. buildEnv: () => 'test' as const,
  10. };
  11. describe('production turn safety routing', () => {
  12. it.each([undefined, '', ' '])('normalizes an empty input guide before runtime delivery: %j', async (guide) => {
  13. const fetchImpl = vi.fn<typeof fetch>().mockImplementation(async () => Response.json({
  14. action: 4, errorCode: 50201, ...(guide !== undefined ? { guide_prompt: guide } : {}),
  15. }));
  16. const checker = createContentSafetyChecker({ ...deps, fetchImpl });
  17. expect(await checker('query', SAFETY_SCENE.UserInput)).toEqual({ pass: true, action: 'allow' });
  18. for (const scene of [SAFETY_SCENE.MessageOutput, SAFETY_SCENE.StreamChunk, SAFETY_SCENE.ThinkingContent]) {
  19. expect(await checker('draft', scene)).toEqual({ pass: false, action: 'guide', errorKind: 'rejected' });
  20. }
  21. });
  22. it.each(
  23. [
  24. { body: { action: 1 }, blocked: false, immediate: false },
  25. {
  26. body: { action: 2, errorCode: 50201, guide_prompt: 'ignored' },
  27. blocked: true,
  28. immediate: true,
  29. },
  30. {
  31. body: { action: 4, errorCode: 50201, guide_prompt: 'model guide' },
  32. blocked: true,
  33. immediate: false,
  34. guide: 'model guide',
  35. },
  36. { body: { action: 4, errorCode: 50201 }, blocked: true, immediate: false },
  37. {
  38. body: { action: 4, errorCode: 50201, guide_prompt: ' ' },
  39. blocked: true,
  40. immediate: false,
  41. },
  42. ].flatMap((testCase) => [
  43. { ...testCase, thinking: false },
  44. { ...testCase, thinking: true },
  45. ]),
  46. )(
  47. 'applies HTTP action $body.action at the output boundary (thinking=$thinking)',
  48. async ({ body, blocked, immediate, guide, thinking }) => {
  49. const fetchImpl = vi
  50. .fn<typeof fetch>()
  51. .mockImplementation(async () => Response.json(body));
  52. const pushRuntime = vi.fn();
  53. const appendEvents = vi.fn();
  54. const writer = new LocalOutputSafetyEventWriter(
  55. { pushRuntime, appendEvents },
  56. { checkText: createContentSafetyChecker({ ...deps, fetchImpl }), chunkThreshold: 1 },
  57. );
  58. await writer.pushRuntime({
  59. schema: 'runtime.event/v1',
  60. event_id: 'action-chunk',
  61. type: RuntimeEventType.STREAM_RESP,
  62. payload: {
  63. stream_resp: JSON.stringify({
  64. type: RespDataType.AgentMessageChunk,
  65. agent_message_chunk: {
  66. msg_id: 'm',
  67. ...(thinking ? { thinking_content: 'draft' } : { msg_content: 'draft' }),
  68. },
  69. }),
  70. },
  71. } as IRuntimeEvent);
  72. expect(writer.blocked).toBe(blocked);
  73. expect(writer.immediateBlock).toBe(immediate);
  74. expect(writer.networkStopped).toBe(false);
  75. // An empty guide leaves regeneration eligible and selects the existing SR.
  76. expect(writer.consumeGuidePrompt()).toBe(guide);
  77. expect(writer.consumeGuidePrompt()).toBeUndefined();
  78. expect(pushRuntime).not.toHaveBeenCalled();
  79. expect(appendEvents).toHaveBeenCalledTimes(blocked ? 0 : 1);
  80. if (!blocked) {
  81. expect(appendEvents).toHaveBeenCalledWith([
  82. expect.objectContaining({ event_id: 'action-chunk' }),
  83. ]);
  84. }
  85. expect(fetchImpl).toHaveBeenCalledOnce();
  86. expect(fetchImpl.mock.calls.at(-1)?.[0]).toMatch(
  87. /\/mavis\/api\/v2\/content\?require_auth=true$/,
  88. );
  89. expect(JSON.parse(String(fetchImpl.mock.calls.at(-1)?.[1]?.body))).toEqual({
  90. content_text: 'draft',
  91. scene: thinking ? 13 : 11,
  92. });
  93. },
  94. );
  95. it('retains the V1 endpoint and payload unless V2 is explicitly selected', async () => {
  96. const fetchImpl = vi
  97. .fn<typeof fetch>()
  98. .mockImplementation(async () => Response.json({ pass: true, decision: 'pass' }));
  99. const legacyDeps = { region: deps.region, buildEnv: deps.buildEnv };
  100. const checker = createContentSafetyChecker({ ...legacyDeps, fetchImpl });
  101. expect(await checker('text', SAFETY_SCENE.UserInput)).toMatchObject({ pass: true });
  102. expect(fetchImpl.mock.calls[0]?.[0]).toMatch(/\/mavis\/api\/v1\/content$/);
  103. expect(JSON.parse(String(fetchImpl.mock.calls[0]?.[1]?.body))).toEqual({
  104. content_text: 'text',
  105. scene: 300,
  106. });
  107. });
  108. it.each([
  109. { action: 4, errorCode: 50201, guide_prompt: 'thinking guide' },
  110. { action: 2, errorCode: 50201 },
  111. ])('keeps DesktopThinking scene 13 after a V2 transport error before action $action', async (body) => {
  112. const fetchImpl = vi
  113. .fn<typeof fetch>()
  114. .mockImplementationOnce(async () => new Response('{}', { status: 503 }))
  115. .mockImplementationOnce(async () => Response.json(body));
  116. const inner = { pushRuntime: vi.fn(), appendEvents: vi.fn() };
  117. const writer = new LocalOutputSafetyEventWriter(inner, {
  118. checkText: createContentSafetyChecker({ ...deps, fetchImpl }),
  119. retryDelay: async () => {},
  120. chunkThreshold: 1,
  121. });
  122. await writer.pushRuntime({
  123. schema: 'runtime.event/v1',
  124. event_id: 'thinking-retry',
  125. type: RuntimeEventType.STREAM_RESP,
  126. payload: {
  127. stream_resp: JSON.stringify({
  128. type: RespDataType.AgentMessageChunk,
  129. agent_message_chunk: { msg_id: 'm', thinking_content: 'thinking draft' },
  130. }),
  131. },
  132. } as IRuntimeEvent);
  133. expect(fetchImpl.mock.calls.map(([url]) => String(url).split('/api/')[1])).toEqual([
  134. 'v2/content?require_auth=true',
  135. 'v2/content?require_auth=true',
  136. ]);
  137. expect(fetchImpl.mock.calls.map(([, init]) => JSON.parse(String(init?.body)))).toEqual([
  138. { content_text: 'thinking draft', scene: 13 },
  139. { content_text: 'thinking draft', scene: 13 },
  140. ]);
  141. expect(writer.blocked).toBe(true);
  142. expect(writer.networkStopped).toBe(false);
  143. expect(writer.immediateBlock).toBe(body.action === 2);
  144. expect(writer.consumeGuidePrompt()).toBe(body.action === 4 ? 'thinking guide' : undefined);
  145. expect(writer.consumeGuidePrompt()).toBeUndefined();
  146. expect(inner.pushRuntime).not.toHaveBeenCalled();
  147. expect(inner.appendEvents).not.toHaveBeenCalled();
  148. });
  149. it('keeps retries of a failed V2 window on V2 even if V1 would now allow', async () => {
  150. let v2Calls = 0;
  151. const fetchImpl = vi.fn<typeof fetch>().mockImplementation(async (url) => {
  152. if (String(url).includes('/v1/content')) return Response.json({ pass: false });
  153. return ++v2Calls === 1
  154. ? new Response('{}', { status: 503 })
  155. : Response.json({ action: 2, errorCode: 50201 });
  156. });
  157. const writer = new LocalOutputSafetyEventWriter(
  158. { pushRuntime: vi.fn(), appendEvents: vi.fn() },
  159. {
  160. checkText: createContentSafetyChecker({ ...deps, fetchImpl }),
  161. retryDelay: async () => {},
  162. chunkThreshold: 1,
  163. },
  164. );
  165. await writer.pushRuntime({
  166. schema: 'runtime.event/v1',
  167. event_id: 'chunk',
  168. type: RuntimeEventType.STREAM_RESP,
  169. payload: {
  170. stream_resp: JSON.stringify({
  171. type: RespDataType.AgentMessageChunk,
  172. agent_message_chunk: { msg_id: 'm', msg_content: 'draft' },
  173. }),
  174. },
  175. } as IRuntimeEvent);
  176. expect(fetchImpl.mock.calls.map(([url]) => String(url).split('/api/')[1])).toEqual([
  177. 'v2/content?require_auth=true',
  178. 'v2/content?require_auth=true',
  179. ]);
  180. expect(writer.immediateBlock).toBe(true);
  181. });
  182. it.each([
  183. [SAFETY_SCENE.UserInput, 110],
  184. [SAFETY_SCENE.MessageOutput, 11],
  185. [SAFETY_SCENE.ThinkingContent, 13],
  186. [SAFETY_SCENE.StreamChunk, 11],
  187. ] as const)('uses V2 for scene %s', async (scene, wireScene) => {
  188. const fetchImpl = vi
  189. .fn<typeof fetch>()
  190. .mockImplementation(async () =>
  191. Response.json({ action: 4, errorCode: 50201, guide_prompt: 'MODEL_ONLY' }),
  192. );
  193. const result = await createContentSafetyChecker({ ...deps, fetchImpl })('text', scene);
  194. expect(result).toEqual({
  195. pass: false,
  196. action: 'guide',
  197. errorKind: 'rejected',
  198. guide_prompt: 'MODEL_ONLY',
  199. });
  200. expect(fetchImpl.mock.calls[0]?.[0]).toMatch(/\/mavis\/api\/v2\/content\?require_auth=true$/);
  201. expect(JSON.parse(String(fetchImpl.mock.calls[0]?.[1]?.body))).toEqual({
  202. content_text: 'text',
  203. scene: wireScene,
  204. });
  205. });
  206. it('keeps ConfigField on its existing V1 endpoint', async () => {
  207. const fetchImpl = vi
  208. .fn<typeof fetch>()
  209. .mockImplementation(async () => Response.json({ pass: true, decision: 'pass' }));
  210. expect(
  211. await createContentSafetyChecker({ ...deps, fetchImpl })('text', SAFETY_SCENE.ConfigField),
  212. ).toMatchObject({ pass: true });
  213. expect(fetchImpl).toHaveBeenCalledOnce();
  214. expect(fetchImpl.mock.calls[0]?.[0]).toMatch(/\/mavis\/api\/v1\/content$/);
  215. });
  216. it('sends a streaming output window directly to V2 as an assistant reply', async () => {
  217. const fetchImpl = vi
  218. .fn<typeof fetch>()
  219. .mockImplementation(async () =>
  220. Response.json({ action: 4, errorCode: 50201, guide_prompt: 'model guide' }),
  221. );
  222. expect(
  223. await createContentSafetyChecker({ ...deps, fetchImpl })('draft', SAFETY_SCENE.StreamChunk),
  224. ).toEqual({
  225. pass: false,
  226. action: 'guide',
  227. guide_prompt: 'model guide',
  228. errorKind: 'rejected',
  229. });
  230. expect(fetchImpl).toHaveBeenCalledOnce();
  231. expect(fetchImpl.mock.calls[0]?.[0]).toMatch(/\/mavis\/api\/v2\/content\?require_auth=true$/);
  232. expect(JSON.parse(String(fetchImpl.mock.calls[0]?.[1]?.body))).toEqual({
  233. content_text: 'draft',
  234. scene: 11,
  235. });
  236. });
  237. it.each([401, 403] as const)(
  238. 'keeps a streaming output window on V2 after HTTP %s refresh',
  239. async (status) => {
  240. let accessToken = 'expired-token';
  241. let v2Calls = 0;
  242. const fetchImpl = vi.fn<typeof fetch>().mockImplementation(async (url) => {
  243. expect(String(url)).toContain('/v2/content?require_auth=true');
  244. v2Calls += 1;
  245. return v2Calls === 1
  246. ? new Response('{}', { status })
  247. : Response.json({ action: 2, errorCode: 50201 });
  248. });
  249. const authContextInvalidator = vi.fn(async () => {
  250. accessToken = 'fresh-token';
  251. });
  252. const result = await createContentSafetyChecker({
  253. ...deps,
  254. fetchImpl,
  255. authContextGetter: () => ({ accessToken }),
  256. authContextInvalidator,
  257. })('draft', SAFETY_SCENE.StreamChunk);
  258. expect(result).toMatchObject({
  259. pass: false,
  260. action: 'reject',
  261. errorKind: 'rejected',
  262. });
  263. expect(authContextInvalidator).toHaveBeenCalledOnce();
  264. expect(authContextInvalidator).toHaveBeenCalledWith('expired-token');
  265. expect(fetchImpl.mock.calls.map(([url]) => String(url).split('/api/')[1])).toEqual([
  266. 'v2/content?require_auth=true',
  267. 'v2/content?require_auth=true',
  268. ]);
  269. expect(fetchImpl.mock.calls.map(([, init]) => JSON.parse(String(init?.body)))).toEqual([
  270. { content_text: 'draft', scene: 11 },
  271. { content_text: 'draft', scene: 11 },
  272. ]);
  273. expect(new Headers(fetchImpl.mock.calls[1]?.[1]?.headers).get('Authorization')).toBe(
  274. 'Bearer fresh-token',
  275. );
  276. },
  277. );
  278. it.each([401, 403])(
  279. 'preserves ConfigField V1 routing on an initial HTTP %s refresh',
  280. async (status) => {
  281. let accessToken = 'expired-token';
  282. const fetchImpl = vi
  283. .fn<typeof fetch>()
  284. .mockImplementationOnce(async () => new Response('{}', { status }))
  285. .mockImplementationOnce(async () => Response.json({ pass: true }));
  286. const authContextInvalidator = vi.fn(async () => {
  287. accessToken = 'fresh-token';
  288. });
  289. const result = await createContentSafetyChecker({
  290. ...deps,
  291. fetchImpl,
  292. authContextGetter: () => ({ accessToken }),
  293. authContextInvalidator,
  294. })('draft', SAFETY_SCENE.ConfigField);
  295. expect(result).toMatchObject({ pass: true });
  296. expect(authContextInvalidator).toHaveBeenCalledOnce();
  297. expect(authContextInvalidator).toHaveBeenCalledWith('expired-token');
  298. expect(fetchImpl.mock.calls.map(([url]) => String(url).split('/api/')[1])).toEqual([
  299. 'v1/content',
  300. 'v1/content',
  301. ]);
  302. expect(fetchImpl.mock.calls.map(([, init]) => JSON.parse(String(init?.body)))).toEqual([
  303. { content_text: 'draft', scene: SAFETY_SCENE.ConfigField },
  304. { content_text: 'draft', scene: SAFETY_SCENE.ConfigField },
  305. ]);
  306. expect(new Headers(fetchImpl.mock.calls[1]?.[1]?.headers).get('Authorization')).toBe(
  307. 'Bearer fresh-token',
  308. );
  309. },
  310. );
  311. it.each([
  312. [SAFETY_SCENE.UserInput, 110],
  313. [SAFETY_SCENE.ThinkingContent, 13],
  314. [SAFETY_SCENE.MessageOutput, 11],
  315. [SAFETY_SCENE.StreamChunk, 11],
  316. ] as const)('preserves V2 scene %s after authentication refresh', async (scene, wireScene) => {
  317. let accessToken = 'expired-token';
  318. const fetchImpl = vi
  319. .fn<typeof fetch>()
  320. .mockImplementationOnce(async () => new Response('{}', { status: 401 }))
  321. .mockImplementationOnce(async () => Response.json({ action: 1 }));
  322. const result = await createContentSafetyChecker({
  323. ...deps,
  324. fetchImpl,
  325. authContextGetter: () => ({ accessToken }),
  326. authContextInvalidator: async () => {
  327. accessToken = 'fresh-token';
  328. },
  329. })('text', scene);
  330. expect(result).toMatchObject({ pass: true, action: 'allow' });
  331. expect(fetchImpl.mock.calls.map(([url]) => String(url).split('/api/')[1])).toEqual([
  332. 'v2/content?require_auth=true',
  333. 'v2/content?require_auth=true',
  334. ]);
  335. expect(fetchImpl.mock.calls.map(([, init]) => JSON.parse(String(init?.body)))).toEqual([
  336. { content_text: 'text', scene: wireScene },
  337. { content_text: 'text', scene: wireScene },
  338. ]);
  339. });
  340. it.each([400, 401, 503])(
  341. 'does not downgrade a failed V2 streaming output review to V1 allow (HTTP %s)',
  342. async (status) => {
  343. const fetchImpl = vi
  344. .fn<typeof fetch>()
  345. .mockImplementation(async () => new Response('{}', { status }));
  346. const result = await createContentSafetyChecker({ ...deps, fetchImpl })(
  347. 'draft',
  348. SAFETY_SCENE.StreamChunk,
  349. );
  350. expect(result).toMatchObject({
  351. pass: false,
  352. errorKind: status === 401 ? 'auth_error' : 'local_error',
  353. });
  354. expect(fetchImpl).toHaveBeenCalledOnce();
  355. },
  356. );
  357. it('keeps default V1 thinking on scene 3 without consuming extra guide fields', async () => {
  358. const legacyDeps = { region: deps.region, buildEnv: deps.buildEnv };
  359. const fetchImpl = vi
  360. .fn<typeof fetch>()
  361. .mockImplementation(async () =>
  362. Response.json({ pass: false, guide_prompt: 'ignored V1 guide' }),
  363. );
  364. expect(
  365. await createContentSafetyChecker({ ...legacyDeps, fetchImpl })(
  366. 'thinking',
  367. SAFETY_SCENE.ThinkingContent,
  368. ),
  369. ).toEqual({ pass: false, errorKind: 'rejected' });
  370. expect(fetchImpl).toHaveBeenCalledOnce();
  371. expect(fetchImpl.mock.calls[0]?.[0]).toMatch(/\/mavis\/api\/v1\/content$/);
  372. expect(JSON.parse(String(fetchImpl.mock.calls[0]?.[1]?.body))).toEqual({
  373. content_text: 'thinking',
  374. scene: 3,
  375. });
  376. });
  377. });