mobile-pairing.ts 5.3 KB

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