upstreamReplayServer.test.ts 35 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049
  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("分阶段工具参数必须逐次释放,第一次释放不能越过第二个观察点", async () => {
  20. const dir = await mkdtemp(join(tmpdir(), "zcode-replay-stages-"));
  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: "stages",
  30. metadata: { timingPolicy: "controlled-stream" },
  31. match: { pathIncludes: "/messages" },
  32. response: {
  33. statusCode: 200,
  34. releaseAfterChunks: [1, 2],
  35. chunks: [
  36. { offsetMs: 0, text: "partial\n" },
  37. { offsetMs: 45000, text: "path-ready\n" },
  38. { offsetMs: 90000, text: "completed\n" },
  39. ],
  40. },
  41. },
  42. ],
  43. }),
  44. );
  45. const server = await startUpstreamReplayServer({
  46. artifactPath: join(dir, "artifact.json"),
  47. fixturePaths: [fixture],
  48. });
  49. activeServers.push(server);
  50. const response = await fetch(`${server.baseUrl}/messages`, {
  51. signal: AbortSignal.timeout(5000),
  52. });
  53. const reader = response.body!.getReader();
  54. for (const text of ["partial\n", "path-ready\n"]) {
  55. expect(new TextDecoder().decode((await reader.read()).value)).toBe(text);
  56. expect(await fetch(`${server.baseUrl}/__e2e__/gates`).then((r) => r.json())).toEqual([
  57. "stages",
  58. ]);
  59. expect(
  60. (await fetch(`${server.baseUrl}/__e2e__/release/stages`, { method: "POST" })).status,
  61. ).toBe(204);
  62. }
  63. expect(new TextDecoder().decode((await reader.read()).value)).toBe("completed\n");
  64. expect((await reader.read()).done).toBe(true);
  65. expect(
  66. (await fetch(`${server.baseUrl}/__e2e__/release/stages`, { method: "POST" })).status,
  67. ).toBe(409);
  68. });
  69. it("从最新真实 workflow-hole 通知绑定 run ID,缺失通知时拒绝伪造 FillWorkflowHole", async () => {
  70. const dir = await mkdtemp(join(tmpdir(), "zcode-workflow-hole-replay-"));
  71. tempDirs.push(dir);
  72. const fixture = join(dir, "fixture.json");
  73. await writeFile(
  74. fixture,
  75. JSON.stringify({
  76. version: 1,
  77. fixtures: [
  78. {
  79. id: "fill-hole",
  80. match: { pathIncludes: "/messages" },
  81. response: {
  82. statusCode: 200,
  83. toolUse: {
  84. name: "FillWorkflowHole",
  85. input: {
  86. run_id: "{{latestWorkflowRunId}}",
  87. hole_id: "hole#21b40fca",
  88. script: "return 1;",
  89. },
  90. },
  91. },
  92. },
  93. ],
  94. }),
  95. );
  96. const server = await startUpstreamReplayServer({
  97. artifactPath: join(dir, "artifact.json"),
  98. fixturePaths: [fixture],
  99. });
  100. activeServers.push(server);
  101. const request = (content: string) =>
  102. fetch(`${server.baseUrl}/messages`, {
  103. method: "POST",
  104. headers: { "content-type": "application/json" },
  105. body: JSON.stringify({ messages: [{ role: "user", content }] }),
  106. });
  107. const response = await request(
  108. "<workflow-hole><run-id>run-old</run-id></workflow-hole>\n<workflow-hole><run-id>run-current</run-id></workflow-hole>",
  109. );
  110. const body = await response.text();
  111. expect(response.status).toBe(200);
  112. expect(body).toContain("run-current");
  113. expect(body).not.toContain("run-old");
  114. expect(body).not.toContain("{{latestWorkflowRunId}}");
  115. const missing = await request("no workflow notification");
  116. expect(missing.status).toBe(500);
  117. expect(await missing.text()).toContain("Missing");
  118. });
  119. it("按请求的 stream 属性选择 SSE 或 JSON 响应格式", async () => {
  120. const dir = await mkdtemp(join(tmpdir(), "zcode-replay-response-format-"));
  121. tempDirs.push(dir);
  122. const fixture = join(dir, "fixture.json");
  123. await writeFile(
  124. fixture,
  125. JSON.stringify({
  126. version: 1,
  127. fixtures: [
  128. {
  129. id: "format-text",
  130. match: { bodyIncludes: ["FORMAT_PROBE_TEXT"], pathIncludes: "/messages" },
  131. response: { statusCode: 200, text: { id: "msg_format_text", text: "FORMAT_TEXT_OK" } },
  132. },
  133. {
  134. id: "format-tool",
  135. match: { bodyIncludes: ["FORMAT_PROBE_TOOL"], pathIncludes: "/messages" },
  136. response: {
  137. statusCode: 200,
  138. toolUse: { id: "toolu_format_tool", input: { value: 1 }, name: "Read" },
  139. },
  140. },
  141. ],
  142. }),
  143. );
  144. const server = await startUpstreamReplayServer({
  145. artifactPath: join(dir, "artifact.json"),
  146. fixturePaths: [fixture],
  147. });
  148. activeServers.push(server);
  149. const request = (content: string, stream?: true) =>
  150. fetch(`${server.baseUrl}/messages`, {
  151. body: JSON.stringify({
  152. ...(stream ? { stream } : {}),
  153. messages: [{ role: "user", content }],
  154. }),
  155. headers: { "content-type": "application/json" },
  156. method: "POST",
  157. signal: AbortSignal.timeout(5000),
  158. });
  159. const nonStreamText = await request("FORMAT_PROBE_TEXT");
  160. expect(nonStreamText.headers.get("content-type")).toContain("application/json");
  161. expect(await nonStreamText.json()).toMatchObject({
  162. id: "msg_format_text",
  163. type: "message",
  164. role: "assistant",
  165. content: [{ type: "text", text: "FORMAT_TEXT_OK" }],
  166. stop_reason: "end_turn",
  167. });
  168. const streamingText = await request("FORMAT_PROBE_TEXT", true);
  169. expect(streamingText.headers.get("content-type")).toContain("text/event-stream");
  170. const streamingBody = await streamingText.text();
  171. expect(streamingBody).toContain("event: message_start");
  172. expect(streamingBody).toContain("FORMAT_TEXT_OK");
  173. const nonStreamTool = await request("FORMAT_PROBE_TOOL");
  174. expect(nonStreamTool.headers.get("content-type")).toContain("application/json");
  175. expect(await nonStreamTool.json()).toMatchObject({
  176. type: "message",
  177. role: "assistant",
  178. content: [{ type: "tool_use", id: "toolu_format_tool", name: "Read", input: { value: 1 } }],
  179. stop_reason: "tool_use",
  180. });
  181. });
  182. it("受控流在释放前保持 running,释放后不再等待旧的 45 秒时间轴", async () => {
  183. const dir = await mkdtemp(join(tmpdir(), "zcode-replay-gate-"));
  184. tempDirs.push(dir);
  185. const fixture = join(dir, "fixture.json");
  186. await writeFile(
  187. fixture,
  188. JSON.stringify({
  189. version: 1,
  190. fixtures: [
  191. {
  192. id: "controlled",
  193. metadata: { timingPolicy: "controlled-stream" },
  194. match: { pathIncludes: "/messages" },
  195. response: {
  196. statusCode: 200,
  197. releaseAfterChunks: 1,
  198. headers: { "content-type": "text/event-stream" },
  199. chunks: [
  200. { offsetMs: 0, text: "running\n" },
  201. { offsetMs: 45000, text: "complete\n" },
  202. ],
  203. },
  204. },
  205. ],
  206. }),
  207. );
  208. const server = await startUpstreamReplayServer({
  209. artifactPath: join(dir, "artifact.json"),
  210. fixturePaths: [fixture],
  211. });
  212. activeServers.push(server);
  213. const response = await fetch(`${server.baseUrl}/messages`, {
  214. signal: AbortSignal.timeout(5000),
  215. });
  216. const reader = response.body!.getReader();
  217. expect(new TextDecoder().decode((await reader.read()).value)).toBe("running\n");
  218. expect(
  219. (await fetch(`${server.baseUrl}/__e2e__/release/unknown`, { method: "POST" })).status,
  220. ).toBe(409);
  221. const held = await fetch(`${server.baseUrl}/__e2e__/gates`).then((result) => result.json());
  222. expect(held).toEqual(["controlled"]);
  223. expect(
  224. (await fetch(`${server.baseUrl}/__e2e__/release/controlled`, { method: "POST" })).status,
  225. ).toBe(204);
  226. expect(new TextDecoder().decode((await reader.read()).value)).toBe("complete\n");
  227. expect((await reader.read()).done).toBe(true);
  228. expect(
  229. (await fetch(`${server.baseUrl}/__e2e__/release/controlled`, { method: "POST" })).status,
  230. ).toBe(409);
  231. // 第二个 runner 使用相同 fixture ID,也必须有独立的 gate 与请求台账。
  232. const other = await startUpstreamReplayServer({
  233. artifactPath: join(dir, "other.json"),
  234. fixturePaths: [fixture],
  235. });
  236. activeServers.push(other);
  237. const second = await fetch(`${other.baseUrl}/messages`, { signal: AbortSignal.timeout(5000) });
  238. const secondReader = second.body!.getReader();
  239. await secondReader.read();
  240. expect(
  241. (await fetch(`${server.baseUrl}/__e2e__/release/controlled`, { method: "POST" })).status,
  242. ).toBe(409);
  243. expect(await fetch(`${other.baseUrl}/__e2e__/gates`).then((value) => value.json())).toEqual([
  244. "controlled",
  245. ]);
  246. await fetch(`${other.baseUrl}/__e2e__/release/controlled`, { method: "POST" });
  247. expect(new TextDecoder().decode((await secondReader.read()).value)).toBe("complete\n");
  248. expect((await secondReader.read()).done).toBe(true);
  249. });
  250. it("closes the listener when the initial artifact write fails", async () => {
  251. const tempDir = await mkdtemp(join(tmpdir(), "zcode-upstream-start-failure-"));
  252. tempDirs.push(tempDir);
  253. const fixturePath = join(tempDir, "fixture.json");
  254. const artifactPath = join(tempDir, "artifact.json");
  255. const port = await reserveLoopbackPort();
  256. const initialWriteError = new Error("initial-artifact-write-failed");
  257. let artifactWriteCount = 0;
  258. await writeFile(fixturePath, JSON.stringify({ fixtures: [], version: 1 }, null, 2), "utf-8");
  259. await expect(
  260. startUpstreamReplayServer({
  261. artifactPath,
  262. artifactWriter: async () => {
  263. artifactWriteCount += 1;
  264. throw initialWriteError;
  265. },
  266. fixturePaths: [fixturePath],
  267. port,
  268. }),
  269. ).rejects.toBe(initialWriteError);
  270. expect(artifactWriteCount).toBe(1);
  271. await expectLoopbackPortAvailable(port);
  272. });
  273. it.runIf(process.platform === "win32")(
  274. "ends the provider response when a persistently locked artifact cannot be replaced",
  275. async () => {
  276. const { artifactPath, server } = await startFixtureServer("end");
  277. const reader = await open(artifactPath, "r");
  278. try {
  279. const response = await fetch(`${server.baseUrl}/messages`, {
  280. body: JSON.stringify({
  281. messages: [{ role: "user", content: "SSE_CLOSE_MODE_PROBE" }],
  282. }),
  283. headers: { "content-type": "application/json" },
  284. method: "POST",
  285. signal: AbortSignal.timeout(3000),
  286. });
  287. expect(response.status).toBe(500);
  288. await expect(response.text()).resolves.toContain("Upstream E2E replay handler failed");
  289. } finally {
  290. await reader.close();
  291. }
  292. },
  293. );
  294. it("expands static fixture variables before matching and replaying", async () => {
  295. const tempDir = await mkdtemp(join(tmpdir(), "zcode-upstream-replay-vars-"));
  296. tempDirs.push(tempDir);
  297. const fixturePath = join(tempDir, "fixture.json");
  298. const artifactPath = join(tempDir, "artifact.json");
  299. const runtimeRoot = "C:/e2e-home/ZCodeProject/.zcode-e2e";
  300. await writeFile(
  301. fixturePath,
  302. JSON.stringify(
  303. {
  304. fixtures: [
  305. {
  306. id: "static-runtime-path",
  307. match: {
  308. bodyIncludes: ["Read {{e2eRuntimeRoot}}/shared/readonly.txt"],
  309. method: "POST",
  310. pathIncludes: "/messages",
  311. },
  312. response: {
  313. statusCode: 200,
  314. toolUse: {
  315. id: "toolu_static_runtime_path",
  316. input: {
  317. file_path: "{{e2eRuntimeRoot}}/shared/readonly.txt",
  318. },
  319. name: "Read",
  320. },
  321. },
  322. },
  323. ],
  324. version: 1,
  325. },
  326. null,
  327. 2,
  328. ),
  329. );
  330. const server = await startUpstreamReplayServer({
  331. artifactPath,
  332. fixturePaths: [fixturePath],
  333. fixtureVariables: { e2eRuntimeRoot: runtimeRoot },
  334. });
  335. activeServers.push(server);
  336. const response = await fetch(`${server.baseUrl}/messages`, {
  337. body: JSON.stringify({
  338. stream: true,
  339. messages: [
  340. {
  341. content: `Read ${runtimeRoot}/shared/readonly.txt`,
  342. role: "user",
  343. },
  344. ],
  345. }),
  346. headers: { "content-type": "application/json" },
  347. method: "POST",
  348. signal: AbortSignal.timeout(5000),
  349. });
  350. const responseText = await response.text();
  351. expect(response.status).toBe(200);
  352. expect(responseText).toContain(`\\"file_path\\":\\"${runtimeRoot}/shared/readonly.txt\\"`);
  353. expect(responseText).not.toContain("{{e2eRuntimeRoot}}");
  354. });
  355. it.each([
  356. {
  357. output:
  358. "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.",
  359. expected: "bash_last",
  360. },
  361. { output: "agentId: agent_other", expected: "{{latestBashTaskId}}" },
  362. ])(
  363. "resolves Bash task IDs from actual launch results: $expected",
  364. async ({ output, expected }) => {
  365. const tempDir = await mkdtemp(join(tmpdir(), "zcode-bash-task-replay-"));
  366. tempDirs.push(tempDir);
  367. const fixturePath = join(tempDir, "fixture.json");
  368. await writeFile(
  369. fixturePath,
  370. JSON.stringify({
  371. version: 1,
  372. fixtures: [
  373. {
  374. id: "bash-task-output",
  375. match: { method: "POST", pathIncludes: "/messages" },
  376. response: {
  377. statusCode: 200,
  378. toolUse: {
  379. id: "toolu_bash_task_output",
  380. name: "TaskOutput",
  381. input: { task_id: "{{latestBashTaskId}}", block: false },
  382. },
  383. },
  384. },
  385. ],
  386. }),
  387. );
  388. const server = await startUpstreamReplayServer({
  389. fixturePaths: [fixturePath],
  390. artifactPath: join(tempDir, "artifact.json"),
  391. });
  392. activeServers.push(server);
  393. const response = await fetch(`${server.baseUrl}/messages`, {
  394. method: "POST",
  395. headers: { "content-type": "application/json" },
  396. body: JSON.stringify({
  397. stream: true,
  398. messages: [
  399. {
  400. role: "user",
  401. content: [
  402. {
  403. type: "tool_result",
  404. tool_use_id: "toolu_bash_launch",
  405. content: output,
  406. },
  407. ],
  408. },
  409. ],
  410. }),
  411. signal: AbortSignal.timeout(5000),
  412. });
  413. expect(response.status).toBe(200);
  414. expect(await response.text()).toContain(`\\"task_id\\":\\"${expected}\\"`);
  415. },
  416. );
  417. it("records normal SSE EOF as complete end", async () => {
  418. const { artifactPath, server } = await startFixtureServer("end");
  419. const response = await fetch(`${server.baseUrl}/messages`, {
  420. body: JSON.stringify({
  421. messages: [{ role: "user", content: "SSE_CLOSE_MODE_PROBE" }],
  422. }),
  423. headers: { "content-type": "application/json" },
  424. method: "POST",
  425. signal: AbortSignal.timeout(5000),
  426. });
  427. await expect(response.text()).resolves.toBe(SSE_EVENT_TEXT);
  428. await server.stop();
  429. activeServers.pop();
  430. const record = (await readArtifact(artifactPath)).records[0];
  431. expect(record?.status).toBe("complete");
  432. expect(record?.replay).toEqual({
  433. closeMode: "end",
  434. fixtureId: "sse-close-mode-end",
  435. });
  436. expect(record?.responseEvents).toHaveLength(1);
  437. });
  438. it.each(["events", "chunks", "body"] as const)(
  439. "destroys %s SSE responses when closeMode is destroy",
  440. async (format) => {
  441. const { artifactPath, server } = await startFixtureServer("destroy", format);
  442. let fetchFailed = false;
  443. try {
  444. const response = await fetch(`${server.baseUrl}/messages`, {
  445. body: JSON.stringify({
  446. messages: [{ role: "user", content: "SSE_CLOSE_MODE_PROBE" }],
  447. }),
  448. headers: { "content-type": "application/json" },
  449. method: "POST",
  450. signal: AbortSignal.timeout(5000),
  451. });
  452. await response.text();
  453. } catch {
  454. fetchFailed = true;
  455. }
  456. await server.stop();
  457. activeServers.pop();
  458. const record = (await readArtifact(artifactPath)).records[0];
  459. expect(fetchFailed).toBe(true);
  460. expect(record?.status).toBe("error");
  461. expect(record?.error).toBe("Replay fixture destroyed SSE response stream");
  462. expect(record?.replay).toEqual({
  463. closeMode: "destroy",
  464. fixtureId: "sse-close-mode-destroy",
  465. });
  466. if (format === "events") expect(record?.responseEvents).toHaveLength(1);
  467. if (format === "chunks") expect(record?.responseChunkTimeline).toHaveLength(1);
  468. expect(record?.responseBodyBytes).toBe(Buffer.byteLength(SSE_EVENT_TEXT));
  469. },
  470. );
  471. it("injects a loopback Browser fixture URL without trailing punctuation", async () => {
  472. const server = await startBrowserVariableFixtureServer();
  473. const response = await fetch(`${server.baseUrl}/messages`, {
  474. body: JSON.stringify({
  475. messages: [
  476. {
  477. role: "user",
  478. content:
  479. "BROWSER_VARIABLE_PROBE E2E_BROWSER_FIXTURE_URL:http://127.0.0.1:43123/basic),",
  480. },
  481. ],
  482. }),
  483. headers: { "content-type": "application/json" },
  484. method: "POST",
  485. });
  486. expect(response.status).toBe(200);
  487. const body = await response.text();
  488. expect(body).toContain("http://127.0.0.1:43123/basic");
  489. expect(body).not.toContain("{{browserFixtureUrl}}");
  490. expect(body).not.toContain("/basic),");
  491. });
  492. it("injects the latest automation id from a CronList tool result", async () => {
  493. const server = await startAutomationVariableFixtureServer();
  494. const response = await fetch(`${server.baseUrl}/messages`, {
  495. body: JSON.stringify({
  496. messages: [
  497. { role: "user", content: "AUTOMATION_VARIABLE_PROBE" },
  498. {
  499. role: "user",
  500. content: [
  501. {
  502. type: "tool_result",
  503. tool_use_id: "toolu_cron_list",
  504. content: JSON.stringify({
  505. automations: [{ automationId: "automation-runtime-123" }],
  506. }),
  507. },
  508. ],
  509. },
  510. ],
  511. }),
  512. headers: { "content-type": "application/json" },
  513. method: "POST",
  514. });
  515. expect(response.status).toBe(200);
  516. const body = await response.text();
  517. expect(body).toContain("automation-runtime-123");
  518. expect(body).not.toContain("{{latestAutomationId}}");
  519. });
  520. it("injects Browser stable tab ids from the latest tool result", async () => {
  521. const server = await startBrowserTabVariableFixtureServer();
  522. const response = await fetch(`${server.baseUrl}/messages`, {
  523. body: JSON.stringify({
  524. messages: [
  525. { role: "user", content: "BROWSER_TAB_VARIABLE_PROBE" },
  526. {
  527. role: "user",
  528. content: [
  529. {
  530. type: "tool_result",
  531. tool_use_id: "toolu_browser_tabs_stale",
  532. content:
  533. '=> {"e2eBrowserTabId":"tab-single-stale","e2eBrowserTabAId":"tab-a-stale","e2eBrowserTabBId":"tab-b-stale"}\n\nStructured content:\n',
  534. },
  535. ],
  536. },
  537. {
  538. role: "user",
  539. content: [
  540. {
  541. type: "tool_result",
  542. tool_use_id: "toolu_browser_tabs_list",
  543. content:
  544. '=> {\n "e2eBrowserTabAId": "tab-a-runtime",\n "e2eBrowserTabBId": "tab-b-runtime",\n "e2eBrowserTabId": "tab-single-runtime"\n}\n\nStructured content:\n',
  545. },
  546. ],
  547. },
  548. ],
  549. }),
  550. headers: { "content-type": "application/json" },
  551. method: "POST",
  552. });
  553. expect(response.status).toBe(200);
  554. const body = await response.text();
  555. expect(body).toContain("tab-single-runtime");
  556. expect(body).toContain("tab-a-runtime");
  557. expect(body).toContain("tab-b-runtime");
  558. expect(body).not.toContain("{{latestBrowserTabId}}");
  559. expect(body).not.toContain("{{latestBrowserTabAId}}");
  560. expect(body).not.toContain("{{latestBrowserTabBId}}");
  561. expect(body).not.toContain("stale");
  562. });
  563. it("fails closed when the Browser fixture URL marker is not loopback", async () => {
  564. const server = await startBrowserVariableFixtureServer();
  565. const response = await fetch(`${server.baseUrl}/messages`, {
  566. body: JSON.stringify({
  567. messages: [
  568. {
  569. role: "user",
  570. content: "BROWSER_VARIABLE_PROBE E2E_BROWSER_FIXTURE_URL:https://example.com/basic",
  571. },
  572. ],
  573. }),
  574. headers: { "content-type": "application/json" },
  575. method: "POST",
  576. });
  577. expect(response.status).toBe(500);
  578. await expect(response.text()).resolves.toContain(
  579. "Missing E2E_BROWSER_FIXTURE_URL replay variable",
  580. );
  581. });
  582. it("contains a missing Browser fixture variable artifact failure in the request handler", async () => {
  583. let artifactWriteCount = 0;
  584. let failedMissingVariableArtifact = false;
  585. const unhandledRejections: unknown[] = [];
  586. const handlerWarning = vi.spyOn(console, "warn").mockImplementation(() => undefined);
  587. const onUnhandledRejection = (reason: unknown) => {
  588. unhandledRejections.push(reason);
  589. };
  590. process.on("unhandledRejection", onUnhandledRejection);
  591. try {
  592. const server = await startBrowserVariableFixtureServer({
  593. artifactWriter: async (path, value) => {
  594. artifactWriteCount += 1;
  595. const artifact = value as E2ENetworkCaptureArtifact;
  596. const containsMissingVariableResponse = artifact.records.some(
  597. (record) =>
  598. record.status === "complete" &&
  599. record.statusCode === 500 &&
  600. record.responseTextPreview?.includes(
  601. "Missing E2E_BROWSER_FIXTURE_URL replay variable",
  602. ),
  603. );
  604. if (containsMissingVariableResponse && !failedMissingVariableArtifact) {
  605. failedMissingVariableArtifact = true;
  606. throw new Error("missing-variable-artifact-write-failed");
  607. }
  608. await writeFile(path, JSON.stringify(value, null, 2), "utf-8");
  609. },
  610. });
  611. const response = await fetch(`${server.baseUrl}/messages`, {
  612. body: JSON.stringify({
  613. messages: [{ role: "user", content: "BROWSER_VARIABLE_PROBE" }],
  614. }),
  615. headers: { "content-type": "application/json" },
  616. method: "POST",
  617. });
  618. expect(response.status).toBe(500);
  619. await expect(response.text()).resolves.toContain(
  620. "Missing E2E_BROWSER_FIXTURE_URL replay variable",
  621. );
  622. await new Promise<void>((resolveImmediate) => setImmediate(resolveImmediate));
  623. expect(artifactWriteCount).toBeGreaterThanOrEqual(4);
  624. expect(failedMissingVariableArtifact).toBe(true);
  625. expect(unhandledRejections).toEqual([]);
  626. expect(handlerWarning).toHaveBeenCalledWith(
  627. expect.stringContaining("missing-variable-artifact-write-failed"),
  628. );
  629. } finally {
  630. process.off("unhandledRejection", onUnhandledRejection);
  631. handlerWarning.mockRestore();
  632. }
  633. });
  634. it("matches the latest tool_result instead of a success marker inside tool code", async () => {
  635. const server = await startLatestToolResultFixtureServer();
  636. const request = (toolResult: string) =>
  637. fetch(`${server.baseUrl}/messages`, {
  638. body: JSON.stringify({
  639. messages: [
  640. {
  641. role: "assistant",
  642. content: [
  643. {
  644. type: "tool_use",
  645. input: { code: "return 'E2E_TOOL_RESULT_OK'" },
  646. },
  647. ],
  648. },
  649. {
  650. role: "user",
  651. content: [
  652. {
  653. type: "tool_result",
  654. content: toolResult,
  655. },
  656. ],
  657. },
  658. ],
  659. }),
  660. headers: { "content-type": "application/json" },
  661. method: "POST",
  662. });
  663. const failedResult = await request("E2E_TOOL_RESULT_FAILED");
  664. expect(failedResult.status).toBe(500);
  665. await expect(failedResult.text()).resolves.toContain("Missing Upstream e2e fixture");
  666. const successfulResult = await request("E2E_TOOL_RESULT_OK");
  667. expect(successfulResult.status).toBe(200);
  668. await expect(successfulResult.text()).resolves.toContain("tool result matched");
  669. });
  670. it("matches the background prompt when task-notification only appears in tool schema", async () => {
  671. const server = await startBackgroundFixtureServer();
  672. const response = await requestBackgroundDirectPrompt(
  673. server,
  674. "E2E_BACKGROUND_DIRECT_USER_PROMPT: send immediately. Payload: E2E_BACKGROUND_DIRECT_USER_PROMPT_PAYLOAD.",
  675. );
  676. expect(response.status).toBe(200);
  677. await expect(response.text()).resolves.toContain("background-direct-user-prompt-received-ok");
  678. });
  679. it("rejects the background prompt when task-notification is in the latest user message", async () => {
  680. const server = await startBackgroundFixtureServer();
  681. const response = await requestBackgroundDirectPrompt(
  682. server,
  683. "<task-notification>completed</task-notification> E2E_BACKGROUND_DIRECT_USER_PROMPT_PAYLOAD",
  684. );
  685. expect(response.status).toBe(500);
  686. await expect(response.text()).resolves.toContain("Missing Upstream e2e fixture");
  687. });
  688. });
  689. async function startFixtureServer(
  690. closeMode: "end" | "destroy",
  691. format: "events" | "chunks" | "body" = "events",
  692. ) {
  693. const tempDir = await mkdtemp(join(tmpdir(), "zcode-upstream-replay-"));
  694. tempDirs.push(tempDir);
  695. const fixturePath = join(tempDir, "fixture.json");
  696. const artifactPath = join(tempDir, "artifact.json");
  697. await writeFile(
  698. fixturePath,
  699. JSON.stringify(
  700. {
  701. fixtures: [
  702. {
  703. id: `sse-close-mode-${closeMode}`,
  704. match: {
  705. bodyIncludes: ["SSE_CLOSE_MODE_PROBE"],
  706. method: "POST",
  707. pathIncludes: "/messages",
  708. },
  709. response: {
  710. closeMode,
  711. ...(format === "body"
  712. ? { body: SSE_EVENT_TEXT }
  713. : {
  714. [format]: [
  715. {
  716. byteLength: Buffer.byteLength(SSE_EVENT_TEXT, "utf-8"),
  717. offsetMs: 0,
  718. sequence: 0,
  719. text: SSE_EVENT_TEXT,
  720. },
  721. ],
  722. }),
  723. headers: { "content-type": "text/event-stream; charset=utf-8" },
  724. statusCode: 200,
  725. statusMessage: "OK",
  726. },
  727. },
  728. ],
  729. version: 1,
  730. },
  731. null,
  732. 2,
  733. ),
  734. );
  735. const server = await startUpstreamReplayServer({
  736. artifactPath,
  737. fixturePaths: [fixturePath],
  738. });
  739. activeServers.push(server);
  740. return { artifactPath, server };
  741. }
  742. async function startBrowserVariableFixtureServer(
  743. options: {
  744. artifactWriter?: Parameters<typeof startUpstreamReplayServer>[0]["artifactWriter"];
  745. } = {},
  746. ) {
  747. const tempDir = await mkdtemp(join(tmpdir(), "zcode-upstream-browser-variable-"));
  748. tempDirs.push(tempDir);
  749. const fixturePath = join(tempDir, "fixture.json");
  750. const artifactPath = join(tempDir, "artifact.json");
  751. await writeFile(
  752. fixturePath,
  753. JSON.stringify(
  754. {
  755. fixtures: [
  756. {
  757. id: "browser-variable",
  758. match: {
  759. bodyIncludes: ["BROWSER_VARIABLE_PROBE"],
  760. method: "POST",
  761. pathIncludes: "/messages",
  762. },
  763. response: {
  764. statusCode: 200,
  765. toolUse: {
  766. id: "toolu_browser_variable",
  767. input: {
  768. code: "await tab.goto('{{browserFixtureUrl}}')",
  769. title: "打开测试页面",
  770. },
  771. name: "mcp__node_repl__js",
  772. },
  773. },
  774. },
  775. ],
  776. version: 1,
  777. },
  778. null,
  779. 2,
  780. ),
  781. );
  782. const server = await startUpstreamReplayServer({
  783. artifactPath,
  784. fixturePaths: [fixturePath],
  785. ...(options.artifactWriter ? { artifactWriter: options.artifactWriter } : {}),
  786. });
  787. activeServers.push(server);
  788. return server;
  789. }
  790. async function startAutomationVariableFixtureServer() {
  791. const tempDir = await mkdtemp(join(tmpdir(), "zcode-upstream-automation-variable-"));
  792. tempDirs.push(tempDir);
  793. const fixturePath = join(tempDir, "fixture.json");
  794. const artifactPath = join(tempDir, "artifact.json");
  795. await writeFile(
  796. fixturePath,
  797. JSON.stringify(
  798. {
  799. fixtures: [
  800. {
  801. id: "automation-variable",
  802. match: {
  803. bodyIncludes: ["AUTOMATION_VARIABLE_PROBE"],
  804. method: "POST",
  805. pathIncludes: "/messages",
  806. },
  807. response: {
  808. statusCode: 200,
  809. toolUse: {
  810. id: "toolu_automation_variable",
  811. input: { id: "{{latestAutomationId}}", title: "updated" },
  812. name: "CronUpdate",
  813. },
  814. },
  815. },
  816. ],
  817. version: 1,
  818. },
  819. null,
  820. 2,
  821. ),
  822. );
  823. const server = await startUpstreamReplayServer({
  824. artifactPath,
  825. fixturePaths: [fixturePath],
  826. });
  827. activeServers.push(server);
  828. return server;
  829. }
  830. async function startBrowserTabVariableFixtureServer() {
  831. const tempDir = await mkdtemp(join(tmpdir(), "zcode-upstream-browser-tab-variable-"));
  832. tempDirs.push(tempDir);
  833. const fixturePath = join(tempDir, "fixture.json");
  834. const artifactPath = join(tempDir, "artifact.json");
  835. await writeFile(
  836. fixturePath,
  837. JSON.stringify(
  838. {
  839. fixtures: [
  840. {
  841. id: "browser-tab-variable",
  842. match: {
  843. bodyIncludes: ["BROWSER_TAB_VARIABLE_PROBE"],
  844. method: "POST",
  845. pathIncludes: "/messages",
  846. },
  847. response: {
  848. statusCode: 200,
  849. toolUse: {
  850. id: "toolu_browser_tab_variable",
  851. input: {
  852. code: [
  853. "const browser = await agent.browsers.get('iab');",
  854. "const tab = await browser.tabs.get('{{latestBrowserTabId}}');",
  855. "const tabA = await browser.tabs.get('{{latestBrowserTabAId}}');",
  856. "const tabB = await browser.tabs.get('{{latestBrowserTabBId}}');",
  857. ].join("\n"),
  858. title: "恢复 Browser tab",
  859. },
  860. name: "mcp__node_repl__js",
  861. },
  862. },
  863. },
  864. ],
  865. version: 1,
  866. },
  867. null,
  868. 2,
  869. ),
  870. );
  871. const server = await startUpstreamReplayServer({
  872. artifactPath,
  873. fixturePaths: [fixturePath],
  874. });
  875. activeServers.push(server);
  876. return server;
  877. }
  878. async function startLatestToolResultFixtureServer() {
  879. const tempDir = await mkdtemp(join(tmpdir(), "zcode-upstream-tool-result-"));
  880. tempDirs.push(tempDir);
  881. const fixturePath = join(tempDir, "fixture.json");
  882. const artifactPath = join(tempDir, "artifact.json");
  883. await writeFile(
  884. fixturePath,
  885. JSON.stringify(
  886. {
  887. fixtures: [
  888. {
  889. id: "latest-tool-result",
  890. match: {
  891. lastUserMessageIncludes: ["E2E_TOOL_RESULT_OK"],
  892. method: "POST",
  893. pathIncludes: "/messages",
  894. },
  895. response: { statusCode: 200, text: "tool result matched" },
  896. },
  897. ],
  898. version: 1,
  899. },
  900. null,
  901. 2,
  902. ),
  903. );
  904. const server = await startUpstreamReplayServer({
  905. artifactPath,
  906. fixturePaths: [fixturePath],
  907. });
  908. activeServers.push(server);
  909. return server;
  910. }
  911. async function startBackgroundFixtureServer() {
  912. const tempDir = await mkdtemp(join(tmpdir(), "zcode-upstream-background-fixture-"));
  913. tempDirs.push(tempDir);
  914. const artifactPath = join(tempDir, "artifact.json");
  915. const fixturePath = join(
  916. import.meta.dirname,
  917. "e2e/fixtures/upstream/conversation-session/conversation-session-background.json",
  918. );
  919. const server = await startUpstreamReplayServer({
  920. artifactPath,
  921. fixturePaths: [fixturePath],
  922. });
  923. activeServers.push(server);
  924. return server;
  925. }
  926. function requestBackgroundDirectPrompt(server: UpstreamReplayServer, latestUserText: string) {
  927. // Bug 根因:TaskOutput 的 provider schema 自身包含 notification 标签;
  928. // 是否已注入通知必须只看最新 user message,不能扫描整个请求体。
  929. return fetch(`${server.baseUrl}/messages`, {
  930. body: JSON.stringify({
  931. messages: [{ role: "user", content: latestUserText }],
  932. tools: [
  933. {
  934. description: "Background tasks receive a <task-notification> when the task completes.",
  935. name: "TaskOutput",
  936. },
  937. ],
  938. }),
  939. headers: { "content-type": "application/json" },
  940. method: "POST",
  941. });
  942. }
  943. async function readArtifact(path: string): Promise<E2ENetworkCaptureArtifact> {
  944. return JSON.parse(await readFile(path, "utf-8")) as E2ENetworkCaptureArtifact;
  945. }
  946. async function reserveLoopbackPort(): Promise<number> {
  947. const server = createNetServer();
  948. await listenOnLoopback(server, 0);
  949. const address = server.address();
  950. if (!address || typeof address === "string") {
  951. await closeNetServer(server);
  952. throw new Error("Temporary port server did not expose an address");
  953. }
  954. await closeNetServer(server);
  955. return address.port;
  956. }
  957. async function expectLoopbackPortAvailable(port: number): Promise<void> {
  958. const server = createNetServer();
  959. try {
  960. await listenOnLoopback(server, port);
  961. } finally {
  962. if (server.listening) {
  963. await closeNetServer(server);
  964. }
  965. }
  966. }
  967. function listenOnLoopback(server: NetServer, port: number): Promise<void> {
  968. return new Promise((resolveListen, rejectListen) => {
  969. const onError = (error: Error) => {
  970. rejectListen(error);
  971. };
  972. server.once("error", onError);
  973. server.listen(port, "127.0.0.1", () => {
  974. server.off("error", onError);
  975. resolveListen();
  976. });
  977. });
  978. }
  979. function closeNetServer(server: NetServer): Promise<void> {
  980. return new Promise((resolveClose, rejectClose) => {
  981. server.close((error) => {
  982. if (error) {
  983. rejectClose(error);
  984. return;
  985. }
  986. resolveClose();
  987. });
  988. });
  989. }