mobile-pairing.ts 6.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147
  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. // 修复原因:Windows 上 Vite 冷启动首次按需转换整个 remote 入口依赖,domcontentloaded 实测可达 ~57s(热缓存仅 ~11s),
  60. // 旧的 45s 超时在冷缓存下稳定失败;放宽到 120s,仍以真实页面加载为准,不加固定等待。
  61. await page.goto(pairingUrl, { waitUntil: "domcontentloaded", timeout: 120_000 });
  62. // 新首页已展示共享项目/任务,不再渲染旧“已连接”文案;必须等调用方指定的真实内容。
  63. // Desktop 的手机连接状态仍由各 case 独立核对,空侧栏不能作为配对成功证据。
  64. const connected = page.locator(options.readySelector);
  65. const onboarding = page.getByTestId("onboarding-page");
  66. // 隔离测试账号可能尚未完成引导;通过真实“三步跳过”完成初始化。
  67. // 只点关闭不会保存记录,bridge 恢复重建 Root 时引导会再次遮住会话。
  68. await connected.or(onboarding).first().waitFor({ timeout: 60_000 });
  69. if (await onboarding.isVisible()) {
  70. for (const step of [1, 2, 3]) {
  71. await onboarding
  72. .locator('li[aria-current="step"]')
  73. .filter({ hasText: `${step}.` })
  74. .waitFor();
  75. await onboarding.getByRole("button", { name: /^(跳过|Skip)$/u }).click();
  76. }
  77. // Source Host 不一定提供引导记录 channel;偏好保存完成后仍可见时正常退出,
  78. // 让远控用例只依赖已保存的初始化偏好,不依赖引导记录 channel 的可用性。
  79. await page.waitForFunction(() => {
  80. const onboarding = document.querySelector('[data-testid="onboarding-page"]');
  81. return (
  82. !onboarding ||
  83. Array.from(onboarding.querySelectorAll("button")).some(
  84. (button) =>
  85. /^(开始使用|Get started)$/u.test(button.textContent?.trim() ?? "") &&
  86. !button.disabled,
  87. )
  88. );
  89. });
  90. if (await onboarding.isVisible()) {
  91. const saveError = onboarding.getByRole("alert");
  92. if (await saveError.isVisible()) {
  93. throw new Error(`首次引导偏好保存失败:${await saveError.textContent()}`);
  94. }
  95. await onboarding.getByRole("button", { name: /退出引导|Exit onboarding/u }).click();
  96. }
  97. await onboarding.waitFor({ state: "hidden", timeout: 30_000 });
  98. }
  99. await connected.waitFor({ timeout: 60_000 });
  100. } catch (error) {
  101. const prefix = resolve(
  102. options.artifactDir,
  103. `mobile-${options.phase.replace(/[^a-z0-9-]/giu, "-")}`,
  104. );
  105. try {
  106. await mkdir(options.artifactDir, { recursive: true });
  107. const snapshot = await page.evaluate(() => ({
  108. title: document.title,
  109. text: (document.body?.innerText ?? "").slice(0, 6000),
  110. testIds: Array.from(document.querySelectorAll<HTMLElement>("[data-testid]")).map(
  111. (node) => node.dataset.testid,
  112. ),
  113. scripts: Array.from(document.scripts)
  114. .map((node) => node.src)
  115. .filter(Boolean),
  116. }));
  117. await writeFile(
  118. `${prefix}.json`,
  119. JSON.stringify(
  120. {
  121. url: publicUrl(page.url()),
  122. ...snapshot,
  123. text: redact(snapshot.text),
  124. scripts: snapshot.scripts.map(publicUrl),
  125. failures,
  126. },
  127. null,
  128. 2,
  129. ),
  130. );
  131. await page.screenshot({ path: `${prefix}.png`, fullPage: true });
  132. } catch (captureError) {
  133. record(`诊断采集失败: ${String(captureError)}`);
  134. }
  135. throw new Error(
  136. `${options.caseMarker}: 手机配对失败;${redact(String(error))};${failures.join(" | ")}`,
  137. );
  138. } finally {
  139. page.off("console", onConsole);
  140. page.off("pageerror", onPageError);
  141. page.off("requestfailed", onRequestFailed);
  142. }
  143. }