conversation-session-r3-ui-pairwise.test.ts 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237
  1. import { mkdir, writeFile } from "node:fs/promises";
  2. import { resolve } from "node:path";
  3. import { parseRemoteWorkspaceIdentity } from "@zcode/shared";
  4. import { clearAppData, readSettings } from "#e2e/helpers/desktop-app";
  5. import {
  6. disconnectRemoteSource,
  7. reconnectRemoteProject,
  8. } from "#e2e/helpers/remote-project-actions";
  9. import { connectSSHWorkspace, readSSHRuntimeConfig } from "#e2e/helpers/ssh-remote-p0";
  10. import { prepareV4ConversationE2E } from "#e2e/helpers/v4-conversation";
  11. const CASE_MARKER = "E2E_R3_UI_PAIRWISE";
  12. const artifactDir = resolve(process.env.ZCODE_E2E_ARTIFACT_DIR ?? ".e2e-artifacts/r3-ui-pairwise");
  13. const NARROW = { width: 960, height: 700 };
  14. /** Electron 下 WebDriver setWindowSize 不可用(Browser.getWindowForTarget 缺失),改经 main 进程设置主窗口尺寸。 */
  15. async function setWindowSize(width: number, height: number): Promise<number> {
  16. const startedAt = Date.now();
  17. await browser.electron.execute(
  18. (electron, w, h) => {
  19. const win = electron.BrowserWindow.getAllWindows().find(
  20. (candidate) => !candidate.isDestroyed(),
  21. );
  22. win?.setSize(w, h);
  23. },
  24. width,
  25. height,
  26. );
  27. await browser.waitUntil(
  28. async () => {
  29. const geometry = await browser.electron.execute((electron) => {
  30. const win = electron.BrowserWindow.getAllWindows().find((item) => !item.isDestroyed());
  31. return win ? { size: win.getSize(), content: win.getContentSize() } : null;
  32. });
  33. const viewport = await browser.execute(() => [innerWidth, innerHeight]);
  34. return Boolean(
  35. geometry &&
  36. geometry.size[0] === width &&
  37. geometry.size[1] === height &&
  38. geometry.content[0] === viewport[0] &&
  39. geometry.content[1] === viewport[1],
  40. );
  41. },
  42. { timeout: 10_000, interval: 100, timeoutMsg: "窗口尺寸与 Renderer viewport 未收敛" },
  43. );
  44. return Date.now() - startedAt;
  45. }
  46. async function setLocaleAndTheme(
  47. locale: "zh-CN" | "en-US",
  48. theme: "light" | "dark",
  49. ): Promise<{ locale: string; theme: string }> {
  50. const read = () =>
  51. browser.execute(() => {
  52. const actions = (
  53. window as Window & { __testActions?: { getLocale?: () => string; getTheme?: () => string } }
  54. ).__testActions;
  55. return { locale: actions?.getLocale?.() ?? "", theme: actions?.getTheme?.() ?? "" };
  56. });
  57. await browser.execute(
  58. (nextLocale, nextTheme) => {
  59. const actions = (
  60. window as Window & {
  61. __testActions?: { setLocale?: (l: string) => void; setTheme?: (t: string) => void };
  62. }
  63. ).__testActions;
  64. actions?.setLocale?.(nextLocale);
  65. actions?.setTheme?.(nextTheme);
  66. },
  67. locale,
  68. theme,
  69. );
  70. // locale/theme 切换为异步状态更新:最多等 10s 收敛。
  71. let state = await read();
  72. await browser.waitUntil(
  73. async () => {
  74. state = await read();
  75. return state.locale === locale && state.theme.includes(theme);
  76. },
  77. { timeout: 10_000, interval: 300, timeoutMsg: "locale-theme" },
  78. );
  79. return state;
  80. }
  81. /** 视口内可见的关键元素是否被裁切/横向溢出,以及焦点是否落在可见元素上。 */
  82. async function readLayoutHealth(selectors: string[]): Promise<{
  83. overflowX: boolean;
  84. clipped: string[];
  85. focusVisible: boolean;
  86. htmlClass: string;
  87. bodyText: string;
  88. }> {
  89. return browser.execute((list) => {
  90. const clipped: string[] = [];
  91. for (const selector of list) {
  92. for (const node of Array.from(document.querySelectorAll<HTMLElement>(selector))) {
  93. const rect = node.getBoundingClientRect();
  94. if (!rect.width || !rect.height) continue;
  95. if (
  96. rect.left < -1 ||
  97. rect.right > window.innerWidth + 1 ||
  98. rect.top < -1 ||
  99. rect.bottom > window.innerHeight + 1
  100. )
  101. clipped.push(
  102. `${selector}@${Math.round(rect.left)},${Math.round(rect.top)},${Math.round(rect.right)},${Math.round(rect.bottom)}`,
  103. );
  104. }
  105. }
  106. const active = document.activeElement as HTMLElement | null;
  107. return {
  108. overflowX: document.documentElement.scrollWidth > window.innerWidth + 1,
  109. clipped: clipped.slice(0, 10),
  110. focusVisible: Boolean(active && active !== document.body && active.getClientRects().length),
  111. htmlClass: document.documentElement.className,
  112. bodyText: (document.body?.innerText ?? "").replace(/\s+/gu, " ").slice(0, 2000),
  113. };
  114. }, selectors);
  115. }
  116. describe(`${CASE_MARKER}: 项目导航中英文/深浅主题与窄窗口`, () => {
  117. const facts: Array<Record<string, unknown>> = [];
  118. after(async () => {
  119. await mkdir(artifactDir, { recursive: true });
  120. await writeFile(resolve(artifactDir, "ui-pairwise.json"), JSON.stringify(facts, null, 2));
  121. await browser.electron.restoreAllMocks();
  122. await clearAppData();
  123. });
  124. it("R3A-UI-03 英文深色窄窗口与中文浅色桌面下,设备标注、项目菜单、离线入口与重连保持可见可用", async function () {
  125. this.timeout(15 * 60_000);
  126. const config = readSSHRuntimeConfig(CASE_MARKER);
  127. await prepareV4ConversationE2E({ skipProvider: true });
  128. await mkdir(artifactDir, { recursive: true });
  129. const scenarios = [
  130. {
  131. locale: "en-US" as const,
  132. theme: "dark" as const,
  133. width: NARROW.width,
  134. height: NARROW.height,
  135. },
  136. { locale: "zh-CN" as const, theme: "light" as const, width: 1280, height: 900 },
  137. ];
  138. let identity: string | undefined;
  139. for (const scenario of scenarios) {
  140. const current: Record<string, unknown> = { ...scenario };
  141. facts.push(current);
  142. current.resizeMs = await setWindowSize(scenario.width, scenario.height);
  143. const appearance = await setLocaleAndTheme(scenario.locale, scenario.theme);
  144. expect(appearance.locale).toBe(scenario.locale);
  145. expect(appearance.theme).toContain(scenario.theme);
  146. if (!identity) {
  147. const tab = await connectSSHWorkspace({
  148. config,
  149. caseMarker: CASE_MARKER,
  150. workspacePath: config.workspacePaths[0],
  151. });
  152. identity = tab.workspaceIdentity!;
  153. }
  154. const sourceId = parseRemoteWorkspaceIdentity(identity)?.sourceServerId;
  155. if (!sourceId) throw new Error("缺少 Source 身份");
  156. const selector = `[data-project-workspace-identity="${identity}"]`;
  157. const row = $(selector);
  158. expect(await row.getAttribute("data-connection-state")).toBe("online");
  159. // 项目整合后设备标签只负责展示;详情弹层已移除,操作由项目菜单承载。
  160. const deviceName = (await readSettings()).sourceServers?.find(
  161. (source) => source.sourceServerId === sourceId,
  162. )?.displayName;
  163. expect(deviceName).toBeTruthy();
  164. const device = row.$('[data-testid="project-device"]');
  165. // 设备原生 title 已迁入统一身份详情;检查可见名称和真实 hover,避免旧属性让后续矩阵提前失败。
  166. expect(await device.getText()).toBe(deviceName);
  167. await row.$('[data-testid="virtual-project-toggle"]').moveTo();
  168. const details = $('[data-testid="remote-identity-details"]');
  169. await details.waitForDisplayed();
  170. current.identityDetails = await details.getText();
  171. expect(current.identityDetails).toContain(deviceName);
  172. expect(current.identityDetails).toContain(config.workspacePaths[0]);
  173. expect(await details.$$("button")).toHaveLength(0);
  174. const outside = await browser.execute(() => ({ x: innerWidth - 24, y: 24 }));
  175. await browser.action("pointer").move(outside).perform();
  176. await details.waitForDisplayed({ reverse: true });
  177. await row.moveTo();
  178. const trigger = row.$('[data-testid="virtual-project-menu"]');
  179. await trigger.click();
  180. const menuId = await trigger.getAttribute("aria-controls");
  181. expect(menuId).toBeTruthy();
  182. const menuSelector = `[id=${JSON.stringify(menuId)}]`;
  183. const menu = $(menuSelector);
  184. await menu.waitForDisplayed({ timeout: 15_000 });
  185. expect(await menu.getText()).toMatch(
  186. scenario.locale === "en-US" ? /Edit|Delete|Remove/iu : /编辑|删除|移除/u,
  187. );
  188. current.deviceName = deviceName;
  189. current.menuText = await menu.getText();
  190. await menu.$('[data-testid="virtual-project-edit"]').click();
  191. const editorSelector = '[role="dialog"]:has([data-testid="virtual-project-name"])';
  192. const editor = $(editorSelector);
  193. await editor.waitForDisplayed();
  194. expect(
  195. await editor.$('[data-testid="virtual-project-root-name"]').getAttribute("title"),
  196. ).toBe(config.workspacePaths[0]);
  197. // 本例验收布局与后续交互;用真实点击建立用户焦点,不要求菜单打开后自动聚焦。
  198. await editor.$('[data-testid="virtual-project-name"]').click();
  199. await browser
  200. .waitUntil(
  201. () =>
  202. browser.execute((selector) => {
  203. const editor = document.querySelector(selector);
  204. const active = document.activeElement;
  205. return Boolean(
  206. editor && active && editor.contains(active) && active.getClientRects().length,
  207. );
  208. }, editorSelector),
  209. { timeout: 5000, timeoutMsg: "项目编辑器未获得可见焦点" },
  210. )
  211. .catch(async (cause: unknown) => {
  212. current.focusFailure = await browser.execute(() => ({
  213. tag: document.activeElement?.tagName,
  214. testId: document.activeElement?.getAttribute("data-testid"),
  215. }));
  216. throw cause;
  217. });
  218. const health = await readLayoutHealth([selector, editorSelector]);
  219. expect(health.overflowX).toBe(false);
  220. expect(health.clipped).toEqual([]);
  221. expect(health.focusVisible).toBe(true);
  222. await browser.saveScreenshot(
  223. resolve(artifactDir, `${scenario.locale}-${scenario.theme}.png`),
  224. );
  225. await browser.keys("Escape");
  226. await disconnectRemoteSource(sourceId, CASE_MARKER, { workspaceIdentities: [identity] });
  227. expect(await row.isDisplayed()).toBe(true);
  228. await reconnectRemoteProject(identity, CASE_MARKER);
  229. expect(await row.getAttribute("data-connection-state")).toBe("online");
  230. current.health = health;
  231. }
  232. });
  233. });