upstreamReplayServer.test.ts 29 KB

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