mobile-pairing.ts 6.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145
  1. import { mkdir, writeFile } from "node:fs/promises";
  2. import { resolve } from "node:path";
  3. import type { BrowserContext, ConsoleMessage, Page, Request } from "playwright-core";
  4. import { WEB_REMOTE_CONTROL_FIXTURE_CREDENTIALS } from "#e2e/helpers/web-remote-control-session-events-fixture";
  5. /** Desktop 的合成账号不会自动进入新浏览器上下文;仅为已启用的 loopback fixture 补齐登录前置。 */
  6. export async function seedMobileFixtureLogin(context: BrowserContext): Promise<void> {
  7. const endpoint = process.env.ZCODE_E2E_REMOTE_AUTH_GATE_URL;
  8. if (!endpoint || !["127.0.0.1", "localhost", "[::1]"].includes(new URL(endpoint).hostname))
  9. return;
  10. await context.addInitScript((credentials) => {
  11. if (!location.protocol.startsWith("http")) return;
  12. for (const [key, value] of Object.entries(credentials)) localStorage.setItem(key, value);
  13. }, WEB_REMOTE_CONTROL_FIXTURE_CREDENTIALS);
  14. }
  15. function publicUrl(value: string): string {
  16. try {
  17. const url = new URL(value);
  18. return `${url.origin}${url.pathname}`;
  19. } catch {
  20. return "<invalid-url>";
  21. }
  22. }
  23. /** 配对参数只留在内存;错误、控制台和页面文本不能把它们带入诊断记录。 */
  24. export function redactMobileDiagnosticText(text: string, pairingUrl: string): string {
  25. const url = new URL(pairingUrl);
  26. const values = [
  27. ...url.searchParams.values(),
  28. ...new URLSearchParams(url.hash.slice(1)).values(),
  29. url.hash.slice(1),
  30. ];
  31. let result = text.split(pairingUrl).join(publicUrl(pairingUrl));
  32. for (const value of values) {
  33. if (value.length < 4) continue;
  34. result = result.split(value).join("<REDACTED>");
  35. }
  36. return result.replace(/https?:\/\/[^\s"'<>]+/gu, publicUrl);
  37. }
  38. /** 保留真实手机页面配对链路,同时在关闭 Playwright 上下文前保存失败现场。 */
  39. export async function openMobilePairingPage(
  40. page: Page,
  41. pairingUrl: string,
  42. options: { artifactDir: string; caseMarker: string; phase: string; readySelector: string },
  43. ): Promise<void> {
  44. const redact = (value: string) => redactMobileDiagnosticText(value, pairingUrl);
  45. const failures: string[] = [];
  46. const record = (value: string) => {
  47. if (failures.length < 50) failures.push(redact(value));
  48. };
  49. const onConsole = (message: ConsoleMessage) => {
  50. if (message.type() === "error") record(message.text());
  51. };
  52. const onPageError = (error: Error) => record(error.message);
  53. const onRequestFailed = (request: Request) =>
  54. record(`${publicUrl(request.url())}: ${request.failure()?.errorText ?? "request failed"}`);
  55. page.on("console", onConsole);
  56. page.on("pageerror", onPageError);
  57. page.on("requestfailed", onRequestFailed);
  58. try {
  59. await page.goto(pairingUrl, { waitUntil: "domcontentloaded", timeout: 45_000 });
  60. // 新首页已展示共享项目/任务,不再渲染旧“已连接”文案;必须等调用方指定的真实内容。
  61. // Desktop 的手机连接状态仍由各 case 独立核对,空侧栏不能作为配对成功证据。
  62. const connected = page.locator(options.readySelector);
  63. const onboarding = page.getByTestId("onboarding-page");
  64. // 隔离测试账号可能尚未完成引导;通过真实“三步跳过”完成初始化。
  65. // 只点关闭不会保存记录,bridge 恢复重建 Root 时引导会再次遮住会话。
  66. await connected.or(onboarding).first().waitFor({ timeout: 60_000 });
  67. if (await onboarding.isVisible()) {
  68. for (const step of [1, 2, 3]) {
  69. await onboarding
  70. .locator('li[aria-current="step"]')
  71. .filter({ hasText: `${step}.` })
  72. .waitFor();
  73. await onboarding.getByRole("button", { name: /^(跳过|Skip)$/u }).click();
  74. }
  75. // Source Host 不一定提供引导记录 channel;偏好保存完成后仍可见时正常退出,
  76. // 让远控用例只依赖已保存的初始化偏好,不依赖引导记录 channel 的可用性。
  77. await page.waitForFunction(() => {
  78. const onboarding = document.querySelector('[data-testid="onboarding-page"]');
  79. return (
  80. !onboarding ||
  81. Array.from(onboarding.querySelectorAll("button")).some(
  82. (button) =>
  83. /^(开始使用|Get started)$/u.test(button.textContent?.trim() ?? "") &&
  84. !button.disabled,
  85. )
  86. );
  87. });
  88. if (await onboarding.isVisible()) {
  89. const saveError = onboarding.getByRole("alert");
  90. if (await saveError.isVisible()) {
  91. throw new Error(`首次引导偏好保存失败:${await saveError.textContent()}`);
  92. }
  93. await onboarding.getByRole("button", { name: /退出引导|Exit onboarding/u }).click();
  94. }
  95. await onboarding.waitFor({ state: "hidden", timeout: 30_000 });
  96. }
  97. await connected.waitFor({ timeout: 60_000 });
  98. } catch (error) {
  99. const prefix = resolve(
  100. options.artifactDir,
  101. `mobile-${options.phase.replace(/[^a-z0-9-]/giu, "-")}`,
  102. );
  103. try {
  104. await mkdir(options.artifactDir, { recursive: true });
  105. const snapshot = await page.evaluate(() => ({
  106. title: document.title,
  107. text: (document.body?.innerText ?? "").slice(0, 6000),
  108. testIds: Array.from(document.querySelectorAll<HTMLElement>("[data-testid]")).map(
  109. (node) => node.dataset.testid,
  110. ),
  111. scripts: Array.from(document.scripts)
  112. .map((node) => node.src)
  113. .filter(Boolean),
  114. }));
  115. await writeFile(
  116. `${prefix}.json`,
  117. JSON.stringify(
  118. {
  119. url: publicUrl(page.url()),
  120. ...snapshot,
  121. text: redact(snapshot.text),
  122. scripts: snapshot.scripts.map(publicUrl),
  123. failures,
  124. },
  125. null,
  126. 2,
  127. ),
  128. );
  129. await page.screenshot({ path: `${prefix}.png`, fullPage: true });
  130. } catch (captureError) {
  131. record(`诊断采集失败: ${String(captureError)}`);
  132. }
  133. throw new Error(
  134. `${options.caseMarker}: 手机配对失败;${redact(String(error))};${failures.join(" | ")}`,
  135. );
  136. } finally {
  137. page.off("console", onConsole);
  138. page.off("pageerror", onPageError);
  139. page.off("requestfailed", onRequestFailed);
  140. }
  141. }