upstreamReplayServer.test.ts 48 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384
  1. import { mkdtemp, open, readFile, rm, writeFile } from "node:fs/promises";
  2. import { createServer as createNetServer, type Server as NetServer } from "node:net";
  3. import { tmpdir } from "node:os";
  4. import { join } from "node:path";
  5. import { afterEach, describe, expect, it, vi } from "vitest";
  6. import {
  7. startUpstreamReplayServer,
  8. type UpstreamReplayServer,
  9. } from "./e2e/helpers/upstream-replay-server.js";
  10. import type { E2ENetworkCaptureArtifact } from "./e2e/helpers/network-capture-proxy.js";
  11. const SSE_EVENT_TEXT = 'event: message_start\ndata: {"type":"message_start"}\n\n';
  12. const activeServers: UpstreamReplayServer[] = [];
  13. const tempDirs: string[] = [];
  14. afterEach(async () => {
  15. await Promise.all(activeServers.splice(0).map((server) => server.stop()));
  16. await Promise.all(tempDirs.splice(0).map((dir) => rm(dir, { force: true, recursive: true })));
  17. });
  18. describe("Upstream replay server", () => {
  19. it("SCT lifecycle resolves only structured successful tool results, including operation and fork boundary", async () => {
  20. const dir = await mkdtemp(join(tmpdir(), "zcode-app-lifecycle-replay-"));
  21. tempDirs.push(dir);
  22. const fixture = join(dir, "fixture.json");
  23. await writeFile(
  24. fixture,
  25. JSON.stringify({
  26. version: 1,
  27. fixtures: [
  28. {
  29. id: "lifecycle",
  30. match: { pathIncludes: "/messages" },
  31. response: {
  32. statusCode: 200,
  33. toolUse: {
  34. name: "ForkSession",
  35. input: {
  36. session: "{{appControlResult:toolu_sct04_create.session}}",
  37. sessionId: "{{appControlResult:toolu_sct04_create.session.sessionId}}",
  38. operation: "{{appControlResult:toolu_sct04_create.operation}}",
  39. commandId: "{{appControlResult:toolu_sct04_create.operation.commandId}}",
  40. atMessage: "{{appControlResult:toolu_sct04_page.messages.firstAssistant.id}}",
  41. cursor: "{{appControlResult:toolu_sct04_page.nextCursor}}",
  42. execution: "{{appControlResult:toolu_sct04_summary.summary.executionId}}",
  43. },
  44. },
  45. },
  46. },
  47. ],
  48. }),
  49. );
  50. const server = await startUpstreamReplayServer({
  51. artifactPath: join(dir, "artifact.json"),
  52. fixturePaths: [fixture],
  53. });
  54. activeServers.push(server);
  55. const session = {
  56. kind: "app",
  57. sourceServerId: "local",
  58. workspacePath: "/workspace",
  59. sessionId: "created",
  60. };
  61. const operation = { session, commandId: "real-command" };
  62. const blocks = [
  63. {
  64. type: "tool_result",
  65. tool_use_id: "toolu_sct04_create",
  66. content: JSON.stringify({ session, operation }),
  67. },
  68. {
  69. type: "tool_result",
  70. tool_use_id: "toolu_sct04_page",
  71. content: [
  72. {
  73. type: "text",
  74. text: JSON.stringify({
  75. messages: [
  76. { id: "user", role: "user", text: "E2E_SCT04_CREATE_TARGET" },
  77. { id: "internal", role: "user", text: "Available agent types" },
  78. { id: "assistant", role: "assistant", text: "SCT04_CREATE_DONE" },
  79. { id: "later-assistant", role: "assistant", text: "SCT04_SEND_DONE" },
  80. ],
  81. nextCursor: "assistant",
  82. }),
  83. },
  84. ],
  85. },
  86. {
  87. type: "tool_result",
  88. tool_use_id: "toolu_sct04_summary",
  89. content: JSON.stringify({ summary: { executionId: "real-execution" } }),
  90. },
  91. ];
  92. const request = (content: unknown) =>
  93. fetch(`${server.baseUrl}/messages`, {
  94. method: "POST",
  95. headers: { "content-type": "application/json" },
  96. // 工具调用简写只在流式请求返回 SSE;下面的断言读取 partial_json,必须声明 stream。
  97. body: JSON.stringify({ stream: true, messages: [{ role: "user", content }] }),
  98. });
  99. const response = await request(blocks);
  100. expect(response.status).toBe(200);
  101. const body = await response.text();
  102. const inputEvent = body.split("\n").find((line) => line.includes('"partial_json"'));
  103. expect(JSON.parse(JSON.parse(inputEvent!.slice("data: ".length)).delta.partial_json)).toEqual({
  104. session,
  105. sessionId: "created",
  106. operation,
  107. commandId: "real-command",
  108. atMessage: "assistant",
  109. cursor: "assistant",
  110. execution: "real-execution",
  111. });
  112. // 用户正文不能冒充工具回执,失败回执也不能成为下一步权威身份。
  113. expect((await request([{ type: "text", text: JSON.stringify(blocks) }])).status).toBe(500);
  114. expect((await request(blocks.map((block) => ({ ...block, is_error: true })))).status).toBe(500);
  115. expect(
  116. (
  117. await request(
  118. blocks.map((block) =>
  119. block.tool_use_id === "toolu_sct04_page"
  120. ? {
  121. ...block,
  122. content: JSON.stringify({
  123. messages: [{ id: "fake-assistant", role: "user", text: "SCT04_CREATE_DONE" }],
  124. nextCursor: "user",
  125. }),
  126. }
  127. : block,
  128. ),
  129. )
  130. ).status,
  131. ).toBe(500);
  132. });
  133. it.each([
  134. {
  135. marker: "E2E_SCT03",
  136. tool: "OpenSession",
  137. field: "session",
  138. token: "appControlTargetRef",
  139. },
  140. {
  141. marker: "E2E_SCT07",
  142. tool: "ListSessions",
  143. field: "project",
  144. token: "appControlTargetProjectRef",
  145. },
  146. ])(
  147. "$marker binds only the complete App reference returned by a real tool result",
  148. async ({ marker, tool, field, token }) => {
  149. const dir = await mkdtemp(join(tmpdir(), "zcode-app-navigation-replay-"));
  150. tempDirs.push(dir);
  151. const fixture = join(dir, "fixture.json");
  152. await writeFile(
  153. fixture,
  154. JSON.stringify({
  155. version: 1,
  156. fixtures: [
  157. {
  158. id: "open",
  159. match: { pathIncludes: "/messages" },
  160. response: {
  161. statusCode: 200,
  162. toolUse: { name: tool, input: { [field]: `{{${token}}}` } },
  163. },
  164. },
  165. ],
  166. }),
  167. );
  168. const server = await startUpstreamReplayServer({
  169. artifactPath: join(dir, "artifact.json"),
  170. fixturePaths: [fixture],
  171. });
  172. activeServers.push(server);
  173. const ref = {
  174. kind: "app",
  175. sourceServerId: "local",
  176. workspacePath: "/workspace",
  177. sessionId: "target",
  178. project: { kind: "app", sourceServerId: "local", projectId: "project" },
  179. };
  180. const request = (content: unknown[]) =>
  181. fetch(`${server.baseUrl}/messages`, {
  182. method: "POST",
  183. headers: { "content-type": "application/json" },
  184. body: JSON.stringify({
  185. stream: true,
  186. messages: [
  187. { role: "user", content: `${marker}_TARGET_SESSION_ID:target` },
  188. { role: "user", content },
  189. ],
  190. }),
  191. });
  192. const response = await request([
  193. {
  194. type: "tool_result",
  195. tool_use_id: "list",
  196. content: JSON.stringify({ sessions: [{ session: ref }] }),
  197. },
  198. ]);
  199. expect(response.status).toBe(200);
  200. const body = await response.text();
  201. expect(body).toContain("projectId");
  202. expect(body).not.toContain(`{{${token}}}`);
  203. const inputEvent = body.split("\n").find((line) => line.includes('"partial_json"'));
  204. const input = JSON.parse(JSON.parse(inputEvent!.slice("data: ".length)).delta.partial_json);
  205. expect(input).toEqual({ [field]: field === "project" ? ref.project : ref });
  206. const untrusted = await request([
  207. { type: "text", text: JSON.stringify({ sessions: [{ session: ref }] }) },
  208. ]);
  209. expect(untrusted.status).toBe(500);
  210. },
  211. );
  212. it("分阶段工具参数必须逐次释放,第一次释放不能越过第二个观察点", async () => {
  213. const dir = await mkdtemp(join(tmpdir(), "zcode-replay-stages-"));
  214. tempDirs.push(dir);
  215. const fixture = join(dir, "fixture.json");
  216. await writeFile(
  217. fixture,
  218. JSON.stringify({
  219. version: 1,
  220. fixtures: [
  221. {
  222. id: "stages",
  223. metadata: { timingPolicy: "controlled-stream" },
  224. match: { pathIncludes: "/messages" },
  225. response: {
  226. statusCode: 200,
  227. releaseAfterChunks: [1, 2],
  228. chunks: [
  229. { offsetMs: 0, text: "partial\n" },
  230. { offsetMs: 45000, text: "path-ready\n" },
  231. { offsetMs: 90000, text: "completed\n" },
  232. ],
  233. },
  234. },
  235. ],
  236. }),
  237. );
  238. const server = await startUpstreamReplayServer({
  239. artifactPath: join(dir, "artifact.json"),
  240. fixturePaths: [fixture],
  241. });
  242. activeServers.push(server);
  243. const response = await fetch(`${server.baseUrl}/messages`, {
  244. signal: AbortSignal.timeout(5000),
  245. });
  246. const reader = response.body!.getReader();
  247. for (const text of ["partial\n", "path-ready\n"]) {
  248. expect(new TextDecoder().decode((await reader.read()).value)).toBe(text);
  249. expect(await fetch(`${server.baseUrl}/__e2e__/gates`).then((r) => r.json())).toEqual([
  250. "stages",
  251. ]);
  252. expect(
  253. (await fetch(`${server.baseUrl}/__e2e__/release/stages`, { method: "POST" })).status,
  254. ).toBe(204);
  255. }
  256. expect(new TextDecoder().decode((await reader.read()).value)).toBe("completed\n");
  257. expect((await reader.read()).done).toBe(true);
  258. expect(
  259. (await fetch(`${server.baseUrl}/__e2e__/release/stages`, { method: "POST" })).status,
  260. ).toBe(409);
  261. });
  262. it("从最新真实 workflow-hole 通知绑定 run ID,缺失通知时拒绝伪造 FillWorkflowHole", async () => {
  263. const dir = await mkdtemp(join(tmpdir(), "zcode-workflow-hole-replay-"));
  264. tempDirs.push(dir);
  265. const fixture = join(dir, "fixture.json");
  266. await writeFile(
  267. fixture,
  268. JSON.stringify({
  269. version: 1,
  270. fixtures: [
  271. {
  272. id: "fill-hole",
  273. match: { pathIncludes: "/messages" },
  274. response: {
  275. statusCode: 200,
  276. toolUse: {
  277. name: "FillWorkflowHole",
  278. input: {
  279. run_id: "{{latestWorkflowRunId}}",
  280. hole_id: "hole#21b40fca",
  281. script: "return 1;",
  282. },
  283. },
  284. },
  285. },
  286. ],
  287. }),
  288. );
  289. const server = await startUpstreamReplayServer({
  290. artifactPath: join(dir, "artifact.json"),
  291. fixturePaths: [fixture],
  292. });
  293. activeServers.push(server);
  294. const request = (content: string) =>
  295. fetch(`${server.baseUrl}/messages`, {
  296. method: "POST",
  297. headers: { "content-type": "application/json" },
  298. body: JSON.stringify({ messages: [{ role: "user", content }] }),
  299. });
  300. const response = await request(
  301. "<workflow-hole><run-id>run-old</run-id></workflow-hole>\n<workflow-hole><run-id>run-current</run-id></workflow-hole>",
  302. );
  303. const body = await response.text();
  304. expect(response.status).toBe(200);
  305. expect(body).toContain("run-current");
  306. expect(body).not.toContain("run-old");
  307. expect(body).not.toContain("{{latestWorkflowRunId}}");
  308. const missing = await request("no workflow notification");
  309. expect(missing.status).toBe(500);
  310. expect(await missing.text()).toContain("Missing");
  311. });
  312. it("按请求的 stream 属性选择 SSE 或 JSON 响应格式", async () => {
  313. const dir = await mkdtemp(join(tmpdir(), "zcode-replay-response-format-"));
  314. tempDirs.push(dir);
  315. const fixture = join(dir, "fixture.json");
  316. await writeFile(
  317. fixture,
  318. JSON.stringify({
  319. version: 1,
  320. fixtures: [
  321. {
  322. id: "format-text",
  323. match: { bodyIncludes: ["FORMAT_PROBE_TEXT"], pathIncludes: "/messages" },
  324. response: { statusCode: 200, text: { id: "msg_format_text", text: "FORMAT_TEXT_OK" } },
  325. },
  326. {
  327. id: "format-tool",
  328. match: { bodyIncludes: ["FORMAT_PROBE_TOOL"], pathIncludes: "/messages" },
  329. response: {
  330. statusCode: 200,
  331. toolUse: { id: "toolu_format_tool", input: { value: 1 }, name: "Read" },
  332. },
  333. },
  334. ],
  335. }),
  336. );
  337. const server = await startUpstreamReplayServer({
  338. artifactPath: join(dir, "artifact.json"),
  339. fixturePaths: [fixture],
  340. });
  341. activeServers.push(server);
  342. const request = (content: string, stream?: true) =>
  343. fetch(`${server.baseUrl}/messages`, {
  344. body: JSON.stringify({
  345. ...(stream ? { stream } : {}),
  346. messages: [{ role: "user", content }],
  347. }),
  348. headers: { "content-type": "application/json" },
  349. method: "POST",
  350. signal: AbortSignal.timeout(5000),
  351. });
  352. const nonStreamText = await request("FORMAT_PROBE_TEXT");
  353. expect(nonStreamText.headers.get("content-type")).toContain("application/json");
  354. expect(await nonStreamText.json()).toMatchObject({
  355. id: "msg_format_text",
  356. type: "message",
  357. role: "assistant",
  358. content: [{ type: "text", text: "FORMAT_TEXT_OK" }],
  359. stop_reason: "end_turn",
  360. });
  361. const streamingText = await request("FORMAT_PROBE_TEXT", true);
  362. expect(streamingText.headers.get("content-type")).toContain("text/event-stream");
  363. const streamingBody = await streamingText.text();
  364. expect(streamingBody).toContain("event: message_start");
  365. expect(streamingBody).toContain("FORMAT_TEXT_OK");
  366. const nonStreamTool = await request("FORMAT_PROBE_TOOL");
  367. expect(nonStreamTool.headers.get("content-type")).toContain("application/json");
  368. expect(await nonStreamTool.json()).toMatchObject({
  369. type: "message",
  370. role: "assistant",
  371. content: [{ type: "tool_use", id: "toolu_format_tool", name: "Read", input: { value: 1 } }],
  372. stop_reason: "tool_use",
  373. });
  374. });
  375. it("受控流在释放前保持 running,释放后不再等待旧的 45 秒时间轴", async () => {
  376. const dir = await mkdtemp(join(tmpdir(), "zcode-replay-gate-"));
  377. tempDirs.push(dir);
  378. const fixture = join(dir, "fixture.json");
  379. await writeFile(
  380. fixture,
  381. JSON.stringify({
  382. version: 1,
  383. fixtures: [
  384. {
  385. id: "controlled",
  386. metadata: { timingPolicy: "controlled-stream" },
  387. match: { pathIncludes: "/messages" },
  388. response: {
  389. statusCode: 200,
  390. releaseAfterChunks: 1,
  391. headers: { "content-type": "text/event-stream" },
  392. chunks: [
  393. { offsetMs: 0, text: "running\n" },
  394. { offsetMs: 45000, text: "complete\n" },
  395. ],
  396. },
  397. },
  398. ],
  399. }),
  400. );
  401. const server = await startUpstreamReplayServer({
  402. artifactPath: join(dir, "artifact.json"),
  403. fixturePaths: [fixture],
  404. });
  405. activeServers.push(server);
  406. const response = await fetch(`${server.baseUrl}/messages`, {
  407. signal: AbortSignal.timeout(5000),
  408. });
  409. const reader = response.body!.getReader();
  410. expect(new TextDecoder().decode((await reader.read()).value)).toBe("running\n");
  411. expect(
  412. (await fetch(`${server.baseUrl}/__e2e__/release/unknown`, { method: "POST" })).status,
  413. ).toBe(409);
  414. const held = await fetch(`${server.baseUrl}/__e2e__/gates`).then((result) => result.json());
  415. expect(held).toEqual(["controlled"]);
  416. expect(
  417. (await fetch(`${server.baseUrl}/__e2e__/release/controlled`, { method: "POST" })).status,
  418. ).toBe(204);
  419. expect(new TextDecoder().decode((await reader.read()).value)).toBe("complete\n");
  420. expect((await reader.read()).done).toBe(true);
  421. expect(
  422. (await fetch(`${server.baseUrl}/__e2e__/release/controlled`, { method: "POST" })).status,
  423. ).toBe(409);
  424. // 第二个 runner 使用相同 fixture ID,也必须有独立的 gate 与请求台账。
  425. const other = await startUpstreamReplayServer({
  426. artifactPath: join(dir, "other.json"),
  427. fixturePaths: [fixture],
  428. });
  429. activeServers.push(other);
  430. const second = await fetch(`${other.baseUrl}/messages`, { signal: AbortSignal.timeout(5000) });
  431. const secondReader = second.body!.getReader();
  432. await secondReader.read();
  433. expect(
  434. (await fetch(`${server.baseUrl}/__e2e__/release/controlled`, { method: "POST" })).status,
  435. ).toBe(409);
  436. expect(await fetch(`${other.baseUrl}/__e2e__/gates`).then((value) => value.json())).toEqual([
  437. "controlled",
  438. ]);
  439. await fetch(`${other.baseUrl}/__e2e__/release/controlled`, { method: "POST" });
  440. expect(new TextDecoder().decode((await secondReader.read()).value)).toBe("complete\n");
  441. expect((await secondReader.read()).done).toBe(true);
  442. });
  443. it("closes the listener when the initial artifact write fails", async () => {
  444. const tempDir = await mkdtemp(join(tmpdir(), "zcode-upstream-start-failure-"));
  445. tempDirs.push(tempDir);
  446. const fixturePath = join(tempDir, "fixture.json");
  447. const artifactPath = join(tempDir, "artifact.json");
  448. const port = await reserveLoopbackPort();
  449. const initialWriteError = new Error("initial-artifact-write-failed");
  450. let artifactWriteCount = 0;
  451. await writeFile(fixturePath, JSON.stringify({ fixtures: [], version: 1 }, null, 2), "utf-8");
  452. await expect(
  453. startUpstreamReplayServer({
  454. artifactPath,
  455. artifactWriter: async () => {
  456. artifactWriteCount += 1;
  457. throw initialWriteError;
  458. },
  459. fixturePaths: [fixturePath],
  460. port,
  461. }),
  462. ).rejects.toBe(initialWriteError);
  463. expect(artifactWriteCount).toBe(1);
  464. await expectLoopbackPortAvailable(port);
  465. });
  466. // 回归:Windows 上 reader 持有 capture 读句柄时 rename 会持续 EPERM。capture 是全量快照、
  467. // 后写覆盖前写,中途一次快照写不成不丢数据;过去这里把模型请求打成 500,台账留下一条
  468. // fixtureId=null 的记录(BG46 在 60MB capture 下必现)。现在请求照常回放,收尾写入补齐。
  469. it("keeps replaying when a mid-request artifact snapshot hits a file lock conflict", async () => {
  470. let locked = true;
  471. let lockedWrites = 0;
  472. const handlerWarning = vi.spyOn(console, "warn").mockImplementation(() => undefined);
  473. try {
  474. const { artifactPath, server } = await startFixtureServer("end", "events", {
  475. artifactWriter: async (path, value) => {
  476. if (locked && (value as E2ENetworkCaptureArtifact).records.length > 0) {
  477. lockedWrites += 1;
  478. throw Object.assign(new Error("EPERM: operation not permitted, rename"), {
  479. code: "EPERM",
  480. });
  481. }
  482. await writeFile(path, JSON.stringify(value, null, 2), "utf-8");
  483. },
  484. });
  485. const response = await fetch(`${server.baseUrl}/messages`, {
  486. body: JSON.stringify({ messages: [{ role: "user", content: "SSE_CLOSE_MODE_PROBE" }] }),
  487. headers: { "content-type": "application/json" },
  488. method: "POST",
  489. });
  490. expect(response.status).toBe(200);
  491. await expect(response.text()).resolves.toBe(SSE_EVENT_TEXT);
  492. expect(lockedWrites).toBeGreaterThan(0);
  493. locked = false;
  494. await server.stop();
  495. activeServers.splice(activeServers.indexOf(server), 1);
  496. const artifact = JSON.parse(
  497. await readFile(artifactPath, "utf-8"),
  498. ) as E2ENetworkCaptureArtifact;
  499. expect(artifact.records).toHaveLength(1);
  500. expect(artifact.records[0]?.replay?.fixtureId).toBe("sse-close-mode-end");
  501. expect(artifact.records[0]?.status).toBe("complete");
  502. } finally {
  503. handlerWarning.mockRestore();
  504. }
  505. });
  506. // 回归(CR-01):请求内所有快照都遇到占用冲突时,旧实现只告警,不保留待写状态;
  507. // 冲突解除后没有新请求、也没调用 stop(),capture 永远停在旧快照,轮询文件的
  508. // waitForUpstreamRequest 只能超时。写入循环必须自己补写到最新快照。
  509. it("backfills the latest snapshot after a file lock clears without a new request or stop", async () => {
  510. let locked = true;
  511. const handlerWarning = vi.spyOn(console, "warn").mockImplementation(() => undefined);
  512. try {
  513. const { artifactPath, server } = await startFixtureServer("end", "events", {
  514. artifactWriter: async (path, value) => {
  515. if (locked && (value as E2ENetworkCaptureArtifact).records.length > 0) {
  516. throw Object.assign(new Error("EPERM: operation not permitted, rename"), {
  517. code: "EPERM",
  518. });
  519. }
  520. await writeFile(path, JSON.stringify(value, null, 2), "utf-8");
  521. },
  522. });
  523. const response = await fetch(`${server.baseUrl}/messages`, {
  524. body: JSON.stringify({ messages: [{ role: "user", content: "SSE_CLOSE_MODE_PROBE" }] }),
  525. headers: { "content-type": "application/json" },
  526. method: "POST",
  527. });
  528. expect(response.status).toBe(200);
  529. await expect(response.text()).resolves.toBe(SSE_EVENT_TEXT);
  530. locked = false;
  531. await vi.waitFor(
  532. async () => {
  533. const artifact = JSON.parse(
  534. await readFile(artifactPath, "utf-8"),
  535. ) as E2ENetworkCaptureArtifact;
  536. expect(artifact.records).toHaveLength(1);
  537. expect(artifact.records[0]?.replay?.fixtureId).toBe("sse-close-mode-end");
  538. expect(artifact.records[0]?.status).toBe("complete");
  539. },
  540. { interval: 50, timeout: 5000 },
  541. );
  542. } finally {
  543. handlerWarning.mockRestore();
  544. }
  545. });
  546. // 回归(CR-01):合并写入与冲突重试不能让较旧的快照覆盖较新的快照。
  547. it("never lands an older snapshot after a newer one under concurrent updates and lock conflicts", async () => {
  548. const landed: E2ENetworkCaptureArtifact[] = [];
  549. let attempts = 0;
  550. const handlerWarning = vi.spyOn(console, "warn").mockImplementation(() => undefined);
  551. const progress = (artifact: E2ENetworkCaptureArtifact) =>
  552. artifact.records.length * 10 +
  553. artifact.records.filter((record) => record.status === "complete").length;
  554. try {
  555. const { artifactPath, server } = await startFixtureServer("end", "events", {
  556. artifactWriter: async (path, value) => {
  557. attempts += 1;
  558. // 真实 writer 一进入就序列化;records 之后还会被原地修改,这里同样先拍下快照。
  559. const snapshot = structuredClone(value) as E2ENetworkCaptureArtifact;
  560. // 写入耗时不一,并让部分写入撞上占用冲突。
  561. await new Promise((resolveDelay) => setTimeout(resolveDelay, (attempts % 3) * 15));
  562. if (attempts % 4 === 0) {
  563. throw Object.assign(new Error("EBUSY: resource busy, rename"), { code: "EBUSY" });
  564. }
  565. landed.push(snapshot);
  566. await writeFile(path, JSON.stringify(snapshot, null, 2), "utf-8");
  567. },
  568. });
  569. const send = () =>
  570. fetch(`${server.baseUrl}/messages`, {
  571. body: JSON.stringify({
  572. messages: [{ role: "user", content: "SSE_CLOSE_MODE_PROBE" }],
  573. }),
  574. headers: { "content-type": "application/json" },
  575. method: "POST",
  576. }).then((response) => response.text());
  577. await Promise.all([send(), send(), send()]);
  578. await vi.waitFor(
  579. async () => {
  580. const artifact = JSON.parse(
  581. await readFile(artifactPath, "utf-8"),
  582. ) as E2ENetworkCaptureArtifact;
  583. expect(artifact.records).toHaveLength(3);
  584. expect(artifact.records.every((record) => record.status === "complete")).toBe(true);
  585. },
  586. { interval: 50, timeout: 5000 },
  587. );
  588. for (let index = 1; index < landed.length; index += 1) {
  589. expect(progress(landed[index]!)).toBeGreaterThanOrEqual(progress(landed[index - 1]!));
  590. }
  591. } finally {
  592. handlerWarning.mockRestore();
  593. }
  594. });
  595. it.runIf(process.platform === "win32")(
  596. "replays normally while a reader holds the artifact open on Windows",
  597. async () => {
  598. const { artifactPath, server } = await startFixtureServer("end");
  599. const reader = await open(artifactPath, "r");
  600. const handlerWarning = vi.spyOn(console, "warn").mockImplementation(() => undefined);
  601. try {
  602. const response = await fetch(`${server.baseUrl}/messages`, {
  603. body: JSON.stringify({
  604. messages: [{ role: "user", content: "SSE_CLOSE_MODE_PROBE" }],
  605. }),
  606. headers: { "content-type": "application/json" },
  607. method: "POST",
  608. signal: AbortSignal.timeout(5000),
  609. });
  610. expect(response.status).toBe(200);
  611. await expect(response.text()).resolves.toBe(SSE_EVENT_TEXT);
  612. } finally {
  613. await reader.close();
  614. handlerWarning.mockRestore();
  615. }
  616. },
  617. );
  618. it("expands static fixture variables before matching and replaying", async () => {
  619. const tempDir = await mkdtemp(join(tmpdir(), "zcode-upstream-replay-vars-"));
  620. tempDirs.push(tempDir);
  621. const fixturePath = join(tempDir, "fixture.json");
  622. const artifactPath = join(tempDir, "artifact.json");
  623. const runtimeRoot = "C:/e2e-home/ZCodeProject/.zcode-e2e";
  624. await writeFile(
  625. fixturePath,
  626. JSON.stringify(
  627. {
  628. fixtures: [
  629. {
  630. id: "static-runtime-path",
  631. match: {
  632. bodyIncludes: ["Read {{e2eRuntimeRoot}}/shared/readonly.txt"],
  633. method: "POST",
  634. pathIncludes: "/messages",
  635. },
  636. response: {
  637. statusCode: 200,
  638. toolUse: {
  639. id: "toolu_static_runtime_path",
  640. input: {
  641. file_path: "{{e2eRuntimeRoot}}/shared/readonly.txt",
  642. },
  643. name: "Read",
  644. },
  645. },
  646. },
  647. ],
  648. version: 1,
  649. },
  650. null,
  651. 2,
  652. ),
  653. );
  654. const server = await startUpstreamReplayServer({
  655. artifactPath,
  656. fixturePaths: [fixturePath],
  657. fixtureVariables: { e2eRuntimeRoot: runtimeRoot },
  658. });
  659. activeServers.push(server);
  660. const response = await fetch(`${server.baseUrl}/messages`, {
  661. body: JSON.stringify({
  662. stream: true,
  663. messages: [
  664. {
  665. content: `Read ${runtimeRoot}/shared/readonly.txt`,
  666. role: "user",
  667. },
  668. ],
  669. }),
  670. headers: { "content-type": "application/json" },
  671. method: "POST",
  672. signal: AbortSignal.timeout(5000),
  673. });
  674. const responseText = await response.text();
  675. expect(response.status).toBe(200);
  676. expect(responseText).toContain(`\\"file_path\\":\\"${runtimeRoot}/shared/readonly.txt\\"`);
  677. expect(responseText).not.toContain("{{e2eRuntimeRoot}}");
  678. });
  679. it.each([
  680. {
  681. output:
  682. "Command running in background with ID: bash_first. Output is being written to: /tmp/first.log.\nCommand running in background with ID: bash_last. Output is being written to: /tmp/last.log.",
  683. expected: "bash_last",
  684. },
  685. { output: "agentId: agent_other", expected: "{{latestBashTaskId}}" },
  686. ])(
  687. "resolves Bash task IDs from actual launch results: $expected",
  688. async ({ output, expected }) => {
  689. const tempDir = await mkdtemp(join(tmpdir(), "zcode-bash-task-replay-"));
  690. tempDirs.push(tempDir);
  691. const fixturePath = join(tempDir, "fixture.json");
  692. await writeFile(
  693. fixturePath,
  694. JSON.stringify({
  695. version: 1,
  696. fixtures: [
  697. {
  698. id: "bash-task-output",
  699. match: { method: "POST", pathIncludes: "/messages" },
  700. response: {
  701. statusCode: 200,
  702. toolUse: {
  703. id: "toolu_bash_task_output",
  704. name: "TaskOutput",
  705. input: { task_id: "{{latestBashTaskId}}", block: false },
  706. },
  707. },
  708. },
  709. ],
  710. }),
  711. );
  712. const server = await startUpstreamReplayServer({
  713. fixturePaths: [fixturePath],
  714. artifactPath: join(tempDir, "artifact.json"),
  715. });
  716. activeServers.push(server);
  717. const response = await fetch(`${server.baseUrl}/messages`, {
  718. method: "POST",
  719. headers: { "content-type": "application/json" },
  720. body: JSON.stringify({
  721. stream: true,
  722. messages: [
  723. {
  724. role: "user",
  725. content: [
  726. {
  727. type: "tool_result",
  728. tool_use_id: "toolu_bash_launch",
  729. content: output,
  730. },
  731. ],
  732. },
  733. ],
  734. }),
  735. signal: AbortSignal.timeout(5000),
  736. });
  737. expect(response.status).toBe(200);
  738. expect(await response.text()).toContain(`\\"task_id\\":\\"${expected}\\"`);
  739. },
  740. );
  741. it("records normal SSE EOF as complete end", async () => {
  742. const { artifactPath, server } = await startFixtureServer("end");
  743. const response = await fetch(`${server.baseUrl}/messages`, {
  744. body: JSON.stringify({
  745. messages: [{ role: "user", content: "SSE_CLOSE_MODE_PROBE" }],
  746. }),
  747. headers: { "content-type": "application/json" },
  748. method: "POST",
  749. signal: AbortSignal.timeout(5000),
  750. });
  751. await expect(response.text()).resolves.toBe(SSE_EVENT_TEXT);
  752. await server.stop();
  753. activeServers.pop();
  754. const record = (await readArtifact(artifactPath)).records[0];
  755. expect(record?.status).toBe("complete");
  756. expect(record?.replay).toEqual({
  757. closeMode: "end",
  758. fixtureId: "sse-close-mode-end",
  759. });
  760. expect(record?.responseEvents).toHaveLength(1);
  761. });
  762. it.each(["events", "chunks", "body"] as const)(
  763. "destroys %s SSE responses when closeMode is destroy",
  764. async (format) => {
  765. const { artifactPath, server } = await startFixtureServer("destroy", format);
  766. let fetchFailed = false;
  767. try {
  768. const response = await fetch(`${server.baseUrl}/messages`, {
  769. body: JSON.stringify({
  770. messages: [{ role: "user", content: "SSE_CLOSE_MODE_PROBE" }],
  771. }),
  772. headers: { "content-type": "application/json" },
  773. method: "POST",
  774. signal: AbortSignal.timeout(5000),
  775. });
  776. await response.text();
  777. } catch {
  778. fetchFailed = true;
  779. }
  780. await server.stop();
  781. activeServers.pop();
  782. const record = (await readArtifact(artifactPath)).records[0];
  783. expect(fetchFailed).toBe(true);
  784. expect(record?.status).toBe("error");
  785. expect(record?.error).toBe("Replay fixture destroyed SSE response stream");
  786. expect(record?.replay).toEqual({
  787. closeMode: "destroy",
  788. fixtureId: "sse-close-mode-destroy",
  789. });
  790. if (format === "events") expect(record?.responseEvents).toHaveLength(1);
  791. if (format === "chunks") expect(record?.responseChunkTimeline).toHaveLength(1);
  792. expect(record?.responseBodyBytes).toBe(Buffer.byteLength(SSE_EVENT_TEXT));
  793. },
  794. );
  795. it("injects a loopback Browser fixture URL without trailing punctuation", async () => {
  796. const server = await startBrowserVariableFixtureServer();
  797. const response = await fetch(`${server.baseUrl}/messages`, {
  798. body: JSON.stringify({
  799. messages: [
  800. {
  801. role: "user",
  802. content:
  803. "BROWSER_VARIABLE_PROBE E2E_BROWSER_FIXTURE_URL:http://127.0.0.1:43123/basic),",
  804. },
  805. ],
  806. }),
  807. headers: { "content-type": "application/json" },
  808. method: "POST",
  809. });
  810. expect(response.status).toBe(200);
  811. const body = await response.text();
  812. expect(body).toContain("http://127.0.0.1:43123/basic");
  813. expect(body).not.toContain("{{browserFixtureUrl}}");
  814. expect(body).not.toContain("/basic),");
  815. });
  816. it("injects the latest automation id from a CronList tool result", async () => {
  817. const server = await startAutomationVariableFixtureServer();
  818. const response = await fetch(`${server.baseUrl}/messages`, {
  819. body: JSON.stringify({
  820. messages: [
  821. { role: "user", content: "AUTOMATION_VARIABLE_PROBE" },
  822. {
  823. role: "user",
  824. content: [
  825. {
  826. type: "tool_result",
  827. tool_use_id: "toolu_cron_list",
  828. content: JSON.stringify({
  829. automations: [{ automationId: "automation-runtime-123" }],
  830. }),
  831. },
  832. ],
  833. },
  834. ],
  835. }),
  836. headers: { "content-type": "application/json" },
  837. method: "POST",
  838. });
  839. expect(response.status).toBe(200);
  840. const body = await response.text();
  841. expect(body).toContain("automation-runtime-123");
  842. expect(body).not.toContain("{{latestAutomationId}}");
  843. });
  844. it("injects Browser stable tab ids from the latest tool result", async () => {
  845. const server = await startBrowserTabVariableFixtureServer();
  846. const response = await fetch(`${server.baseUrl}/messages`, {
  847. body: JSON.stringify({
  848. messages: [
  849. { role: "user", content: "BROWSER_TAB_VARIABLE_PROBE" },
  850. {
  851. role: "user",
  852. content: [
  853. {
  854. type: "tool_result",
  855. tool_use_id: "toolu_browser_tabs_stale",
  856. content:
  857. '=> {"e2eBrowserTabId":"tab-single-stale","e2eBrowserTabAId":"tab-a-stale","e2eBrowserTabBId":"tab-b-stale"}\n\nStructured content:\n',
  858. },
  859. ],
  860. },
  861. {
  862. role: "user",
  863. content: [
  864. {
  865. type: "tool_result",
  866. tool_use_id: "toolu_browser_tabs_list",
  867. content:
  868. '=> {\n "e2eBrowserTabAId": "tab-a-runtime",\n "e2eBrowserTabBId": "tab-b-runtime",\n "e2eBrowserTabId": "tab-single-runtime"\n}\n\nStructured content:\n',
  869. },
  870. ],
  871. },
  872. ],
  873. }),
  874. headers: { "content-type": "application/json" },
  875. method: "POST",
  876. });
  877. expect(response.status).toBe(200);
  878. const body = await response.text();
  879. expect(body).toContain("tab-single-runtime");
  880. expect(body).toContain("tab-a-runtime");
  881. expect(body).toContain("tab-b-runtime");
  882. expect(body).not.toContain("{{latestBrowserTabId}}");
  883. expect(body).not.toContain("{{latestBrowserTabAId}}");
  884. expect(body).not.toContain("{{latestBrowserTabBId}}");
  885. expect(body).not.toContain("stale");
  886. });
  887. it("fails closed when the Browser fixture URL marker is not loopback", async () => {
  888. const server = await startBrowserVariableFixtureServer();
  889. const response = await fetch(`${server.baseUrl}/messages`, {
  890. body: JSON.stringify({
  891. messages: [
  892. {
  893. role: "user",
  894. content: "BROWSER_VARIABLE_PROBE E2E_BROWSER_FIXTURE_URL:https://example.com/basic",
  895. },
  896. ],
  897. }),
  898. headers: { "content-type": "application/json" },
  899. method: "POST",
  900. });
  901. expect(response.status).toBe(500);
  902. await expect(response.text()).resolves.toContain(
  903. "Missing E2E_BROWSER_FIXTURE_URL replay variable",
  904. );
  905. });
  906. it("contains a missing Browser fixture variable artifact failure in the request handler", async () => {
  907. let artifactWriteCount = 0;
  908. let failedMissingVariableArtifact = false;
  909. const unhandledRejections: unknown[] = [];
  910. const handlerWarning = vi.spyOn(console, "warn").mockImplementation(() => undefined);
  911. const onUnhandledRejection = (reason: unknown) => {
  912. unhandledRejections.push(reason);
  913. };
  914. process.on("unhandledRejection", onUnhandledRejection);
  915. try {
  916. const server = await startBrowserVariableFixtureServer({
  917. artifactWriter: async (path, value) => {
  918. artifactWriteCount += 1;
  919. const artifact = value as E2ENetworkCaptureArtifact;
  920. const containsMissingVariableResponse = artifact.records.some(
  921. (record) =>
  922. record.status === "complete" &&
  923. record.statusCode === 500 &&
  924. record.responseTextPreview?.includes(
  925. "Missing E2E_BROWSER_FIXTURE_URL replay variable",
  926. ),
  927. );
  928. if (containsMissingVariableResponse && !failedMissingVariableArtifact) {
  929. failedMissingVariableArtifact = true;
  930. throw new Error("missing-variable-artifact-write-failed");
  931. }
  932. await writeFile(path, JSON.stringify(value, null, 2), "utf-8");
  933. },
  934. });
  935. const response = await fetch(`${server.baseUrl}/messages`, {
  936. body: JSON.stringify({
  937. messages: [{ role: "user", content: "BROWSER_VARIABLE_PROBE" }],
  938. }),
  939. headers: { "content-type": "application/json" },
  940. method: "POST",
  941. });
  942. expect(response.status).toBe(500);
  943. await expect(response.text()).resolves.toContain(
  944. "Missing E2E_BROWSER_FIXTURE_URL replay variable",
  945. );
  946. await new Promise<void>((resolveImmediate) => setImmediate(resolveImmediate));
  947. expect(artifactWriteCount).toBeGreaterThanOrEqual(4);
  948. expect(failedMissingVariableArtifact).toBe(true);
  949. expect(unhandledRejections).toEqual([]);
  950. expect(handlerWarning).toHaveBeenCalledWith(
  951. expect.stringContaining("missing-variable-artifact-write-failed"),
  952. );
  953. } finally {
  954. process.off("unhandledRejection", onUnhandledRejection);
  955. handlerWarning.mockRestore();
  956. }
  957. });
  958. it("matches the latest tool_result instead of a success marker inside tool code", async () => {
  959. const server = await startLatestToolResultFixtureServer();
  960. const request = (toolResult: string) =>
  961. fetch(`${server.baseUrl}/messages`, {
  962. body: JSON.stringify({
  963. messages: [
  964. {
  965. role: "assistant",
  966. content: [
  967. {
  968. type: "tool_use",
  969. input: { code: "return 'E2E_TOOL_RESULT_OK'" },
  970. },
  971. ],
  972. },
  973. {
  974. role: "user",
  975. content: [
  976. {
  977. type: "tool_result",
  978. content: toolResult,
  979. },
  980. ],
  981. },
  982. ],
  983. }),
  984. headers: { "content-type": "application/json" },
  985. method: "POST",
  986. });
  987. const failedResult = await request("E2E_TOOL_RESULT_FAILED");
  988. expect(failedResult.status).toBe(500);
  989. await expect(failedResult.text()).resolves.toContain("Missing Upstream e2e fixture");
  990. const successfulResult = await request("E2E_TOOL_RESULT_OK");
  991. expect(successfulResult.status).toBe(200);
  992. await expect(successfulResult.text()).resolves.toContain("tool result matched");
  993. });
  994. it("matches the background prompt when task-notification only appears in tool schema", async () => {
  995. const server = await startBackgroundFixtureServer();
  996. const response = await requestBackgroundDirectPrompt(
  997. server,
  998. "E2E_BACKGROUND_DIRECT_USER_PROMPT: send immediately. Payload: E2E_BACKGROUND_DIRECT_USER_PROMPT_PAYLOAD.",
  999. );
  1000. expect(response.status).toBe(200);
  1001. await expect(response.text()).resolves.toContain("background-direct-user-prompt-received-ok");
  1002. });
  1003. it("rejects the background prompt when task-notification is in the latest user message", async () => {
  1004. const server = await startBackgroundFixtureServer();
  1005. const response = await requestBackgroundDirectPrompt(
  1006. server,
  1007. "<task-notification>completed</task-notification> E2E_BACKGROUND_DIRECT_USER_PROMPT_PAYLOAD",
  1008. );
  1009. expect(response.status).toBe(500);
  1010. await expect(response.text()).resolves.toContain("Missing Upstream e2e fixture");
  1011. });
  1012. });
  1013. async function startFixtureServer(
  1014. closeMode: "end" | "destroy",
  1015. format: "events" | "chunks" | "body" = "events",
  1016. options: {
  1017. artifactWriter?: Parameters<typeof startUpstreamReplayServer>[0]["artifactWriter"];
  1018. } = {},
  1019. ) {
  1020. const tempDir = await mkdtemp(join(tmpdir(), "zcode-upstream-replay-"));
  1021. tempDirs.push(tempDir);
  1022. const fixturePath = join(tempDir, "fixture.json");
  1023. const artifactPath = join(tempDir, "artifact.json");
  1024. await writeFile(
  1025. fixturePath,
  1026. JSON.stringify(
  1027. {
  1028. fixtures: [
  1029. {
  1030. id: `sse-close-mode-${closeMode}`,
  1031. match: {
  1032. bodyIncludes: ["SSE_CLOSE_MODE_PROBE"],
  1033. method: "POST",
  1034. pathIncludes: "/messages",
  1035. },
  1036. response: {
  1037. closeMode,
  1038. ...(format === "body"
  1039. ? { body: SSE_EVENT_TEXT }
  1040. : {
  1041. [format]: [
  1042. {
  1043. byteLength: Buffer.byteLength(SSE_EVENT_TEXT, "utf-8"),
  1044. offsetMs: 0,
  1045. sequence: 0,
  1046. text: SSE_EVENT_TEXT,
  1047. },
  1048. ],
  1049. }),
  1050. headers: { "content-type": "text/event-stream; charset=utf-8" },
  1051. statusCode: 200,
  1052. statusMessage: "OK",
  1053. },
  1054. },
  1055. ],
  1056. version: 1,
  1057. },
  1058. null,
  1059. 2,
  1060. ),
  1061. );
  1062. const server = await startUpstreamReplayServer({
  1063. artifactPath,
  1064. fixturePaths: [fixturePath],
  1065. ...(options.artifactWriter ? { artifactWriter: options.artifactWriter } : {}),
  1066. });
  1067. activeServers.push(server);
  1068. return { artifactPath, server };
  1069. }
  1070. async function startBrowserVariableFixtureServer(
  1071. options: {
  1072. artifactWriter?: Parameters<typeof startUpstreamReplayServer>[0]["artifactWriter"];
  1073. } = {},
  1074. ) {
  1075. const tempDir = await mkdtemp(join(tmpdir(), "zcode-upstream-browser-variable-"));
  1076. tempDirs.push(tempDir);
  1077. const fixturePath = join(tempDir, "fixture.json");
  1078. const artifactPath = join(tempDir, "artifact.json");
  1079. await writeFile(
  1080. fixturePath,
  1081. JSON.stringify(
  1082. {
  1083. fixtures: [
  1084. {
  1085. id: "browser-variable",
  1086. match: {
  1087. bodyIncludes: ["BROWSER_VARIABLE_PROBE"],
  1088. method: "POST",
  1089. pathIncludes: "/messages",
  1090. },
  1091. response: {
  1092. statusCode: 200,
  1093. toolUse: {
  1094. id: "toolu_browser_variable",
  1095. input: {
  1096. code: "await tab.goto('{{browserFixtureUrl}}')",
  1097. title: "打开测试页面",
  1098. },
  1099. name: "mcp__node_repl__js",
  1100. },
  1101. },
  1102. },
  1103. ],
  1104. version: 1,
  1105. },
  1106. null,
  1107. 2,
  1108. ),
  1109. );
  1110. const server = await startUpstreamReplayServer({
  1111. artifactPath,
  1112. fixturePaths: [fixturePath],
  1113. ...(options.artifactWriter ? { artifactWriter: options.artifactWriter } : {}),
  1114. });
  1115. activeServers.push(server);
  1116. return server;
  1117. }
  1118. async function startAutomationVariableFixtureServer() {
  1119. const tempDir = await mkdtemp(join(tmpdir(), "zcode-upstream-automation-variable-"));
  1120. tempDirs.push(tempDir);
  1121. const fixturePath = join(tempDir, "fixture.json");
  1122. const artifactPath = join(tempDir, "artifact.json");
  1123. await writeFile(
  1124. fixturePath,
  1125. JSON.stringify(
  1126. {
  1127. fixtures: [
  1128. {
  1129. id: "automation-variable",
  1130. match: {
  1131. bodyIncludes: ["AUTOMATION_VARIABLE_PROBE"],
  1132. method: "POST",
  1133. pathIncludes: "/messages",
  1134. },
  1135. response: {
  1136. statusCode: 200,
  1137. toolUse: {
  1138. id: "toolu_automation_variable",
  1139. input: { id: "{{latestAutomationId}}", title: "updated" },
  1140. name: "CronUpdate",
  1141. },
  1142. },
  1143. },
  1144. ],
  1145. version: 1,
  1146. },
  1147. null,
  1148. 2,
  1149. ),
  1150. );
  1151. const server = await startUpstreamReplayServer({
  1152. artifactPath,
  1153. fixturePaths: [fixturePath],
  1154. });
  1155. activeServers.push(server);
  1156. return server;
  1157. }
  1158. async function startBrowserTabVariableFixtureServer() {
  1159. const tempDir = await mkdtemp(join(tmpdir(), "zcode-upstream-browser-tab-variable-"));
  1160. tempDirs.push(tempDir);
  1161. const fixturePath = join(tempDir, "fixture.json");
  1162. const artifactPath = join(tempDir, "artifact.json");
  1163. await writeFile(
  1164. fixturePath,
  1165. JSON.stringify(
  1166. {
  1167. fixtures: [
  1168. {
  1169. id: "browser-tab-variable",
  1170. match: {
  1171. bodyIncludes: ["BROWSER_TAB_VARIABLE_PROBE"],
  1172. method: "POST",
  1173. pathIncludes: "/messages",
  1174. },
  1175. response: {
  1176. statusCode: 200,
  1177. toolUse: {
  1178. id: "toolu_browser_tab_variable",
  1179. input: {
  1180. code: [
  1181. "const browser = await agent.browsers.get('iab');",
  1182. "const tab = await browser.tabs.get('{{latestBrowserTabId}}');",
  1183. "const tabA = await browser.tabs.get('{{latestBrowserTabAId}}');",
  1184. "const tabB = await browser.tabs.get('{{latestBrowserTabBId}}');",
  1185. ].join("\n"),
  1186. title: "恢复 Browser tab",
  1187. },
  1188. name: "mcp__node_repl__js",
  1189. },
  1190. },
  1191. },
  1192. ],
  1193. version: 1,
  1194. },
  1195. null,
  1196. 2,
  1197. ),
  1198. );
  1199. const server = await startUpstreamReplayServer({
  1200. artifactPath,
  1201. fixturePaths: [fixturePath],
  1202. });
  1203. activeServers.push(server);
  1204. return server;
  1205. }
  1206. async function startLatestToolResultFixtureServer() {
  1207. const tempDir = await mkdtemp(join(tmpdir(), "zcode-upstream-tool-result-"));
  1208. tempDirs.push(tempDir);
  1209. const fixturePath = join(tempDir, "fixture.json");
  1210. const artifactPath = join(tempDir, "artifact.json");
  1211. await writeFile(
  1212. fixturePath,
  1213. JSON.stringify(
  1214. {
  1215. fixtures: [
  1216. {
  1217. id: "latest-tool-result",
  1218. match: {
  1219. lastUserMessageIncludes: ["E2E_TOOL_RESULT_OK"],
  1220. method: "POST",
  1221. pathIncludes: "/messages",
  1222. },
  1223. response: { statusCode: 200, text: "tool result matched" },
  1224. },
  1225. ],
  1226. version: 1,
  1227. },
  1228. null,
  1229. 2,
  1230. ),
  1231. );
  1232. const server = await startUpstreamReplayServer({
  1233. artifactPath,
  1234. fixturePaths: [fixturePath],
  1235. });
  1236. activeServers.push(server);
  1237. return server;
  1238. }
  1239. async function startBackgroundFixtureServer() {
  1240. const tempDir = await mkdtemp(join(tmpdir(), "zcode-upstream-background-fixture-"));
  1241. tempDirs.push(tempDir);
  1242. const artifactPath = join(tempDir, "artifact.json");
  1243. const fixturePath = join(
  1244. import.meta.dirname,
  1245. "e2e/fixtures/upstream/conversation-session/conversation-session-background.json",
  1246. );
  1247. const server = await startUpstreamReplayServer({
  1248. artifactPath,
  1249. fixturePaths: [fixturePath],
  1250. });
  1251. activeServers.push(server);
  1252. return server;
  1253. }
  1254. function requestBackgroundDirectPrompt(server: UpstreamReplayServer, latestUserText: string) {
  1255. // Bug 根因:TaskOutput 的 provider schema 自身包含 notification 标签;
  1256. // 是否已注入通知必须只看最新 user message,不能扫描整个请求体。
  1257. return fetch(`${server.baseUrl}/messages`, {
  1258. body: JSON.stringify({
  1259. messages: [{ role: "user", content: latestUserText }],
  1260. tools: [
  1261. {
  1262. description: "Background tasks receive a <task-notification> when the task completes.",
  1263. name: "TaskOutput",
  1264. },
  1265. ],
  1266. }),
  1267. headers: { "content-type": "application/json" },
  1268. method: "POST",
  1269. });
  1270. }
  1271. async function readArtifact(path: string): Promise<E2ENetworkCaptureArtifact> {
  1272. return JSON.parse(await readFile(path, "utf-8")) as E2ENetworkCaptureArtifact;
  1273. }
  1274. async function reserveLoopbackPort(): Promise<number> {
  1275. const server = createNetServer();
  1276. await listenOnLoopback(server, 0);
  1277. const address = server.address();
  1278. if (!address || typeof address === "string") {
  1279. await closeNetServer(server);
  1280. throw new Error("Temporary port server did not expose an address");
  1281. }
  1282. await closeNetServer(server);
  1283. return address.port;
  1284. }
  1285. async function expectLoopbackPortAvailable(port: number): Promise<void> {
  1286. const server = createNetServer();
  1287. try {
  1288. await listenOnLoopback(server, port);
  1289. } finally {
  1290. if (server.listening) {
  1291. await closeNetServer(server);
  1292. }
  1293. }
  1294. }
  1295. function listenOnLoopback(server: NetServer, port: number): Promise<void> {
  1296. return new Promise((resolveListen, rejectListen) => {
  1297. const onError = (error: Error) => {
  1298. rejectListen(error);
  1299. };
  1300. server.once("error", onError);
  1301. server.listen(port, "127.0.0.1", () => {
  1302. server.off("error", onError);
  1303. resolveListen();
  1304. });
  1305. });
  1306. }
  1307. function closeNetServer(server: NetServer): Promise<void> {
  1308. return new Promise((resolveClose, rejectClose) => {
  1309. server.close((error) => {
  1310. if (error) {
  1311. rejectClose(error);
  1312. return;
  1313. }
  1314. resolveClose();
  1315. });
  1316. });
  1317. }