conversation-session-browser-use-subagent-boundary.test.ts 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247
  1. import { readFile } from "node:fs/promises";
  2. import { createServer, type Server } from "node:http";
  3. import type { AddressInfo } from "node:net";
  4. import { TID_BROWSER_ADDRESS_INPUT, TID_BROWSER_WEBVIEW } from "@zcode/shared/test-ids";
  5. import { clearAppData } from "#e2e/helpers/desktop-app";
  6. import type { E2ENetworkCaptureArtifact } from "#e2e/helpers/network-capture-proxy";
  7. import {
  8. prepareV4ConversationE2E,
  9. sendV4Prompt,
  10. waitForV4AssistantMessageContaining,
  11. waitForV4ConversationState,
  12. waitForV4UserMessageContaining,
  13. } from "#e2e/helpers/v4-conversation";
  14. import { waitForUpstreamRequest } from "#e2e/helpers/conversation-session-network";
  15. import { waitForToolCallBlockByToolName } from "#e2e/helpers/conversation-session-tool";
  16. import { ensureToolCrossProductFullAccessMode } from "#e2e/helpers/conversation-session-tool-cross-product";
  17. const PARENT_MARKER = "E2E_BROWSER_SUBAGENT_BOUNDARY_PARENT";
  18. const CHILD_MARKER = "E2E_BROWSER_SUBAGENT_BOUNDARY_CHILD";
  19. const PARENT_INIT_TOOL_ID = "toolu_e2e_browser_subagent_parent_init";
  20. const AGENT_TOOL_ID = "toolu_e2e_browser_subagent_agent";
  21. const CHILD_CHECK_TOOL_ID = "toolu_e2e_browser_subagent_child_check";
  22. const PARENT_RESUME_TOOL_ID = "toolu_e2e_browser_subagent_parent_resume";
  23. const PARENT_INIT_OK = "E2E_BROWSER_SUBAGENT_PARENT_INIT_OK";
  24. const CHILD_CHECKS_OK = "E2E_BROWSER_SUBAGENT_BOUNDARY_CHECKS_OK";
  25. const CHILD_DONE = "E2E_BROWSER_SUBAGENT_BOUNDARY_CHILD_DONE";
  26. const PARENT_RESUME_OK = "E2E_BROWSER_SUBAGENT_PARENT_RESUME_OK";
  27. const PARENT_DONE = "E2E_BROWSER_SUBAGENT_BOUNDARY_DONE";
  28. interface ParentBrowserSurface {
  29. address: string;
  30. id: number;
  31. }
  32. let fixtureServer: Server | null = null;
  33. let fixtureRootUrl = "";
  34. describe("Browser Use subagent 会话 E2E", () => {
  35. before(async () => {
  36. fixtureServer = createFixtureServer();
  37. fixtureRootUrl = await listen(fixtureServer);
  38. });
  39. after(async () => {
  40. await closeServer(fixtureServer);
  41. fixtureServer = null;
  42. await browser.electron.restoreAllMocks();
  43. await clearAppData();
  44. });
  45. it("BAB01/BU-E2E-012: child 与对话共用 Tab,新开的 Tab 在面板展开且结束后保留", async function () {
  46. this.timeout(300000);
  47. await prepareV4ConversationE2E();
  48. await ensureToolCrossProductFullAccessMode();
  49. const runId = Date.now();
  50. const prompt = [
  51. `${PARENT_MARKER}_${runId}: cache one Browser and Tab, then delegate a browser check to a general-purpose child.`,
  52. `E2E_BROWSER_FIXTURE_URL:${fixtureRootUrl}`,
  53. `The child marker is ${CHILD_MARKER}; after it returns, reuse the original parent tab and reply ${PARENT_DONE}.`,
  54. ].join(" ");
  55. await sendV4Prompt(prompt);
  56. await waitForV4UserMessageContaining(`${PARENT_MARKER}_${runId}`);
  57. await waitForUpstreamRequest(
  58. {
  59. includes: [PARENT_MARKER, PARENT_INIT_TOOL_ID, PARENT_INIT_OK],
  60. excludes: ["Generate a concise title", "CRITICAL: Respond with TEXT ONLY"],
  61. },
  62. "主 Agent 初始化 Browser 后没有进入 Agent delegation continuation",
  63. 90000,
  64. );
  65. const beforeChild = await waitForParentBrowserSurface();
  66. await waitForToolCallBlockByToolName("Agent", 90000);
  67. await waitForUpstreamRequest(
  68. {
  69. includes: [CHILD_MARKER, CHILD_CHECK_TOOL_ID, CHILD_CHECKS_OK, "ordinaryValue", "42"],
  70. excludes: [PARENT_MARKER, "Generate a concise title", "CRITICAL: Respond with TEXT ONLY"],
  71. },
  72. "child 普通 Node REPL 与自有 Browser Tab 检查没有完成",
  73. 90000,
  74. );
  75. const childRequestText = JSON.stringify(
  76. await waitForCapturedRequest([CHILD_MARKER, CHILD_CHECK_TOOL_ID, CHILD_CHECKS_OK]),
  77. );
  78. expect(childRequestText).not.toContain("Browser is not available in subagent");
  79. // child 开的 Tab 归当前对话:面板直接展示它,而不是挂成看不见的孤儿 shell。
  80. await waitForBrowserSurface((surface) => surface.address.includes("child=1"));
  81. await waitForUpstreamRequest(
  82. {
  83. includes: [PARENT_MARKER, AGENT_TOOL_ID, CHILD_DONE],
  84. excludes: ["Generate a concise title", "CRITICAL: Respond with TEXT ONLY"],
  85. },
  86. "child 完成后结果没有回到父 Agent continuation",
  87. 90000,
  88. );
  89. await waitForUpstreamRequest(
  90. {
  91. includes: [PARENT_MARKER, PARENT_RESUME_TOOL_ID, PARENT_RESUME_OK],
  92. excludes: ["Generate a concise title", "CRITICAL: Respond with TEXT ONLY"],
  93. },
  94. "父 Agent 返回后没有复用缓存 Tab 完成写入",
  95. 90000,
  96. );
  97. await waitForV4AssistantMessageContaining(PARENT_DONE);
  98. await waitForV4ConversationState(
  99. (snapshot) => snapshot.state === "idle" && snapshot.queueCount === 0,
  100. "subagent Browser case 完成后没有回到 idle",
  101. 90000,
  102. );
  103. expect(beforeChild.id).toBeGreaterThan(0);
  104. });
  105. });
  106. function createFixtureServer(): Server {
  107. return createServer((_request, response) => {
  108. response.setHeader("content-type", "text/html; charset=utf-8");
  109. response.end(`<!doctype html>
  110. <html>
  111. <head><meta name="viewport" content="width=device-width, initial-scale=1" /><title>E2E Subagent Browser Boundary</title></head>
  112. <body>
  113. <label>State <input id="state" /></label>
  114. <p role="status">empty</p>
  115. <script>
  116. document.querySelector("#state").addEventListener("input", (event) => {
  117. document.querySelector("[role=status]").textContent = event.currentTarget.value;
  118. });
  119. </script>
  120. </body>
  121. </html>`);
  122. });
  123. }
  124. async function listen(server: Server): Promise<string> {
  125. await new Promise<void>((resolve, reject) => {
  126. server.once("error", reject);
  127. server.listen(0, "127.0.0.1", () => {
  128. server.off("error", reject);
  129. resolve();
  130. });
  131. });
  132. const address = server.address() as AddressInfo | null;
  133. if (!address) throw new Error("Browser subagent fixture server 没有绑定端口");
  134. return `http://127.0.0.1:${address.port}/boundary`;
  135. }
  136. async function closeServer(server: Server | null) {
  137. if (!server?.listening) return;
  138. await new Promise<void>((resolve, reject) => {
  139. server.close((error) => (error ? reject(error) : resolve()));
  140. });
  141. }
  142. async function waitForParentBrowserSurface(): Promise<ParentBrowserSurface> {
  143. return await waitForBrowserSurface(
  144. (surface) => new URL(surface.address).href === new URL(fixtureRootUrl).href,
  145. );
  146. }
  147. async function waitForBrowserSurface(
  148. matches: (surface: ParentBrowserSurface) => boolean,
  149. ): Promise<ParentBrowserSurface> {
  150. let latest: ParentBrowserSurface | null = null;
  151. await browser.waitUntil(
  152. async () => {
  153. latest = await browser.execute(
  154. (addressTestId, webviewTestId) => {
  155. const isVisible = (element: HTMLElement) => {
  156. const style = getComputedStyle(element);
  157. const rect = element.getBoundingClientRect();
  158. return (
  159. style.display !== "none" &&
  160. style.visibility !== "hidden" &&
  161. rect.width > 0 &&
  162. rect.height > 0
  163. );
  164. };
  165. const addresses = Array.from(
  166. document.querySelectorAll<HTMLInputElement>(`[data-testid="${addressTestId}"]`),
  167. ).filter(isVisible);
  168. const webviews = Array.from(
  169. document.querySelectorAll<HTMLElement>(`[data-testid="${webviewTestId}"]`),
  170. )
  171. .filter(isVisible)
  172. .map(
  173. (element) =>
  174. (
  175. element as HTMLElement & { getWebContentsId?: () => number }
  176. ).getWebContentsId?.() ?? 0,
  177. )
  178. .filter((id) => id > 0);
  179. return { address: addresses[0]?.value ?? "", id: webviews[0] ?? 0 };
  180. },
  181. TID_BROWSER_ADDRESS_INPUT,
  182. TID_BROWSER_WEBVIEW,
  183. );
  184. return latest.id > 0 && latest.address !== "" && matches(latest);
  185. },
  186. {
  187. timeout: 60000,
  188. timeoutMsg: `可见 Browser surface 没有收敛: ${JSON.stringify(latest)}`,
  189. },
  190. );
  191. if (!latest) throw new Error("可见 Browser surface 在等待后仍不存在");
  192. return latest as unknown as ParentBrowserSurface;
  193. }
  194. async function waitForCapturedRequest(expected: string[]) {
  195. let latest: unknown = null;
  196. await browser.waitUntil(
  197. async () => {
  198. const artifact = await readCaptureArtifact();
  199. latest =
  200. artifact?.records.find(
  201. (record) =>
  202. record.status === "complete" &&
  203. expected.every((text) => captureContainsText(record.requestJson, text)),
  204. )?.requestJson ?? null;
  205. return latest !== null;
  206. },
  207. {
  208. timeout: 60000,
  209. timeoutMsg: `没有捕获到请求: ${expected.join(", ")}`,
  210. },
  211. );
  212. return latest;
  213. }
  214. async function readCaptureArtifact(): Promise<E2ENetworkCaptureArtifact | null> {
  215. const capturePath = process.env.E2E_PROVIDER_CAPTURE_PATH?.trim();
  216. if (!capturePath) return null;
  217. try {
  218. return JSON.parse(await readFile(capturePath, "utf-8")) as E2ENetworkCaptureArtifact;
  219. } catch (error) {
  220. if (error instanceof Error && "code" in error && error.code === "ENOENT") return null;
  221. throw error;
  222. }
  223. }
  224. function captureContainsText(value: unknown, expected: string): boolean {
  225. if (typeof value === "string") return value.includes(expected);
  226. if (Array.isArray(value)) return value.some((item) => captureContainsText(item, expected));
  227. if (!value || typeof value !== "object") return false;
  228. return Object.values(value).some((item) => captureContainsText(item, expected));
  229. }