upstreamReplayServer.test.ts 49 KB

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