web-remote-visibility-browser.ts 4.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133
  1. import { appendFile } from "node:fs/promises";
  2. import { join } from "node:path";
  3. import { chromium, type Page } from "playwright-core";
  4. import { openMobilePairingPage } from "#e2e/helpers/mobile-pairing";
  5. interface LocalChromiumPage extends Page {
  6. _connection?: {
  7. toImpl?(page: Page): {
  8. delegate?: {
  9. _mainFrameSession?: {
  10. _client?: {
  11. send(method: string, params: { enabled: boolean }): Promise<void>;
  12. };
  13. };
  14. };
  15. };
  16. };
  17. }
  18. async function useNativeVisibility(page: Page) {
  19. // Playwright在主CDP session强制focus emulation,使后台tab也永远visible。
  20. // 新CDP session不能撤销原session的覆盖;只关闭本地driver原始session的测试仿真,
  21. // 后续完全使用Chrome真实tab切换,不修改document getter或派发visibility事件。
  22. const local = page as LocalChromiumPage;
  23. const client = local._connection?.toImpl?.(page)?.delegate?._mainFrameSession?._client;
  24. if (typeof client?.send !== "function")
  25. throw new Error(
  26. "MRO03: Playwright local Chromium visibility ABI changed; native visibility is required",
  27. );
  28. await client.send("Emulation.setFocusEmulationEnabled", { enabled: false });
  29. }
  30. /** 使用成熟导航与清理流程,仅撤销测试框架强制前台;浏览器仍是真实headed Chrome。 */
  31. export async function createWebRemoteVisibilityBrowser(
  32. artifactDir: string,
  33. options: { width?: number; caseMarker?: string } = {},
  34. ) {
  35. const caseMarker = options.caseMarker ?? "MRO03";
  36. const executablePath =
  37. process.env.ZCODE_E2E_MOBILE_BROWSER_EXECUTABLE || process.env.R3_MOBILE_CHROME;
  38. const chrome = await chromium.launch({
  39. ...(executablePath ? { executablePath } : { channel: "chrome" }),
  40. headless: false,
  41. });
  42. const context = await chrome.newContext({
  43. viewport: { width: options.width ?? 1440, height: 1000 },
  44. locale: "zh-CN",
  45. });
  46. const page = await context.newPage();
  47. page.setDefaultTimeout(30_000);
  48. let logFlight = Promise.resolve();
  49. const recordEvent = (stage: string, detail?: unknown) => {
  50. logFlight = logFlight.then(() =>
  51. appendFile(
  52. join(artifactDir, `${caseMarker}-native-stages.jsonl`),
  53. JSON.stringify({ stage, detail }) + "\n",
  54. ),
  55. );
  56. return logFlight;
  57. };
  58. const record = async (stage: string) =>
  59. recordEvent(stage, {
  60. visibility: await page.evaluate(() => document.visibilityState),
  61. });
  62. page.on("framenavigated", (frame) => {
  63. if (frame === page.mainFrame())
  64. void recordEvent("main-frame-navigated", { path: new URL(frame.url()).pathname });
  65. });
  66. page.on("request", (request) => {
  67. if (request.isNavigationRequest() && request.frame() === page.mainFrame())
  68. void recordEvent("document-request", { path: new URL(request.url()).pathname });
  69. });
  70. page.on("console", (message) => {
  71. if (message.text().startsWith("[vite]"))
  72. void recordEvent("vite-client", {
  73. text: message.text().replace(/https?:\/\/[^\s]+/gu, "<url>"),
  74. });
  75. });
  76. page.on("crash", () => {
  77. void recordEvent("page-crashed");
  78. });
  79. page.on("close", () => {
  80. void recordEvent("page-closed");
  81. });
  82. let cover: Page | undefined;
  83. return {
  84. page,
  85. evaluate: <T>(expression: string) => page.evaluate<T, void>(expression, undefined),
  86. async navigate(url: string, credentials: Record<string, string>, readySelector?: string) {
  87. await context.addInitScript((values) => {
  88. if (!location.protocol.startsWith("http")) return;
  89. for (const [key, value] of Object.entries(values)) localStorage.setItem(key, value);
  90. }, credentials);
  91. if (readySelector)
  92. await openMobilePairingPage(page, url, {
  93. artifactDir,
  94. caseMarker,
  95. phase: "native-admission",
  96. readySelector,
  97. });
  98. else await page.goto(url, { waitUntil: "domcontentloaded", timeout: 60_000 });
  99. await useNativeVisibility(page);
  100. await page.bringToFront();
  101. await record("native-navigation");
  102. },
  103. async click(selector: string) {
  104. await page.locator(selector).first().click();
  105. },
  106. async hide() {
  107. cover ??= await context.newPage();
  108. await useNativeVisibility(cover);
  109. await cover.bringToFront();
  110. await page.waitForFunction(() => document.visibilityState === "hidden");
  111. await record("native-background");
  112. },
  113. async show() {
  114. await page.bringToFront();
  115. await page.waitForFunction(() => document.visibilityState === "visible");
  116. await record("native-foreground");
  117. },
  118. async escape() {
  119. await page.keyboard.press("Escape");
  120. },
  121. async screenshot(name: string) {
  122. await page.screenshot({ path: join(artifactDir, name) });
  123. },
  124. async close() {
  125. await context.close();
  126. await chrome.close();
  127. await logFlight;
  128. },
  129. };
  130. }