conversation-session-webfetch.test.ts 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276
  1. import { mkdir, rm } from "node:fs/promises";
  2. import { homedir } from "node:os";
  3. import { join, resolve } from "node:path";
  4. import { Proxy } from "http-mitm-proxy";
  5. import {
  6. clearAppData,
  7. restoreCliConfig,
  8. seedCliConfig,
  9. seedSettings,
  10. snapshotCliConfig,
  11. type CliConfigSnapshot,
  12. } from "#e2e/helpers/desktop-app";
  13. import { DEFAULT_E2E_NETWORK_CAPTURE_NO_PROXY } from "#e2e/helpers/network-capture-proxy";
  14. import {
  15. prepareV4ConversationE2E,
  16. sendV4Prompt,
  17. waitForV4AssistantMessageContaining,
  18. waitForV4ConversationState,
  19. waitForV4ComposerText,
  20. waitForV4UserMessageContaining,
  21. } from "#e2e/helpers/v4-conversation";
  22. import { waitForUpstreamRequest } from "#e2e/helpers/conversation-session-network";
  23. import { waitForToolCallBlockByToolName } from "#e2e/helpers/conversation-session-tool";
  24. import { ensureToolCrossProductFullAccessMode } from "#e2e/helpers/conversation-session-tool-cross-product";
  25. const CASE_NAME = "conversation-session-webfetch";
  26. const WEBFETCH_TOOL_NAME = "WebFetch";
  27. const WEBFETCH_TARGET_HOST = "webfetch.e2e.test";
  28. const WEBFETCH_TARGET_URL = `https://${WEBFETCH_TARGET_HOST}/e2e-webfetch-success`;
  29. const WEBFETCH_TOOL_CALL_ID = "toolu_e2e_webfetch_success";
  30. const WEBFETCH_HTML_MARKER = "E2E_WEBFETCH_HTML_MARKER";
  31. const WEBFETCH_EXTRACTED_MARKER = "E2E_WEBFETCH_EXTRACTED_OK";
  32. const WEBFETCH_FINAL_MARKER = "E2E_WEBFETCH_FINAL_OK";
  33. const WEBFETCH_REQUEST_MARKER = "E2E_WEBFETCH_REQUEST";
  34. const WEBFETCH_PROXY_ROOT = resolve(homedir(), "..", ".e2e-network-capture", CASE_NAME);
  35. interface WebFetchProxyRecord {
  36. host: string;
  37. isSSL: boolean;
  38. path: string;
  39. userAgent: string;
  40. }
  41. interface WebFetchStubProxy {
  42. caCertPath: string;
  43. errors: string[];
  44. proxyUrl: string;
  45. records: WebFetchProxyRecord[];
  46. stop(): Promise<void>;
  47. }
  48. describe("会话区 WebFetch E2E", () => {
  49. let webFetchProxy: WebFetchStubProxy | null = null;
  50. let cliConfigSnapshot: CliConfigSnapshot | null = null;
  51. afterEach(async () => {
  52. const snapshot = cliConfigSnapshot;
  53. cliConfigSnapshot = null;
  54. try {
  55. if (snapshot) {
  56. await restoreCliConfig(snapshot);
  57. }
  58. } finally {
  59. await webFetchProxy?.stop();
  60. webFetchProxy = null;
  61. }
  62. });
  63. after(async () => {
  64. await browser.electron.restoreAllMocks();
  65. await clearAppData();
  66. });
  67. it("O10: WebFetch 应通过 agent HttpClientPort 完成成功抓取和工具结果回灌", async function () {
  68. this.timeout(180000);
  69. webFetchProxy = await startWebFetchStubProxy();
  70. cliConfigSnapshot = await snapshotCliConfig();
  71. await seedSettings({
  72. httpProxy: webFetchProxy.proxyUrl,
  73. httpProxyCaCertPath: webFetchProxy.caCertPath,
  74. httpProxyNoProxy: DEFAULT_E2E_NETWORK_CAPTURE_NO_PROXY,
  75. messageStreamShowTodos: true,
  76. });
  77. await seedCliConfig({
  78. network: {
  79. httpProxy: webFetchProxy.proxyUrl,
  80. caCertFile: webFetchProxy.caCertPath,
  81. noProxy: DEFAULT_E2E_NETWORK_CAPTURE_NO_PROXY,
  82. },
  83. });
  84. await prepareV4ConversationE2E();
  85. await ensureToolCrossProductFullAccessMode();
  86. const marker = `${WEBFETCH_REQUEST_MARKER}_${Date.now()}`;
  87. const prompt = [
  88. `${marker}: Use ${WEBFETCH_TOOL_NAME} exactly once.`,
  89. `Fetch ${WEBFETCH_TARGET_URL}.`,
  90. `Ask the tool to extract ${WEBFETCH_HTML_MARKER}.`,
  91. `Then reply with exactly "${WEBFETCH_FINAL_MARKER}" and no other text.`,
  92. ].join(" ");
  93. await sendV4Prompt(prompt);
  94. await waitForV4ComposerText("", "WebFetch prompt 发送后输入框没有清空");
  95. await waitForV4UserMessageContaining(marker);
  96. await waitForUpstreamRequest(
  97. {
  98. excludes: ["Generate a concise title", "CRITICAL: Respond with TEXT ONLY"],
  99. includes: [WEBFETCH_REQUEST_MARKER, WEBFETCH_TARGET_URL],
  100. },
  101. "没有捕获到 WebFetch 首段主模型请求",
  102. 60000,
  103. );
  104. const toolBlock = await waitForToolCallBlockByToolName(WEBFETCH_TOOL_NAME, 60000);
  105. expect(toolBlock.exists).toBe(true);
  106. const proxyRecord = await waitForWebFetchProxyRecord(webFetchProxy);
  107. expect(proxyRecord.isSSL).toBe(true);
  108. expect(proxyRecord.path).toBe("/e2e-webfetch-success");
  109. expect(proxyRecord.userAgent).toContain("ZCode-WebFetch");
  110. await waitForUpstreamRequest(
  111. {
  112. excludes: ["Generate a concise title", "CRITICAL: Respond with TEXT ONLY"],
  113. includes: [
  114. "Web page content:",
  115. WEBFETCH_HTML_MARKER,
  116. "Extract the e2e marker from the fetched page.",
  117. ],
  118. },
  119. "没有捕获到 WebFetch 内部 lite model 抽取请求",
  120. 60000,
  121. );
  122. await waitForUpstreamRequest(
  123. {
  124. excludes: ["Generate a concise title", "CRITICAL: Respond with TEXT ONLY"],
  125. includes: [WEBFETCH_REQUEST_MARKER, WEBFETCH_TOOL_CALL_ID, WEBFETCH_EXTRACTED_MARKER],
  126. },
  127. "WebFetch 工具结果没有进入后续主模型请求",
  128. 90000,
  129. );
  130. await waitForV4AssistantMessageContaining(WEBFETCH_FINAL_MARKER);
  131. await waitForV4ConversationState(
  132. (snapshot) => snapshot.state === "idle" && snapshot.queueCount === 0,
  133. "WebFetch E2E 完成后没有回到 idle",
  134. 90000,
  135. );
  136. expect(webFetchProxy.errors).toEqual([]);
  137. });
  138. });
  139. async function startWebFetchStubProxy(): Promise<WebFetchStubProxy> {
  140. await rm(WEBFETCH_PROXY_ROOT, { recursive: true, force: true });
  141. await mkdir(WEBFETCH_PROXY_ROOT, { recursive: true });
  142. const host = "127.0.0.1";
  143. const proxy = new Proxy();
  144. const records: WebFetchProxyRecord[] = [];
  145. const errors: string[] = [];
  146. proxy.onError((ctx, error, errorKind) => {
  147. const requestHost = normalizeHost(ctx?.clientToProxyRequest?.headers.host);
  148. const message = [errorKind, requestHost, error instanceof Error ? error.message : String(error)]
  149. .filter(Boolean)
  150. .join(": ");
  151. errors.push(message || "WebFetch stub proxy error");
  152. });
  153. proxy.onRequest((ctx) => {
  154. const requestHost = normalizeHost(ctx.clientToProxyRequest.headers.host);
  155. const requestPath = normalizePath(ctx.clientToProxyRequest.url);
  156. if (requestHost === WEBFETCH_TARGET_HOST) {
  157. records.push({
  158. host: requestHost,
  159. isSSL: ctx.isSSL,
  160. path: requestPath,
  161. userAgent: headerValue(ctx.clientToProxyRequest.headers["user-agent"]),
  162. });
  163. ctx.proxyToClientResponse.writeHead(200, "OK", {
  164. "cache-control": "no-store",
  165. "content-type": "text/html; charset=utf-8",
  166. });
  167. ctx.proxyToClientResponse.end(
  168. [
  169. "<!doctype html>",
  170. "<html><body>",
  171. "<h1>WebFetch E2E Fixture</h1>",
  172. `<p>${WEBFETCH_HTML_MARKER}: WebFetch successfully reached the local stub proxy.</p>`,
  173. "</body></html>",
  174. ].join(""),
  175. );
  176. return;
  177. }
  178. // 修复原因:该 case 只允许 WebFetch 目标流量进入 stub proxy;
  179. // 其它请求如果误走这里,直接失败以暴露代理/NoProxy 边界漂移。
  180. const unexpectedTarget = `Unexpected proxy target: ${requestHost}${requestPath}`;
  181. errors.push(unexpectedTarget);
  182. ctx.proxyToClientResponse.writeHead(502, "Unexpected Proxy Target", {
  183. "content-type": "text/plain; charset=utf-8",
  184. });
  185. ctx.proxyToClientResponse.end(unexpectedTarget);
  186. });
  187. await new Promise<void>((resolveStart, rejectStart) => {
  188. proxy.listen(
  189. {
  190. host,
  191. keepAlive: true,
  192. port: 0,
  193. sslCaDir: WEBFETCH_PROXY_ROOT,
  194. },
  195. (error?: Error | null) => {
  196. if (error) {
  197. rejectStart(error);
  198. return;
  199. }
  200. resolveStart();
  201. },
  202. );
  203. });
  204. return {
  205. caCertPath: join(WEBFETCH_PROXY_ROOT, "certs", "ca.pem"),
  206. errors,
  207. proxyUrl: `http://${host}:${proxy.httpPort}`,
  208. records,
  209. async stop() {
  210. await new Promise<void>((resolveStop) => {
  211. proxy.close();
  212. resolveStop();
  213. });
  214. },
  215. };
  216. }
  217. async function waitForWebFetchProxyRecord(proxy: WebFetchStubProxy) {
  218. await browser.waitUntil(
  219. async () => proxy.records.some((record) => record.host === WEBFETCH_TARGET_HOST),
  220. {
  221. timeout: 60000,
  222. timeoutMsg: `WebFetch stub proxy 没有收到目标请求: ${JSON.stringify(proxy.records)}`,
  223. },
  224. );
  225. const record = proxy.records.find((item) => item.host === WEBFETCH_TARGET_HOST);
  226. if (!record) {
  227. throw new Error("WebFetch stub proxy record disappeared after wait");
  228. }
  229. return record;
  230. }
  231. function normalizeHost(value: string | string[] | undefined): string {
  232. const raw = headerValue(value).toLowerCase();
  233. return raw.replace(/:\d+$/u, "");
  234. }
  235. function normalizePath(value: string | undefined): string {
  236. if (!value) {
  237. return "/";
  238. }
  239. try {
  240. const parsed = new URL(value);
  241. return `${parsed.pathname}${parsed.search}`;
  242. } catch {
  243. return value;
  244. }
  245. }
  246. function headerValue(value: string | string[] | undefined): string {
  247. if (Array.isArray(value)) {
  248. return value[0] ?? "";
  249. }
  250. return value ?? "";
  251. }