conversation-session-tool-input-validation-provider-content.test.ts 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220
  1. import { clearAppData, waitForDefaultWorkspaceReady } from "#e2e/helpers/desktop-app";
  2. import { waitForUpstreamNetworkCapture } from "#e2e/helpers/upstream-capture";
  3. import { reloadElectronSessionSafely } from "#e2e/helpers/e2e-electron-reload";
  4. import {
  5. prepareV4ConversationE2E,
  6. selectV4TaskById,
  7. sendV4Prompt,
  8. waitForV4AssistantMessageContaining,
  9. waitForV4Pane,
  10. waitForV4TimelineContaining,
  11. } from "#e2e/helpers/v4-conversation";
  12. import {
  13. beginConversationTelemetryCapture,
  14. readAllEventReportRequests,
  15. type ConversationTelemetryCaptureHandle,
  16. type ConversationTelemetryReport,
  17. } from "#e2e/helpers/conversation-telemetry-parity-capture";
  18. const PROMPT_MARKER = "E2E_TOOL_INPUT_VALIDATION_PROVIDER_CONTENT";
  19. const COLD_PROMPT_MARKER = "E2E_TOOL_INPUT_VALIDATION_COLD_REPLAY";
  20. const RAW_INPUT_MARKER = "E2E_TOOL_INPUT_VALIDATION_RAW_INPUT";
  21. const RAW_INPUT = `not-json-${RAW_INPUT_MARKER}`;
  22. const LIVE_DONE = "E2E_TOOL_INPUT_VALIDATION_LIVE_OK";
  23. const COLD_DONE = "E2E_TOOL_INPUT_VALIDATION_COLD_OK";
  24. const TOOL_CALL_ID = "toolu_e2e_tool_input_validation";
  25. const TOOL_NAME = "AskUserQuestion";
  26. const LEGACY_VALIDATION_CONTENT = "Tool input failed inputSchema validation";
  27. // 入参 JSON 无法解析时不再按 {} 报缺参;错误正文带原始串的预览(不超过 200 个码元)。
  28. const MISSING_PARAMETER_CONTENT = "The required parameter `questions` is missing";
  29. const VALIDATION_CONTENT = [
  30. "<tool_use_error>InputValidationError: AskUserQuestion was called with input that could not be parsed as JSON.",
  31. `You sent (first ${RAW_INPUT.length} of ${RAW_INPUT.length} bytes): ${RAW_INPUT}`,
  32. "Common causes: unescaped backslashes in file paths (use / or \\\\), unescaped control characters, or truncated output. Retry with valid JSON.</tool_use_error>",
  33. ].join("\n");
  34. describe("Z02 工具输入校验 provider content E2E", () => {
  35. after(async () => {
  36. await browser.electron.restoreAllMocks();
  37. await clearAppData();
  38. });
  39. it("malformed arguments 的精确 error tool result 在 live 与 cold replay 中保持一致", async function () {
  40. this.timeout(240000);
  41. await prepareV4ConversationE2E();
  42. const telemetry = await beginConversationTelemetryCapture();
  43. const baseline = toolStepsOf(await readAllEventReportRequests(telemetry)).length;
  44. const runId = Date.now();
  45. const prompt = `${PROMPT_MARKER}_${runId}: trigger the malformed tool input fixture.`;
  46. await sendV4Prompt(prompt);
  47. const liveContinuation = await waitForUpstreamNetworkCapture(VALIDATION_CONTENT);
  48. expect(liveContinuation.statusCode).toBe(200);
  49. assertValidationHistory(liveContinuation.requestJson);
  50. await waitForV4TimelineContaining(LIVE_DONE, 60000);
  51. const completed = await waitForV4Pane(
  52. (snapshot) =>
  53. snapshot.sessionId !== null &&
  54. snapshot.sessionId !== "draft" &&
  55. !snapshot.canStop &&
  56. snapshot.timelineText.includes(LIVE_DONE),
  57. "malformed tool input continuation 没有完成",
  58. 60000,
  59. );
  60. const sessionId = completed.sessionId;
  61. if (!sessionId || sessionId === "draft") {
  62. throw new Error(`malformed tool input case 缺少真实 sessionId: ${sessionId ?? "null"}`);
  63. }
  64. await assertToolFailureTelemetry(telemetry, baseline);
  65. // Bug 回归边界:renderer refresh 仍可能复用 CLI 内存;必须等待旧 Electron、
  66. // Host 和 Agent 进程树完整退出,才能证明 provider content 来自持久化历史。
  67. await reloadElectronSessionSafely(browser);
  68. await waitForDefaultWorkspaceReady(60000);
  69. // 完整进程重启后 task index 可能晚于 workspace ready;这里只延长该恢复边界,
  70. // 不给 live/provider 断言增加重试或降级路径。
  71. await selectV4TaskById(sessionId, 60000);
  72. await waitForV4Pane(
  73. (snapshot) => snapshot.sessionId === sessionId && !snapshot.canStop,
  74. `CLI cold restart 后没有恢复 session ${sessionId}`,
  75. 60000,
  76. );
  77. const coldPrompt = `${COLD_PROMPT_MARKER}_${runId}: reply with exactly ${COLD_DONE}.`;
  78. await sendV4Prompt(coldPrompt);
  79. const coldRequest = await waitForUpstreamNetworkCapture(coldPrompt);
  80. expect(coldRequest.statusCode).toBe(200);
  81. assertValidationHistory(coldRequest.requestJson);
  82. await waitForV4AssistantMessageContaining(COLD_DONE, 60000);
  83. await waitForV4Pane(
  84. (snapshot) =>
  85. snapshot.sessionId === sessionId &&
  86. !snapshot.canStop &&
  87. snapshot.timelineText.includes(COLD_DONE),
  88. "cold follow-up 没有完成",
  89. 60000,
  90. );
  91. });
  92. });
  93. function assertValidationHistory(requestJson: unknown) {
  94. const serialized = JSON.stringify(requestJson);
  95. // 原始串只出现在 tool_result 的预览里一次;tool_use.input 仍是 {}(下方精确断言)。
  96. expect(serialized.split(RAW_INPUT_MARKER)).toHaveLength(2);
  97. expect(serialized).not.toContain(LEGACY_VALIDATION_CONTENT);
  98. expect(serialized).not.toContain(MISSING_PARAMETER_CONTENT);
  99. const messages = readRecordArray(readRecord(requestJson).messages);
  100. const contentBlocks = messages.flatMap((message, messageIndex) =>
  101. readContentBlocks(message).map((block) => ({
  102. block,
  103. message,
  104. messageIndex,
  105. })),
  106. );
  107. const toolUses = contentBlocks.filter(
  108. ({ block }) => block.type === "tool_use" && block.id === TOOL_CALL_ID,
  109. );
  110. const toolResults = contentBlocks.filter(
  111. ({ block }) => block.type === "tool_result" && block.tool_use_id === TOOL_CALL_ID,
  112. );
  113. expect(toolUses).toHaveLength(1);
  114. expect(toolResults).toHaveLength(1);
  115. const toolUse = toolUses[0]!;
  116. const toolResult = toolResults[0]!;
  117. expect(toolUse.messageIndex).toBeGreaterThanOrEqual(0);
  118. expect(toolResult.messageIndex).toBe(toolUse.messageIndex + 1);
  119. expect(toolUse.message.role).toBe("assistant");
  120. expect(toolResult.message.role).toBe("user");
  121. const expectedToolUse = {
  122. type: "tool_use",
  123. id: TOOL_CALL_ID,
  124. name: TOOL_NAME,
  125. input: {},
  126. };
  127. const expectedToolResult = {
  128. type: "tool_result",
  129. tool_use_id: TOOL_CALL_ID,
  130. is_error: true,
  131. content: VALIDATION_CONTENT,
  132. };
  133. // thinking 是独立的推理投影;本 case 只允许它与唯一目标 tool_use 共存,
  134. // 其他 text 或 tool block 仍应让精确 provider message 合同失败。
  135. expect(
  136. readContentBlocks(toolUse.message)
  137. .filter((block) => block.type !== "thinking")
  138. .map(withoutCacheControl),
  139. ).toEqual([expectedToolUse]);
  140. expect(readContentBlocks(toolResult.message).map(withoutCacheControl)).toEqual([
  141. expectedToolResult,
  142. ]);
  143. }
  144. function toolStepsOf(reports: ConversationTelemetryReport[]) {
  145. return reports.filter(
  146. (r) =>
  147. r.element_name === "agent_step" &&
  148. (r.event_extra_detail as Record<string, string> | undefined)?.tool_call_id === TOOL_CALL_ID,
  149. );
  150. }
  151. /**
  152. * 工具失败原因码:CLI 的 schema 校验失败是 ToolExecutionFailed(不是 InvalidInput),工具 step
  153. * 带 error_code=tool_execution_failed,error_type 保持旧口径;错误原文与模型给的原始参数都不出现在
  154. * 上报里。只看本用例开始后的增量。
  155. */
  156. async function assertToolFailureTelemetry(
  157. telemetry: ConversationTelemetryCaptureHandle,
  158. baseline: number,
  159. ) {
  160. let reports: ConversationTelemetryReport[] = [];
  161. await browser.waitUntil(
  162. async () => {
  163. reports = await readAllEventReportRequests(telemetry);
  164. return toolStepsOf(reports).length > baseline;
  165. },
  166. { timeout: 30000, timeoutMsg: `${TOOL_CALL_ID} 的 agent_step 没有上报` },
  167. );
  168. const steps = toolStepsOf(reports);
  169. expect(steps).toHaveLength(baseline + 1);
  170. expect(steps[baseline]!.event_extra_detail).toMatchObject({
  171. tool_name: TOOL_NAME,
  172. status: "fail",
  173. error_type: "TOOL_EXEC_ERROR",
  174. error_code: "tool_execution_failed",
  175. error_msg: "[redacted]",
  176. });
  177. const serialized = JSON.stringify(reports);
  178. expect(serialized).not.toContain("InputValidationError");
  179. expect(serialized).not.toContain(RAW_INPUT_MARKER);
  180. }
  181. function readRecord(value: unknown): Record<string, unknown> {
  182. if (!value || typeof value !== "object" || Array.isArray(value)) {
  183. throw new Error(`期望 object,实际为 ${JSON.stringify(value)}`);
  184. }
  185. return value as Record<string, unknown>;
  186. }
  187. function readRecordArray(value: unknown): Record<string, unknown>[] {
  188. if (!Array.isArray(value)) {
  189. throw new Error(`期望 array,实际为 ${JSON.stringify(value)}`);
  190. }
  191. return value.map(readRecord);
  192. }
  193. function readContentBlocks(message: Record<string, unknown>) {
  194. return readRecordArray(message.content);
  195. }
  196. function withoutCacheControl(block: Record<string, unknown>) {
  197. const result = { ...block };
  198. delete result.cache_control;
  199. return result;
  200. }