runtime-path.test.ts 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272
  1. import { describe, expect, it, vi } from "vitest";
  2. import { readFile, writeFile, rm } from "node:fs/promises";
  3. import { join } from "node:path";
  4. import { runRegression } from "#public";
  5. import { selectCases } from "#regression/cases";
  6. import { fixture, chatResponse } from "#test/fixture";
  7. describe("product runtime regression", () => {
  8. it("重复工具编号归并成一次真实工具闭环", () => {
  9. expect(selectCases(["TOOL-001", "TOOL-002"]).map((c) => c.id)).toEqual(["TOOL-001"]);
  10. expect(selectCases(["TOOL-002"]).map((c) => c.id)).toEqual(["TOOL-001"]);
  11. });
  12. it("文本用例走产品会话,仅发送流式请求并使用产品来源头", async () => {
  13. const f = await fixture();
  14. try {
  15. await writeFile(
  16. f.options.listFile,
  17. JSON.stringify({ ...f.list, caseIds: ["TEXT-001"], timeoutMs: 30000 }),
  18. );
  19. const requests: Record<string, unknown>[] = [];
  20. const report = await runRegression({
  21. ...f.options,
  22. transport: async (_url, init) => {
  23. const body = JSON.parse(String(init?.body));
  24. requests.push(body);
  25. expect(new Headers(init?.headers).get("x-title")).toBe("Z Code@electron");
  26. expect(new Headers(init?.headers).get("x-zcode-app-version")).toMatch(/^\d+\.\d+\.\d+/);
  27. expect(body.stream).toBe(true);
  28. expect(body.messages.some((m: { role: string }) => m.role === "system")).toBe(true);
  29. return chatResponse();
  30. },
  31. });
  32. expect(report.rows[0].status, report.rows[0].detail).toBe("passed");
  33. expect(report.rows[0].executionPath).toBe("session");
  34. expect(report.rows[0].maxOutputTokens).toBeUndefined();
  35. expect(requests).toHaveLength(1);
  36. const persisted = await readFile(f.options.listFile, "utf8");
  37. expect(persisted).toContain("TEXT-001");
  38. } finally {
  39. await rm(f.dir, { recursive: true, force: true });
  40. }
  41. });
  42. });
  43. it("搜索复用产品 handler 的低档位与流式请求,摘要无结构化来源仍成功", async () => {
  44. const f = await fixture("anthropic-messages");
  45. try {
  46. const path = join(f.dir, "builtin.json");
  47. const builtin = JSON.parse(await readFile(path, "utf8"));
  48. builtin.config.modelConfigRules.modelRules[0].config.properties.supportsNativeWebSearch = true;
  49. await writeFile(path, JSON.stringify(builtin));
  50. await writeFile(f.options.listFile, JSON.stringify({ ...f.list, caseIds: ["WEB-001"] }));
  51. const report = await runRegression({
  52. ...f.options,
  53. transport: async (_url, init) => {
  54. const body = JSON.parse(String(init?.body));
  55. expect(body.stream).toBe(true);
  56. expect(body.reasoning_effort).toBe("low");
  57. expect(body.max_tokens).toBe(4096);
  58. const events = [
  59. {
  60. type: "message_start",
  61. message: {
  62. id: "m",
  63. type: "message",
  64. role: "assistant",
  65. model: "model-a",
  66. content: [],
  67. stop_reason: null,
  68. stop_sequence: null,
  69. usage: { input_tokens: 1, output_tokens: 0 },
  70. },
  71. },
  72. { type: "content_block_start", index: 0, content_block: { type: "text", text: "" } },
  73. {
  74. type: "content_block_delta",
  75. index: 0,
  76. delta: { type: "text_delta", text: "IANA example domain summary" },
  77. },
  78. { type: "content_block_stop", index: 0 },
  79. {
  80. type: "message_delta",
  81. delta: { stop_reason: "end_turn", stop_sequence: null },
  82. usage: { output_tokens: 5 },
  83. },
  84. { type: "message_stop" },
  85. ];
  86. return new Response(
  87. events.map((e) => `event: ${e.type}\ndata: ${JSON.stringify(e)}\n\n`).join(""),
  88. { headers: { "content-type": "text/event-stream" } },
  89. );
  90. },
  91. });
  92. expect(report.rows[0].status, report.rows[0].detail).toBe("passed");
  93. expect(report.rows[0].executionPath).toBe("websearch-handler");
  94. expect(report.rows[0].reasoningLevel).toBe("low");
  95. expect(report.rows[0].maxOutputTokens).toBe(4096);
  96. expect(report.rows[0].detail).toContain("0 项");
  97. } finally {
  98. await rm(f.dir, { recursive: true, force: true });
  99. }
  100. });
  101. it("无效 PDF 沿产品附件降级,不将无效文件直接送到供应商", async () => {
  102. const f = await fixture();
  103. try {
  104. const path = join(f.dir, "builtin.json");
  105. const builtin = JSON.parse(await readFile(path, "utf8"));
  106. builtin.config.modelConfigRules.modelRules[0].config.properties.inputFormat.supportsPdf = true;
  107. await writeFile(path, JSON.stringify(builtin));
  108. await writeFile(join(f.dir, "invalid.pdf"), "not a PDF");
  109. await writeFile(
  110. f.options.listFile,
  111. JSON.stringify({
  112. ...f.list,
  113. caseIds: ["PDF-001"],
  114. timeoutMs: 30000,
  115. fixtures: {
  116. pdf: {
  117. path: "invalid.pdf",
  118. mediaType: "application/pdf",
  119. prompt: "读附件",
  120. expected: "value",
  121. },
  122. },
  123. }),
  124. );
  125. let calls = 0;
  126. const report = await runRegression({
  127. ...f.options,
  128. transport: async (_url, init) => {
  129. calls++;
  130. expect(String(init?.body)).not.toContain(Buffer.from("not a PDF").toString("base64"));
  131. expect(String(init?.body)).not.toContain('"file_data"');
  132. return chatResponse();
  133. },
  134. });
  135. expect(report.rows[0].status).toBe("review");
  136. expect(calls).toBe(1);
  137. } finally {
  138. await rm(f.dir, { recursive: true, force: true });
  139. }
  140. });
  141. it("1 pass 保留产品瞬态错误重试,报告记录实际请求次数", async () => {
  142. const f = await fixture();
  143. vi.stubEnv("ZCODE_MODEL_RETRY_BASE_DELAY_MS", "0");
  144. try {
  145. await writeFile(
  146. f.options.listFile,
  147. JSON.stringify({ ...f.list, repetitions: 1, timeoutMs: 30000 }),
  148. );
  149. let calls = 0;
  150. const report = await runRegression({
  151. ...f.options,
  152. transport: async () => {
  153. calls++;
  154. return calls === 1 ? new Response("unavailable", { status: 503 }) : chatResponse();
  155. },
  156. });
  157. expect(report.rows.every((row) => row.status === "passed")).toBe(true);
  158. expect(report.rows).toHaveLength(2);
  159. expect(report.rows.map((row) => row.requestCount)).toEqual([2, 1]);
  160. } finally {
  161. vi.unstubAllEnvs();
  162. await rm(f.dir, { recursive: true, force: true });
  163. }
  164. });
  165. it.each([true, false])(
  166. "MCS 两轮使用产品历史并累计指标,第二轮有思考=%s",
  167. async (secondReasoning) => {
  168. const f = await fixture();
  169. let clock = 100;
  170. const now = vi.spyOn(performance, "now").mockImplementation(() => clock);
  171. try {
  172. await writeFile(
  173. f.options.listFile,
  174. JSON.stringify({ ...f.list, caseIds: ["SYSTEM-001"], repetitions: 1, timeoutMs: 30000 }),
  175. );
  176. let calls = 0;
  177. const report = await runRegression({
  178. ...f.options,
  179. transport: async (_url, init) => {
  180. const body = JSON.parse(String(init?.body));
  181. const token = ++calls === 1 ? "OLD" : "BLUE-42";
  182. if (calls === 2) clock = 10000;
  183. expect(body.stream).toBe(true);
  184. const messages = body.messages as { role: string; content: unknown }[];
  185. const last = messages.at(-1)!;
  186. expect(last.role).toBe("system");
  187. expect(JSON.stringify(last.content)).toContain(token);
  188. expect(messages.at(-2)?.role).toBe("user");
  189. if (calls === 2)
  190. expect(
  191. messages.some(
  192. (m) => m.role === "assistant" && JSON.stringify(m.content).includes("OLD"),
  193. ),
  194. ).toBe(true);
  195. const response = chatResponse();
  196. const text = await response.text();
  197. const lines = text.split("\n").map((line) => {
  198. if (!line.startsWith("data: {")) return line;
  199. const chunk = JSON.parse(line.slice(6));
  200. if (chunk.choices[0].delta.content) chunk.choices[0].delta.content = token;
  201. if (calls === 2 && !secondReasoning) delete chunk.choices[0].delta.reasoning_content;
  202. return `data: ${JSON.stringify(chunk)}`;
  203. });
  204. return new Response(lines.join("\n"), { headers: response.headers });
  205. },
  206. });
  207. expect(report.rows[0].status, report.rows[0].detail).toBe("passed");
  208. expect(report.rows[0].executionPath).toBe("session");
  209. expect(report.rows[0].requestCount).toBe(2);
  210. expect(calls).toBe(2);
  211. expect(report.rows[0].reasoningCharacters).toBe(secondReasoning ? 6 : 3);
  212. expect(report.rows[0].firstTextMs).toBe(0);
  213. } finally {
  214. now.mockRestore();
  215. await rm(f.dir, { recursive: true, force: true });
  216. }
  217. },
  218. );
  219. it.each([
  220. ["pdf", "PDF-001", "supportsPdf", 8 * 1024 * 1024, true],
  221. ["pdf", "PDF-001", "supportsPdf", 8 * 1024 * 1024 + 1, false],
  222. ["image", "IMAGE-001", "supportsImage", 8 * 1024 * 1024 + 1, false],
  223. ["video", "VIDEO-001", "supportsVideo", 8 * 1024 * 1024 + 1, false],
  224. ] as const)(
  225. "素材边界:%s / %s / %s / %i 字节 / 可读取=%s",
  226. async (kind, caseId, property, size, accepted) => {
  227. const f = await fixture();
  228. try {
  229. const path = join(f.dir, "builtin.json");
  230. const builtin = JSON.parse(await readFile(path, "utf8"));
  231. builtin.config.modelConfigRules.modelRules[0].config.properties.inputFormat[property] = true;
  232. await writeFile(path, JSON.stringify(builtin));
  233. await writeFile(join(f.dir, "media.bin"), Buffer.alloc(size));
  234. await writeFile(
  235. f.options.listFile,
  236. JSON.stringify({
  237. ...f.list,
  238. caseIds: [caseId],
  239. timeoutMs: 30000,
  240. fixtures: {
  241. [kind]: {
  242. path: "media.bin",
  243. mediaType:
  244. kind === "pdf" ? "application/pdf" : `${kind}/${kind === "image" ? "png" : "mp4"}`,
  245. prompt: "读附件",
  246. expected: "marker",
  247. },
  248. },
  249. }),
  250. );
  251. const transport = vi.fn(async () => chatResponse());
  252. const report = await runRegression({ ...f.options, transport });
  253. if (accepted) {
  254. // 边界内的无效 PDF 仍交给产品附件链降级,测试器不另造附件处理。
  255. expect(transport).toHaveBeenCalledTimes(1);
  256. expect(report.rows[0].detail).not.toContain("8 MiB");
  257. } else {
  258. expect(transport).not.toHaveBeenCalled();
  259. expect(report.rows[0].status).toBe("failed");
  260. expect(report.rows[0].detail).toContain("8 MiB");
  261. }
  262. } finally {
  263. await rm(f.dir, { recursive: true, force: true });
  264. }
  265. },
  266. );