upstreamReplayServer.test.ts 25 KB

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