browser-empty-state-deferred-guest.test.ts 6.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160
  1. import { createServer, type Server, type ServerResponse } from "node:http";
  2. import type { AddressInfo } from "node:net";
  3. import { TID_BROWSER_ADDRESS_INPUT, TID_BROWSER_WEBVIEW } from "@zcode/shared/test-ids";
  4. import { clearAppData } from "#e2e/helpers/desktop-app";
  5. import { openFirstBrowserTab } from "#e2e/helpers/browser-side-pane";
  6. import { prepareConversationE2E } from "#e2e/helpers/conversation-session";
  7. let fixtureServer: Server | null = null;
  8. let fixtureUrl = "";
  9. let pendingResponse: ServerResponse | null = null;
  10. describe("BCP-226:human Browser 空态延迟创建 guest(formal)", () => {
  11. before(async () => {
  12. fixtureServer = createFixtureServer();
  13. fixtureUrl = `${await listen(fixtureServer)}/ready`;
  14. });
  15. after(async () => {
  16. pendingResponse?.destroy();
  17. pendingResponse = null;
  18. await closeServer(fixtureServer);
  19. fixtureServer = null;
  20. await browser.electron.restoreAllMocks();
  21. await clearAppData();
  22. });
  23. it("空 tab 与地址草稿不创建 guest,回车后创建单 guest 并完成导航", async function () {
  24. this.timeout(90_000);
  25. await prepareConversationE2E({ skipProvider: true });
  26. await openFirstBrowserTab();
  27. await waitForEmptyHumanTab();
  28. expect(await readGuestSnapshot()).toEqual({ domGuests: 0, mainGuests: 0 });
  29. const addressInput = await $(`[data-testid="${TID_BROWSER_ADDRESS_INPUT}"]`);
  30. await addressInput.waitForDisplayed({ timeout: 15_000 });
  31. const pendingUrl = new URL("/pending", fixtureUrl).href;
  32. await addressInput.setValue(pendingUrl);
  33. // Bug 回归:地址草稿不是已确认导航,不能提前裸露或创建 about:blank guest。
  34. await waitForEmptyHumanTab();
  35. expect(await readGuestSnapshot()).toEqual({ domGuests: 0, mainGuests: 0 });
  36. await addressInput.click();
  37. await browser.keys("Enter");
  38. await browser.waitUntil(
  39. async () => {
  40. const snapshot = await readGuestSnapshot();
  41. return snapshot.domGuests === 1 && snapshot.mainGuests === 1;
  42. },
  43. { timeout: 20_000, timeoutMsg: "确认导航后没有创建唯一 Browser guest" },
  44. );
  45. try {
  46. // 暂扣真实响应,让 bootstrap 已结束、目标页尚未提交的窗口可重复观测,不靠 sleep。
  47. await browser.waitUntil(() => pendingResponse !== null, {
  48. timeout: 15_000,
  49. timeoutMsg: "首次导航没有到达受控服务器",
  50. });
  51. expect(await readMainGuestUrls()).toEqual(["about:blank"]);
  52. expect(await addressInput.getValue()).toBe(pendingUrl);
  53. } finally {
  54. pendingResponse?.writeHead(302, { location: "/ready" });
  55. pendingResponse?.end();
  56. pendingResponse = null;
  57. }
  58. await browser.waitUntil(
  59. async () => (await readMainGuestUrls()).some((url) => url === fixtureUrl),
  60. { timeout: 30_000, timeoutMsg: "新 guest 没有消费地址栏待导航 URL" },
  61. );
  62. expect(await readGuestSnapshot()).toEqual({ domGuests: 1, mainGuests: 1 });
  63. await expect(addressInput).toHaveValue(fixtureUrl);
  64. // 初始化空白页不回填,不能变成所有 about:blank 导航都被忽略。
  65. await browser.electron.execute((electron) => {
  66. const guest = electron.webContents
  67. .getAllWebContents()
  68. .find((contents) => !contents.isDestroyed() && contents.getType() === "webview");
  69. if (!guest) throw new Error("缺少 Browser guest");
  70. return guest.executeJavaScript("document.getElementById('blank-link').click()");
  71. });
  72. await browser.waitUntil(async () => (await readMainGuestUrls()).includes("about:blank"), {
  73. timeout: 15_000,
  74. timeoutMsg: "主动空白页导航没有提交",
  75. });
  76. await expect(addressInput).toHaveValue("");
  77. });
  78. });
  79. async function waitForEmptyHumanTab(): Promise<void> {
  80. await browser.waitUntil(
  81. () =>
  82. browser.execute((webviewTestId) => {
  83. const bodyText = document.body?.innerText ?? "";
  84. const hasEmptyCopy =
  85. bodyText.includes("Paste or type a URL to open a page.") ||
  86. bodyText.includes("粘贴或输入 URL 以打开网页。");
  87. const hasSpinner = Boolean(document.querySelector("svg.lucide-loader-circle.animate-spin"));
  88. const hasWebview = Boolean(document.querySelector(`[data-testid="${webviewTestId}"]`));
  89. return hasEmptyCopy && !hasSpinner && !hasWebview;
  90. }, TID_BROWSER_WEBVIEW),
  91. { timeout: 15_000, timeoutMsg: "human 空 tab 没有保持 Globe 空态且无 webview" },
  92. );
  93. }
  94. async function readGuestSnapshot(): Promise<{ domGuests: number; mainGuests: number }> {
  95. const domGuests = await browser.execute(
  96. (webviewTestId) => document.querySelectorAll(`[data-testid="${webviewTestId}"]`).length,
  97. TID_BROWSER_WEBVIEW,
  98. );
  99. const mainGuests = await browser.electron.execute(
  100. (electron) =>
  101. electron.webContents
  102. .getAllWebContents()
  103. .filter((contents) => !contents.isDestroyed() && contents.getType() === "webview").length,
  104. );
  105. return { domGuests, mainGuests };
  106. }
  107. async function readMainGuestUrls(): Promise<string[]> {
  108. return browser.electron.execute((electron) =>
  109. electron.webContents
  110. .getAllWebContents()
  111. .filter((contents) => !contents.isDestroyed() && contents.getType() === "webview")
  112. .map((contents) => contents.getURL()),
  113. ) as unknown as Promise<string[]>;
  114. }
  115. function createFixtureServer(): Server {
  116. return createServer((request, response) => {
  117. if (request.url === "/pending") {
  118. pendingResponse = response;
  119. return;
  120. }
  121. response.setHeader("content-type", "text/html; charset=utf-8");
  122. response.end(
  123. '<!doctype html><html><head><title>BCP-226</title></head><body><main data-e2e-marker="BCP226_READY">ready</main><a id="blank-link" href="about:blank">Blank</a></body></html>',
  124. );
  125. });
  126. }
  127. async function listen(server: Server): Promise<string> {
  128. await new Promise<void>((resolve, reject) => {
  129. server.once("error", reject);
  130. server.listen(0, "127.0.0.1", () => {
  131. server.off("error", reject);
  132. resolve();
  133. });
  134. });
  135. const address = server.address() as AddressInfo | null;
  136. if (!address) throw new Error("BCP-226 fixture server 没有绑定端口");
  137. return `http://127.0.0.1:${address.port}`;
  138. }
  139. async function closeServer(server: Server | null): Promise<void> {
  140. if (!server?.listening) return;
  141. await new Promise<void>((resolve, reject) => {
  142. server.close((error) => (error ? reject(error) : resolve()));
  143. });
  144. }