conversation-session-hooks-mobile.test.ts 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166
  1. import { mkdir, writeFile } from "node:fs/promises";
  2. import { resolve } from "node:path";
  3. import { chromium } from "playwright-core";
  4. import {
  5. TID_TASK_ITEM,
  6. TID_V4_HOOK_DETAILS_CONTENT,
  7. TID_V4_HOOK_DETAILS_TRIGGER,
  8. testId,
  9. } from "@zcode/shared/test-ids";
  10. import { clearAppData, DEFAULT_WORKSPACE, seedSettings } from "#e2e/helpers/desktop-app";
  11. import { countUpstreamRequestsContaining } from "#e2e/helpers/conversation-session-network";
  12. import {
  13. HOOKS_CASE_MARKERS,
  14. hasHookRecord,
  15. installHooksLifecycleFixture,
  16. restoreHooksLifecycleFixture,
  17. waitForHookScenarioTrace,
  18. } from "#e2e/helpers/hooks-lifecycle-fixture";
  19. import { openMobilePairingPage, seedMobileFixtureLogin } from "#e2e/helpers/mobile-pairing";
  20. import { skipOccupationOnboardingIfPresent } from "#e2e/helpers/occupation-onboarding";
  21. import { selectUpstreamModel, selectUpstreamThoughtLevel } from "#e2e/helpers/upstream-provider";
  22. import {
  23. getV4ConversationState,
  24. prepareV4ConversationE2E,
  25. sendV4Prompt,
  26. waitForV4ConversationState,
  27. waitForV4TimelineContaining,
  28. } from "#e2e/helpers/v4-conversation";
  29. import { obtainUnreadPairingUrl, showMobileTaskHome } from "#e2e/helpers/web-remote-unread";
  30. import { openWorkspaceDraftFromSidebar } from "#e2e/helpers/workspace-agent-warmup";
  31. // ZCT-2118215639243444224:Chrome 109 远控打开含 Hook 记录的会话,Hook 详情组件调用
  32. // executions.toSorted 抛 TypeError,区域错误边界显示“这块界面出了点问题”。
  33. // 本用例在手机 Web 打开同类会话并展开 Hook 详情;默认用新版 Chrome 做回归,
  34. // 设置 ZCODE_E2E_MOBILE_BROWSER_EXECUTABLE 可换成低版本浏览器验证 polyfill。
  35. const CASE_MARKER = "HK-MOB-01";
  36. const artifactDir = resolve(process.env.ZCODE_E2E_ARTIFACT_DIR ?? ".e2e-artifacts/hooks-mobile");
  37. const REGION_ERROR_TEXT = /这块界面出了点问题|This section ran into a problem/u;
  38. describe("Hook 详情手机 Web 远控", () => {
  39. before(async function () {
  40. this.timeout(120000);
  41. await installHooksLifecycleFixture();
  42. await seedSettings({ locale: "zh-CN", localePreference: "zh-CN" });
  43. await skipOccupationOnboardingIfPresent();
  44. await prepareV4ConversationE2E();
  45. });
  46. after(async () => {
  47. await restoreHooksLifecycleFixture();
  48. await browser.electron.restoreAllMocks();
  49. await clearAppData();
  50. });
  51. it(`${CASE_MARKER}: 手机打开含 Hook 记录的会话,Hook 详情可展开且不触发区域错误`, async function () {
  52. this.timeout(240000);
  53. await openWorkspaceDraftFromSidebar(DEFAULT_WORKSPACE);
  54. await selectUpstreamModel();
  55. await selectUpstreamThoughtLevel();
  56. // UserPromptSubmit Hook 在模型前拦截,只产生 Hook 记录,不需要上游回放。
  57. const marker = HOOKS_CASE_MARKERS.promptBlock;
  58. await sendV4Prompt(`${marker}: this prompt must be blocked before the model.`);
  59. await waitForV4TimelineContaining(marker);
  60. await waitForV4ConversationState(
  61. (snapshot) => snapshot.state === "idle" && Boolean(snapshot.taskId),
  62. "Hook 拦截后会话没有回到 idle",
  63. 60000,
  64. );
  65. await waitForHookScenarioTrace(
  66. marker,
  67. (records) =>
  68. hasHookRecord(records, {
  69. executor: "process",
  70. hook_event_name: "UserPromptSubmit",
  71. phase: "completed",
  72. }),
  73. "UserPromptSubmit Hook 没有执行完成",
  74. );
  75. expect(await countUpstreamRequestsContaining(marker)).toBe(0);
  76. const taskId = (await getV4ConversationState()).taskId;
  77. if (!taskId) throw new Error("Hook 会话缺少 taskId");
  78. const triggerTestId = await browser.waitUntil(
  79. () =>
  80. browser.execute(
  81. (text: string, prefix: string) =>
  82. Array.from(document.querySelectorAll<HTMLElement>("[data-turn-id]"))
  83. .find((turn) => turn.textContent?.includes(text))
  84. ?.querySelector<HTMLElement>(`[data-testid^="${prefix}-"]`)
  85. ?.getAttribute("data-testid") ?? false,
  86. marker,
  87. TID_V4_HOOK_DETAILS_TRIGGER,
  88. ),
  89. { timeout: 15000, timeoutMsg: "桌面端没有出现 Hook 详情入口" },
  90. );
  91. const turnId = triggerTestId.slice(TID_V4_HOOK_DETAILS_TRIGGER.length + 1);
  92. const endpoint = process.env.ZCODE_WEB_REMOTE_CONTROL_URL;
  93. if (!endpoint) throw new Error("mobile fixture missing");
  94. const pairingUrl = await obtainUnreadPairingUrl(new URL(endpoint).origin);
  95. const executablePath = process.env.ZCODE_E2E_MOBILE_BROWSER_EXECUTABLE;
  96. const chrome = await chromium.launch({
  97. ...(executablePath ? { executablePath } : { channel: "chrome" }),
  98. headless: true,
  99. });
  100. const pageErrors: string[] = [];
  101. try {
  102. const context = await chrome.newContext({
  103. viewport: { width: 390, height: 844 },
  104. isMobile: true,
  105. hasTouch: true,
  106. locale: "zh-CN",
  107. });
  108. await seedMobileFixtureLogin(context);
  109. const page = await context.newPage();
  110. page.on("pageerror", (error) => pageErrors.push(error.message));
  111. await openMobilePairingPage(page, pairingUrl, {
  112. artifactDir,
  113. caseMarker: CASE_MARKER,
  114. phase: "pairing",
  115. readySelector: '[data-testid="sidebar"], [data-mobile-page="chat"]',
  116. });
  117. const browserVersion = chrome.version();
  118. await showMobileTaskHome(page);
  119. const toggles = page.getByTestId("virtual-project-toggle");
  120. for (let index = 0; index < (await toggles.count()); index++) {
  121. const toggle = toggles.nth(index);
  122. if ((await toggle.getAttribute("aria-expanded")) !== "true") await toggle.click();
  123. }
  124. await mkdir(artifactDir, { recursive: true });
  125. const content = page.getByTestId(testId(TID_V4_HOOK_DETAILS_CONTENT, turnId));
  126. try {
  127. await page.getByTestId(testId(TID_TASK_ITEM, taskId)).first().click();
  128. const session = page.locator(`[data-session-id="${taskId}"]`);
  129. await session.getByText(marker, { exact: false }).first().waitFor({ timeout: 30000 });
  130. const trigger = session.getByTestId(testId(TID_V4_HOOK_DETAILS_TRIGGER, turnId));
  131. await trigger.waitFor({ timeout: 30000 });
  132. await trigger.click();
  133. await content.waitFor({ timeout: 15000 });
  134. } catch (error) {
  135. // 区域错误边界会替换整轮内容,等待超时时需要现场文本与截图区分原因。
  136. await page.screenshot({ path: resolve(artifactDir, `${CASE_MARKER}-failure.png`) });
  137. await writeFile(
  138. resolve(artifactDir, `${CASE_MARKER}-failure.json`),
  139. JSON.stringify(
  140. { browserVersion, bodyText: await page.locator("body").innerText(), pageErrors },
  141. null,
  142. 2,
  143. ),
  144. );
  145. throw error;
  146. }
  147. const contentText = (await content.textContent()) ?? "";
  148. const bodyText = await page.locator("body").innerText();
  149. await page.screenshot({ path: resolve(artifactDir, `${CASE_MARKER}-mobile.png`) });
  150. await writeFile(
  151. resolve(artifactDir, `${CASE_MARKER}.json`),
  152. JSON.stringify({ browserVersion, taskId, turnId, contentText, pageErrors }, null, 2),
  153. );
  154. expect(contentText).toContain("UserPromptSubmit");
  155. expect(REGION_ERROR_TEXT.test(bodyText)).toBe(false);
  156. expect(pageErrors).toEqual([]);
  157. } finally {
  158. await chrome.close();
  159. }
  160. });
  161. });