conversation-session-webfetch.test.ts 8.7 KB

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