e2eNetworkCaptureReplay.test.ts 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352
  1. import { createServer, request } from "node:http";
  2. import { mkdtemp, readFile, rm } from "node:fs/promises";
  3. import { tmpdir } from "node:os";
  4. import { join } from "node:path";
  5. import { expect, it } from "vitest";
  6. import { startE2ENetworkCaptureProxy } from "./e2e/helpers/network-capture-proxy.js";
  7. import { startUpstreamReplayServer } from "#e2e/helpers/upstream-replay-server";
  8. it("GLM-5.2 的标题夹具接纳明确关闭思考的实际请求字段", async () => {
  9. const dir = await mkdtemp(join(tmpdir(), "glm52-title-replay-"));
  10. const upstream = await startUpstreamReplayServer({
  11. artifactPath: join(dir, "capture.json"),
  12. fixturePaths: [
  13. join(
  14. import.meta.dirname,
  15. "e2e/fixtures/upstream/conversation-session/conversation-session-glm52-reasoning-request-shape.json",
  16. ),
  17. ],
  18. });
  19. try {
  20. const response = await fetch(`${upstream.baseUrl}/chat/completions`, {
  21. method: "POST",
  22. headers: { "content-type": "application/json" },
  23. body: JSON.stringify({
  24. model: "GLM-5.2",
  25. thinking: { type: "disabled" },
  26. enable_thinking: false,
  27. reasoning_effort: "none",
  28. messages: [
  29. { role: "system", content: "Generate a concise title for this coding session." },
  30. { role: "user", content: "E2E_GLM52_REASONING_MAX" },
  31. ],
  32. }),
  33. });
  34. expect(response.status).toBe(200);
  35. const title = await response.json();
  36. expect(title.object).toBe("chat.completion");
  37. expect(JSON.parse(title.choices[0].message.content).title).toBeTruthy();
  38. } finally {
  39. await upstream.stop();
  40. await rm(dir, { recursive: true, force: true });
  41. }
  42. });
  43. it("Goal 时间线的新目标未完成后有可取消的正常续跑响应", async () => {
  44. const dir = await mkdtemp(join(tmpdir(), "goal-timeline-replay-"));
  45. const upstream = await startUpstreamReplayServer({
  46. artifactPath: join(dir, "capture.json"),
  47. fixturePaths: [
  48. join(
  49. import.meta.dirname,
  50. "e2e/fixtures/upstream/conversation-session/conversation-session-goal-timeline.json",
  51. ),
  52. ],
  53. });
  54. try {
  55. for (const prompt of [
  56. "E2E_GOAL_TIMELINE_REPRO_A Continue working toward the active session goal",
  57. "E2E_GOAL_TIMELINE_REPRO_A Completion verifier result: Reason: 第一轮只有九个汉字。 写出恰好十个汉字的科幻小说",
  58. "E2E_GOAL_TIMELINE_REPRO_B Continue working toward the active session goal",
  59. ]) {
  60. const prior = await fetch(`${upstream.baseUrl}/messages`, {
  61. method: "POST",
  62. headers: { "content-type": "application/json" },
  63. body: JSON.stringify({
  64. model: "test-model",
  65. stream: true,
  66. messages: [{ role: "user", content: prompt }],
  67. }),
  68. });
  69. expect(prior.status).toBe(200);
  70. await prior.text();
  71. }
  72. const response = await fetch(`${upstream.baseUrl}/messages`, {
  73. method: "POST",
  74. headers: { "content-type": "application/json" },
  75. body: JSON.stringify({
  76. model: "test-model",
  77. stream: true,
  78. messages: [
  79. {
  80. role: "user",
  81. content:
  82. "E2E_GOAL_TIMELINE_REPRO_B Continue working toward the active session goal. Completion verifier result: Reason: 没有交付 10w 字小说。 Next action: 继续写 10w 字小说。",
  83. },
  84. ],
  85. }),
  86. });
  87. expect(response.status).toBe(200);
  88. const gates = await fetch(`${upstream.baseUrl}/__e2e__/gates`).then((res) => res.json());
  89. expect(gates).toContain("upstream-goal-timeline-new-target-continuation");
  90. await response.body?.cancel();
  91. } finally {
  92. await upstream.stop();
  93. await rm(dir, { recursive: true, force: true });
  94. }
  95. });
  96. it("模型回归目录的标题不得命中包含同一 E2E marker 的正文 fixture", async () => {
  97. const dir = await mkdtemp(join(tmpdir(), "catalog-title-replay-"));
  98. const upstream = await startUpstreamReplayServer({
  99. artifactPath: join(dir, "capture.json"),
  100. fixturePaths: [
  101. join(
  102. import.meta.dirname,
  103. "e2e/fixtures/upstream/conversation-session/conversation-session-model-provider-regression-gaps.json",
  104. ),
  105. ],
  106. });
  107. try {
  108. const response = await fetch(`${upstream.baseUrl}/messages`, {
  109. method: "POST",
  110. headers: { "content-type": "application/json" },
  111. body: JSON.stringify({
  112. model: "test-model",
  113. messages: [
  114. {
  115. role: "user",
  116. content:
  117. 'Generate a concise title for E2E_CATALOG_WORKSPACE_A: Reply with exactly "upstream-e2e-ok"',
  118. },
  119. ],
  120. }),
  121. });
  122. expect(response.status).toBe(200);
  123. const title = await response.json();
  124. expect(title.type).toBe("message");
  125. expect(JSON.parse(title.content[0].text).title).toBeTruthy();
  126. } finally {
  127. await upstream.stop();
  128. await rm(dir, { recursive: true, force: true });
  129. }
  130. });
  131. it("SR87 账号请求通过 case-local matcher,R95C 首发与标题分别返回 SSE 和 JSON", async () => {
  132. const dir = await mkdtemp(join(tmpdir(), "zcode-sr87-replay-"));
  133. const upstream = await startUpstreamReplayServer({
  134. artifactPath: join(dir, "upstream.json"),
  135. fixturePaths: [
  136. join(
  137. import.meta.dirname,
  138. "e2e/fixtures/upstream/conversation-session/conversation-session-model-provider-effective-selection.json",
  139. ),
  140. ],
  141. });
  142. let proxy: Awaited<ReturnType<typeof startE2ENetworkCaptureProxy>> | undefined;
  143. try {
  144. proxy = await startE2ENetworkCaptureProxy({
  145. artifactPath: join(dir, "proxy.json"),
  146. caDir: join(dir, "ca"),
  147. requestRedirects: [
  148. {
  149. host: "model.example.test",
  150. path: "/api/anthropic/v1/messages",
  151. targetUrl: `${upstream.baseUrl}/messages`,
  152. },
  153. ],
  154. responseMocks: [
  155. {
  156. host: "model.example.test",
  157. path: "/api/anthropic/v1/messages",
  158. body: "wrong-static-response",
  159. },
  160. ],
  161. });
  162. const address = new URL(proxy.proxyUrl);
  163. const replies = await Promise.all(
  164. [true, false].map(async (stream) => {
  165. const response = await new Promise<import("node:http").IncomingMessage>(
  166. (resolve, reject) => {
  167. const req = request(
  168. {
  169. hostname: address.hostname,
  170. port: address.port,
  171. path: "http://model.example.test/api/anthropic/v1/messages",
  172. method: "POST",
  173. headers: { host: "model.example.test", "content-type": "application/json" },
  174. },
  175. resolve,
  176. );
  177. req.on("error", reject);
  178. req.end(
  179. JSON.stringify({
  180. model: "GLM-5.2",
  181. stream,
  182. messages: [
  183. {
  184. role: "user",
  185. content: stream
  186. ? "E2E_R95C_SEND: Reply briefly."
  187. : "Generate a concise title for E2E_R95C_SEND",
  188. },
  189. ],
  190. }),
  191. );
  192. },
  193. );
  194. let body = "";
  195. for await (const chunk of response) body += String(chunk);
  196. return { status: response.statusCode, type: response.headers["content-type"], body };
  197. }),
  198. );
  199. expect(replies.map((response) => response.status)).toEqual([200, 200]);
  200. expect(replies[0]!.type).toContain("text/event-stream");
  201. expect(replies[0]!.body).toContain("coding-plan-e2e-ok");
  202. expect(replies[1]!.type).toContain("application/json");
  203. const title = JSON.parse(replies[1]!.body);
  204. expect(title.type).toBe("message");
  205. expect(JSON.parse(title.content[0].text).title).toBeTruthy();
  206. } finally {
  207. await proxy?.stop();
  208. await upstream.stop();
  209. await rm(dir, { recursive: true, force: true });
  210. }
  211. });
  212. it("同一模型端点区分普通 JSON 标题与流式正文,并保存真实响应类型", async () => {
  213. const dir = await mkdtemp(join(tmpdir(), "zcode-response-type-"));
  214. const artifactPath = join(dir, "capture.json");
  215. const proxy = await startE2ENetworkCaptureProxy({
  216. artifactPath,
  217. caDir: join(dir, "ca"),
  218. responseMocks: [
  219. {
  220. host: "model.example.test",
  221. path: "/messages",
  222. headers: (body: string) => ({
  223. "content-type":
  224. JSON.parse(body).stream === true ? "text/event-stream" : "application/json",
  225. }),
  226. body: (body) =>
  227. JSON.parse(body).stream === true ? "data: reply\n\n" : '{"title":"Fixture"}',
  228. },
  229. ],
  230. });
  231. let stopped = false;
  232. try {
  233. const proxyAddress = new URL(proxy.proxyUrl);
  234. for (const stream of [false, true]) {
  235. const response = await new Promise<import("node:http").IncomingMessage>((resolve, reject) => {
  236. const req = request(
  237. {
  238. hostname: proxyAddress.hostname,
  239. port: proxyAddress.port,
  240. path: "http://model.example.test/messages",
  241. method: "POST",
  242. headers: { host: "model.example.test", "content-type": "application/json" },
  243. },
  244. resolve,
  245. );
  246. req.on("error", reject);
  247. req.end(JSON.stringify({ stream }));
  248. });
  249. let body = "";
  250. for await (const chunk of response) body += String(chunk);
  251. expect(response.headers["content-type"]).toBe(
  252. stream ? "text/event-stream" : "application/json",
  253. );
  254. expect(body).toBe(stream ? "data: reply\n\n" : '{"title":"Fixture"}');
  255. }
  256. await proxy.stop();
  257. stopped = true;
  258. const capture = JSON.parse(await readFile(artifactPath, "utf8"));
  259. expect(
  260. capture.records.map(
  261. (record: { responseHeaders: Record<string, string> }) =>
  262. record.responseHeaders["content-type"],
  263. ),
  264. ).toEqual(["application/json", "text/event-stream"]);
  265. } finally {
  266. if (!stopped) await proxy.stop();
  267. await rm(dir, { recursive: true, force: true });
  268. }
  269. });
  270. it("账号数据面转发到受控回放时保留首块、请求体和原地址证据", async () => {
  271. const dir = await mkdtemp(join(tmpdir(), "zcode-account-replay-"));
  272. let release = () => {};
  273. const gate = new Promise<void>((resolve) => {
  274. release = resolve;
  275. });
  276. let received = "";
  277. let path = "";
  278. const upstream = createServer(async (req, res) => {
  279. path = req.url ?? "";
  280. for await (const chunk of req) received += String(chunk);
  281. res.writeHead(200, { "content-type": "text/event-stream" });
  282. res.write("first\n");
  283. await gate;
  284. res.end("last\n");
  285. });
  286. await new Promise<void>((resolve) => upstream.listen(0, "127.0.0.1", resolve));
  287. const address = upstream.address();
  288. if (!address || typeof address === "string") throw new Error("fixture 未绑定端口");
  289. const artifactPath = join(dir, "capture.json");
  290. const proxy = await startE2ENetworkCaptureProxy({
  291. artifactPath,
  292. caDir: join(dir, "ca"),
  293. requestRedirects: [
  294. {
  295. host: "127.0.0.1:9",
  296. path: "/api/anthropic/v1/messages",
  297. targetUrl: `http://127.0.0.1:${address.port}/messages`,
  298. },
  299. ],
  300. responseMocks: [
  301. { host: "127.0.0.1:9", path: "/api/anthropic/v1/messages", body: "wrong-fallback" },
  302. ],
  303. });
  304. let stopped = false;
  305. try {
  306. const proxyAddress = new URL(proxy.proxyUrl);
  307. const response = await new Promise<import("node:http").IncomingMessage>((resolve, reject) => {
  308. const req = request(
  309. {
  310. hostname: proxyAddress.hostname,
  311. port: proxyAddress.port,
  312. path: "http://127.0.0.1:9/api/anthropic/v1/messages",
  313. method: "POST",
  314. headers: { host: "127.0.0.1:9", "content-type": "application/json" },
  315. },
  316. resolve,
  317. );
  318. req.on("error", reject);
  319. req.end(JSON.stringify({ messages: [{ role: "user", content: "queue marker" }] }));
  320. });
  321. const chunks = response[Symbol.asyncIterator]();
  322. expect(String((await chunks.next()).value)).toBe("first\n");
  323. expect(path).toBe("/messages");
  324. expect(JSON.parse(received).messages[0].content).toBe("queue marker");
  325. release();
  326. expect(String((await chunks.next()).value)).toBe("last\n");
  327. expect((await chunks.next()).done).toBe(true);
  328. await proxy.stop();
  329. stopped = true;
  330. const capture = JSON.parse(await readFile(artifactPath, "utf8"));
  331. expect(capture.records).toEqual([
  332. expect.objectContaining({
  333. host: "127.0.0.1:9",
  334. path: "/api/anthropic/v1/messages",
  335. status: "complete",
  336. responseTextPreview: "first\nlast\n",
  337. requestJson: JSON.parse(received),
  338. }),
  339. ]);
  340. } finally {
  341. release();
  342. if (!stopped) await proxy.stop();
  343. await new Promise<void>((resolve) => upstream.close(() => resolve()));
  344. await rm(dir, { recursive: true, force: true });
  345. }
  346. });