conversation-session-browser-use-keypress-host-isolation.test.ts 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225
  1. import { createServer, type Server } from "node:http";
  2. import type { AddressInfo } from "node:net";
  3. import { TID_V4_COMPOSER_INPUT } from "@zcode/shared/test-ids";
  4. import { clearAppData } from "#e2e/helpers/desktop-app";
  5. import { waitForUpstreamRequest } from "#e2e/helpers/conversation-session-network";
  6. import {
  7. waitForSuccessfulToolCallByToolCallId,
  8. waitForToolCallBlockByToolName,
  9. } from "#e2e/helpers/conversation-session-tool";
  10. import {
  11. approveV4Permission,
  12. prepareV4ConversationE2E,
  13. sendV4Prompt,
  14. waitForV4AssistantMessageContaining,
  15. waitForV4Pane,
  16. waitForV4UserMessageContaining,
  17. } from "#e2e/helpers/v4-conversation";
  18. // BU-E2E-028(docs/browser-use/2026-07-12-browser-use-runtime-semantics-spec.md §2.2):
  19. // 网页没有键盘焦点、宿主 Composer 有焦点时,cua.keypress 只能送到网页。修复前 guest 主 frame 的
  20. // CDP 按键按窗口焦点落到宿主:Escape 触发停止会话,字母和 Enter 进了 Composer。
  21. const PROMPT_MARKER = "E2E_BROWSER_USE_KEYPRESS_ISOLATION";
  22. const TOOL_NAME = "mcp__node_repl__js";
  23. const TOOL_CALL_ID = "toolu_e2e_browser_keypress_isolation";
  24. const RESULT_MARKER = "E2E_BROWSER_USE_KEYPRESS_OK";
  25. const FINAL_MARKER = "E2E_BROWSER_USE_KEYPRESS_DONE";
  26. const PAGE_PATH = "/keys";
  27. let fixtureServer: Server | null = null;
  28. let fixtureOrigin = "";
  29. describe("BU-E2E-028:网页无焦点时 cua.keypress 不落到宿主", () => {
  30. before(async () => {
  31. fixtureServer = createKeypressFixtureServer();
  32. fixtureOrigin = await listen(fixtureServer);
  33. });
  34. after(async () => {
  35. await closeServer(fixtureServer);
  36. fixtureServer = null;
  37. await clearAppData();
  38. });
  39. it("Escape 不停止会话,a/b/Enter/Escape 只进网页,宿主 Composer 不变", async function () {
  40. this.timeout(240000);
  41. await prepareV4ConversationE2E();
  42. const prompt = [
  43. `${PROMPT_MARKER}: press keys in the in-app browser while the page has no keyboard focus.`,
  44. `E2E_BROWSER_FIXTURE_URL:${fixtureOrigin}/`,
  45. ].join(" ");
  46. await sendV4Prompt(prompt);
  47. await waitForV4UserMessageContaining(PROMPT_MARKER);
  48. await waitForUpstreamRequest(
  49. {
  50. includes: [PROMPT_MARKER, "E2E_BROWSER_FIXTURE_URL:", TOOL_NAME],
  51. excludes: ["Generate a concise title", "CRITICAL: Respond with TEXT ONLY"],
  52. },
  53. "首轮请求没有暴露 Browser Use Node REPL 工具或 fixture marker",
  54. 60000,
  55. );
  56. await waitForToolCallBlockByToolName(TOOL_NAME, 90000);
  57. await approveV4Permission();
  58. // 工具已打开页面、用页面脚本把焦点放进输入框,正在等闸门;此时让宿主 Composer 拿到焦点,
  59. // 再在宿主装按键探针,最后开闸让工具开始按键。
  60. const guestId = await waitForGuestInputFocused().catch(async (error: unknown) => {
  61. const tool = await waitForSuccessfulToolCallByToolCallId(TOOL_CALL_ID, [], 5000).catch(
  62. (toolError: unknown) => String(toolError),
  63. );
  64. throw new Error(`${String(error)}\n工具输出: ${JSON.stringify(tool)}`);
  65. });
  66. const composer = await focusEmptyV4Composer();
  67. expect(composer).toEqual({ focused: true, text: "" });
  68. await installHostKeydownProbe();
  69. await openGuestGate(guestId);
  70. await waitForSuccessfulToolCallByToolCallId(TOOL_CALL_ID, [RESULT_MARKER], 90000);
  71. await waitForV4AssistantMessageContaining(FINAL_MARKER);
  72. await waitForV4Pane(
  73. (snapshot) => !snapshot.canStop && snapshot.sessionId !== "draft",
  74. "按键 turn 完成后没有回到 idle",
  75. 90000,
  76. );
  77. expect(await readHostKeydowns()).toEqual([]);
  78. expect((await readV4ComposerSnapshot()).text).toBe("");
  79. });
  80. });
  81. function createKeypressFixtureServer(): Server {
  82. return createServer((_request, response) => {
  83. response.setHeader("content-type", "text/html; charset=utf-8");
  84. response.end(`<!doctype html>
  85. <html>
  86. <head><title>E2E Keypress Isolation</title></head>
  87. <body>
  88. <form id="form"><label>Name <input id="name" /></label><button type="submit">Submit</button></form>
  89. <dialog id="dialog">E2E dialog</dialog>
  90. <script>
  91. window.__e2eKeys = [];
  92. window.__e2eSubmits = 0;
  93. window.__e2eGate = false;
  94. addEventListener("keydown", (event) => {
  95. if (event.isTrusted) window.__e2eKeys.push(event.key);
  96. }, true);
  97. document.getElementById("form").addEventListener("submit", (event) => {
  98. event.preventDefault();
  99. window.__e2eSubmits += 1;
  100. });
  101. </script>
  102. </body>
  103. </html>`);
  104. });
  105. }
  106. async function listen(server: Server): Promise<string> {
  107. await new Promise<void>((resolve, reject) => {
  108. server.once("error", reject);
  109. server.listen(0, "127.0.0.1", () => {
  110. server.off("error", reject);
  111. resolve();
  112. });
  113. });
  114. const address = server.address() as AddressInfo | null;
  115. if (!address) throw new Error("按键 fixture server 没有绑定端口");
  116. return `http://127.0.0.1:${address.port}`;
  117. }
  118. async function closeServer(server: Server | null) {
  119. if (!server?.listening) return;
  120. await new Promise<void>((resolve, reject) => {
  121. server.close((error) => (error ? reject(error) : resolve()));
  122. });
  123. }
  124. async function waitForGuestInputFocused(timeout = 60000): Promise<number> {
  125. let latest: { id: number; active: string } | null = null;
  126. const ready = await browser
  127. .waitUntil(
  128. async () => {
  129. latest = (await browser.electron.execute(async (electron, pageUrl) => {
  130. const guest = electron.webContents
  131. .getAllWebContents()
  132. .find((item) => item.getType() === "webview" && item.getURL() === pageUrl);
  133. if (!guest) return null;
  134. const active = (await guest.executeJavaScript(
  135. "document.activeElement?.id ?? ''",
  136. )) as string;
  137. return { id: guest.id, active };
  138. }, `${fixtureOrigin}${PAGE_PATH}`)) as { id: number; active: string } | null;
  139. return latest?.active === "name";
  140. },
  141. { timeout, interval: 100 },
  142. )
  143. .then(() => true)
  144. .catch(() => false);
  145. if (!ready || !latest) {
  146. throw new Error(`工具没有打开按键页面并把焦点放进输入框: ${JSON.stringify(latest)}`);
  147. }
  148. return (latest as { id: number }).id;
  149. }
  150. async function openGuestGate(webContentsId: number) {
  151. await browser.electron.execute(async (electron, id) => {
  152. const guest = electron.webContents.fromId(id);
  153. if (!guest) throw new Error("按键页面的 guest 不存在");
  154. await guest.executeJavaScript("window.__e2eGate = true");
  155. }, webContentsId);
  156. }
  157. async function installHostKeydownProbe() {
  158. await browser.execute(() => {
  159. const host = window as unknown as { __e2eHostKeydowns?: string[] };
  160. if (!host.__e2eHostKeydowns) {
  161. host.__e2eHostKeydowns = [];
  162. window.addEventListener("keydown", (event) => host.__e2eHostKeydowns?.push(event.key), true);
  163. }
  164. host.__e2eHostKeydowns.length = 0;
  165. });
  166. }
  167. function readHostKeydowns(): Promise<string[]> {
  168. return browser.execute(() => [
  169. ...((window as unknown as { __e2eHostKeydowns?: string[] }).__e2eHostKeydowns ?? []),
  170. ]);
  171. }
  172. function readV4ComposerSnapshot(): Promise<{ focused: boolean; text: string | null }> {
  173. return browser.execute((inputTestId) => {
  174. const element = document.querySelector<HTMLElement>(`[data-testid="${inputTestId}"]`);
  175. const bridge = (
  176. element as (HTMLElement & { __zcodeLexicalInputE2E?: { getText: () => string } }) | null
  177. )?.__zcodeLexicalInputE2E;
  178. return {
  179. focused: Boolean(
  180. element && document.activeElement && element.contains(document.activeElement),
  181. ),
  182. text: bridge?.getText() ?? null,
  183. };
  184. }, TID_V4_COMPOSER_INPUT);
  185. }
  186. async function focusEmptyV4Composer(timeout = 10000) {
  187. let latest = await readV4ComposerSnapshot();
  188. await browser.waitUntil(
  189. async () => {
  190. await browser.execute((inputTestId) => {
  191. const element = document.querySelector<HTMLElement>(`[data-testid="${inputTestId}"]`);
  192. (
  193. element as (HTMLElement & { __zcodeLexicalInputE2E?: { focus: () => void } }) | null
  194. )?.__zcodeLexicalInputE2E?.focus();
  195. }, TID_V4_COMPOSER_INPUT);
  196. latest = await readV4ComposerSnapshot();
  197. return latest.focused && latest.text === "";
  198. },
  199. {
  200. timeout,
  201. interval: 100,
  202. timeoutMsg: `宿主 Composer 没有在空草稿下拿到焦点: ${JSON.stringify(latest)}`,
  203. },
  204. );
  205. return latest;
  206. }