conversation-session-remote-accessibility.test.ts 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460
  1. import { setRendererViewport } from "#e2e/helpers/renderer-viewport";
  2. import { startProjectPointerDrag } from "#e2e/helpers/project-sidebar";
  3. import { openWorkspaceDraftFromSidebar } from "#e2e/helpers/workspace-agent-warmup";
  4. import { mkdir, writeFile } from "node:fs/promises";
  5. import { resolve } from "node:path";
  6. import {
  7. TID_TASK_SETTINGS_BUTTON,
  8. TID_SETTINGS_SECTION_NAV,
  9. TID_SETTINGS_BACK_BUTTON,
  10. testId,
  11. } from "@zcode/shared/test-ids";
  12. import {
  13. clearAppData,
  14. DEFAULT_WORKSPACE,
  15. readSettings,
  16. waitForWorkspaceApp,
  17. } from "#e2e/helpers/desktop-app";
  18. import { prepareV4ConversationE2E } from "#e2e/helpers/v4-conversation";
  19. import { waitForRendererAfterColdRestart } from "#e2e/helpers/ssh-remote-lifecycle";
  20. import {
  21. openSSHRemoteDialog,
  22. fillSSHPasswordSettings,
  23. prepareSSHConnectionPage,
  24. readSSHRuntimeConfig,
  25. waitForRemoteTab,
  26. } from "#e2e/helpers/ssh-remote-p0";
  27. const marker = "E2E_REMOTE_ACCESSIBILITY";
  28. const artifact = resolve(
  29. process.env.ZCODE_E2E_ARTIFACT_DIR ?? ".e2e-artifacts/remote-accessibility",
  30. );
  31. const dialog = '[data-testid="ssh-dialog"]';
  32. /** 真正按 Tab 到目标,不用 focus()/click() 代替键盘流程。 */
  33. async function tabTo(selector: string, label?: string) {
  34. for (let index = 0; index < 90; index += 1) {
  35. await browser.keys("Tab");
  36. const matched = await browser.execute(
  37. (query, name) => {
  38. const active = document.activeElement;
  39. return Boolean(
  40. active?.matches(query) &&
  41. (!name ||
  42. active.getAttribute("aria-label") === name ||
  43. active.textContent?.trim() === name),
  44. );
  45. },
  46. selector,
  47. label,
  48. );
  49. if (matched) return;
  50. }
  51. const diagnostic = await browser.execute(
  52. (query) => ({
  53. active:
  54. document.activeElement?.getAttribute("data-testid") ?? document.activeElement?.tagName,
  55. activeRole: document.activeElement?.getAttribute("role"),
  56. candidates: [...document.querySelectorAll<HTMLElement>(query)].map((element) => ({
  57. tabIndex: element.tabIndex,
  58. hidden: !element.getClientRects().length,
  59. role: element.getAttribute("role"),
  60. })),
  61. openPopovers: document.querySelectorAll('[data-slot="popover-content"][data-state="open"]')
  62. .length,
  63. }),
  64. selector,
  65. );
  66. await browser.saveScreenshot(resolve(artifact, "keyboard-failure.png"));
  67. throw new Error(
  68. `Keyboard target unavailable: ${selector} ${label ?? ""}: ${JSON.stringify(diagnostic)}`,
  69. );
  70. }
  71. async function activate(selector: string, label?: string) {
  72. await tabTo(selector, label);
  73. await browser.keys("Enter");
  74. }
  75. async function assertLogTimestampContrast(captureName: string) {
  76. const measurements = await browser.execute(() => {
  77. const context = document.createElement("canvas").getContext("2d")!;
  78. const color = (css: string) => {
  79. context.clearRect(0, 0, 1, 1);
  80. context.fillStyle = css;
  81. context.fillRect(0, 0, 1, 1);
  82. return [...context.getImageData(0, 0, 1, 1).data];
  83. };
  84. const luminance = (rgb: number[]) =>
  85. rgb.slice(0, 3).reduce((sum, value, index) => {
  86. const channel = value / 255;
  87. const linear = channel <= 0.04045 ? channel / 12.92 : ((channel + 0.055) / 1.055) ** 2.4;
  88. return sum + linear * [0.2126, 0.7152, 0.0722][index]!;
  89. }, 0);
  90. return [...document.querySelectorAll<HTMLElement>("[data-source-server-log-timestamp]")]
  91. .filter((element) => element.getClientRects().length > 0)
  92. .map((element) => {
  93. const foreground = color(getComputedStyle(element).color);
  94. // 日志的 surface 可以半透明;必须叠加真实祖先背景,不能假设日志节点本身不透明。
  95. const layers: Array<{ node: string; css: string; rgba: number[] }> = [];
  96. for (let node: HTMLElement | null = element; node; node = node.parentElement) {
  97. const style = getComputedStyle(node);
  98. if (Number(style.opacity) !== 1 || style.backgroundImage !== "none") {
  99. throw new Error("Contrast probe requires solid backgrounds and element opacity 1");
  100. }
  101. const rgba = color(style.backgroundColor);
  102. layers.push({ node: node.tagName, css: style.backgroundColor, rgba });
  103. if (rgba[3] === 255) break;
  104. }
  105. if (layers.at(-1)?.rgba[3] !== 255) throw new Error("No opaque ancestor background");
  106. const background = layers.toReversed().reduce(
  107. (base, layer) => {
  108. const alpha = layer.rgba[3]! / 255;
  109. return base.map((channel, index) => layer.rgba[index]! * alpha + channel * (1 - alpha));
  110. },
  111. [0, 0, 0],
  112. );
  113. const alpha = foreground[3]! / 255;
  114. const text = foreground.map(
  115. (value, index) => value * alpha + background[index]! * (1 - alpha),
  116. );
  117. const a = luminance(text);
  118. const b = luminance(background);
  119. return {
  120. foreground,
  121. background,
  122. layers,
  123. ratio: (Math.max(a, b) + 0.05) / (Math.min(a, b) + 0.05),
  124. };
  125. });
  126. });
  127. await writeFile(
  128. resolve(artifact, `contrast-${captureName}.json`),
  129. JSON.stringify(measurements, null, 2),
  130. );
  131. expect(measurements.length).toBeGreaterThan(0);
  132. for (const { ratio } of measurements) expect(ratio).toBeGreaterThanOrEqual(4.5);
  133. }
  134. async function capture(state: string) {
  135. for (const locale of ["zh-CN", "en-US"] as const) {
  136. for (const theme of ["light", "dark"]) {
  137. await browser.execute(
  138. (lang, appearance) => {
  139. const actions = (
  140. window as Window & {
  141. __testActions?: {
  142. setLocale(value: "zh-CN" | "en-US"): void;
  143. setTheme(value: string): void;
  144. };
  145. }
  146. ).__testActions;
  147. if (!actions) throw new Error("Missing appearance actions");
  148. actions.setLocale(lang);
  149. actions.setTheme(appearance);
  150. },
  151. locale,
  152. theme,
  153. );
  154. for (const width of [1400, 900]) {
  155. // macOS 限制原生窗口高度;响应式覆盖使用真实 renderer viewport。
  156. await setRendererViewport(width, 1000);
  157. await browser.executeAsync((done) =>
  158. requestAnimationFrame(() => requestAnimationFrame(() => done())),
  159. );
  160. const sidebarWidth = await browser.execute(() => {
  161. const shell = document.querySelector<HTMLElement>('[style*="--workspace-sidebar-width"]');
  162. return shell
  163. ? getComputedStyle(shell).getPropertyValue("--workspace-sidebar-width").trim()
  164. : null;
  165. });
  166. expect(sidebarWidth).toBe("264px");
  167. if (state === "settings") await assertLogTimestampContrast(`${locale}-${theme}-${width}`);
  168. await browser.saveScreenshot(resolve(artifact, `${state}-${locale}-${theme}-${width}.png`));
  169. }
  170. }
  171. }
  172. await browser.execute(() =>
  173. (
  174. window as Window & { __testActions?: { setLocale(value: "zh-CN"): void } }
  175. ).__testActions?.setLocale("zh-CN"),
  176. );
  177. }
  178. describe(`${marker}: 远程键盘与视觉矩阵`, () => {
  179. after(async () => {
  180. await browser.electron.restoreAllMocks();
  181. await clearAppData();
  182. });
  183. it("RDUX-A11Y 仅键盘完成连接、选目录、侧栏与设置操作", async function () {
  184. this.timeout(15 * 60_000);
  185. await mkdir(artifact, { recursive: true });
  186. const config = readSSHRuntimeConfig(marker);
  187. await prepareSSHConnectionPage(marker);
  188. await prepareV4ConversationE2E({ skipProvider: true });
  189. await browser.execute(() => {
  190. localStorage.setItem("zcode:workspace-shell:sidebar-width-px", "264");
  191. (
  192. window as Window & {
  193. __testActions?: { setLocale(value: "zh-CN"): void };
  194. }
  195. ).__testActions?.setLocale("zh-CN");
  196. });
  197. await openWorkspaceDraftFromSidebar(DEFAULT_WORKSPACE);
  198. await browser.refresh();
  199. // 本步骤只重载侧栏宽度;草稿导航不保证恢复到默认项目,不应成为无障碍场景的额外前置。
  200. await waitForRendererAfterColdRestart(marker);
  201. const projectCountBefore = await $$("[data-project-id]").length;
  202. await openSSHRemoteDialog(marker, { entry: "settings" });
  203. await fillSSHPasswordSettings(config);
  204. // 键盘验收时将指针停在非交互区域,避免窗口缩放把 hover 入口移到指针下。
  205. await browser.performActions([
  206. {
  207. type: "pointer",
  208. id: "park",
  209. parameters: { pointerType: "mouse" },
  210. actions: [{ type: "pointerMove", x: 1, y: 1, duration: 0 }],
  211. },
  212. ]);
  213. await activate(`${dialog} button`, "显示密码");
  214. expect(await $(`${dialog} [data-testid="ssh-password-input"]`).getAttribute("type")).toBe(
  215. "text",
  216. );
  217. await activate(`${dialog} button`, "隐藏密码");
  218. await activate(`${dialog} button`, "高级选项");
  219. const group = $(`${dialog} [role="group"][aria-labelledby$="ssh.assetInstallMode"]`);
  220. // 展开状态先更新,动画随后才使安装方式可见;旧 case 在 Enter 返回后立即读可见性会误报。
  221. await group.$('button[aria-pressed="true"]').waitForDisplayed({ timeout: 5000 });
  222. expect(await group.$('button[aria-pressed="true"]').isDisplayed()).toBe(true);
  223. await tabTo(
  224. `${dialog} [role="group"][aria-labelledby$="ssh.assetInstallMode"] button[aria-pressed="false"]`,
  225. );
  226. // 全局强制描边已回退;键盘流程仍需实际获得焦点,不再要求组件叠加 outline。
  227. expect(await browser.execute(() => document.activeElement!.matches(":focus-visible"))).toBe(
  228. true,
  229. );
  230. await browser.keys("Enter");
  231. await activate(
  232. `${dialog} [role="group"][aria-labelledby$="ssh.assetInstallMode"] button[aria-pressed="false"]`,
  233. );
  234. await capture("form");
  235. await activate(`${dialog} button[type="submit"]`);
  236. // 设置添加只管理设备;旧 case 等待目录页会阻断后续全部键盘断言。
  237. // 首装和首次说明都由键盘确认,再从项目入口单独选择设备与目录。
  238. await browser.waitUntil(
  239. async () =>
  240. (await $(dialog).$("button*=安装并继续").isDisplayed()) ||
  241. (await $('[data-testid="source-server-boundary-dialog"]').isDisplayed()) ||
  242. !(await $(dialog).isExisting()),
  243. { timeout: 120_000 },
  244. );
  245. if (await $(dialog).$("button*=安装并继续").isDisplayed()) {
  246. await capture("install");
  247. await activate(`${dialog} button`, "安装并继续");
  248. }
  249. await browser.waitUntil(
  250. async () =>
  251. (await $('[data-testid="source-server-boundary-dialog"]').isDisplayed()) ||
  252. !(await $(dialog).isExisting()),
  253. { timeout: 180_000, timeoutMsg: `${marker}: 设置添加未到达首次说明或完成状态` },
  254. );
  255. if (await $('[data-testid="source-server-boundary-dialog"]').isDisplayed()) {
  256. await activate(
  257. '[data-testid="source-server-boundary-dialog"] [data-testid="confirm-dialog-confirm"]',
  258. );
  259. }
  260. await $(dialog).waitForExist({ reverse: true });
  261. expect(await $('[data-testid="settings-page"]').isDisplayed()).toBe(true);
  262. expect(await $('[data-testid="ssh-success"]').isExisting()).toBe(false);
  263. expect(await $$("[data-project-id]").length).toBe(projectCountBefore);
  264. const settings = await readSettings();
  265. const profile = settings.connectionProfiles?.find(
  266. (item) =>
  267. item.target.kind === "ssh" &&
  268. item.target.host === config.host &&
  269. (item.target.port ?? 22) === config.port &&
  270. item.target.username === config.username &&
  271. item.lifecycleState !== "retired",
  272. );
  273. if (!profile?.sourceServerId) throw new Error(`${marker}: 设置添加未保存目标设备身份`);
  274. const hostId = `remote:server:${profile.sourceServerId}`;
  275. await $(`[data-source-server-card="${profile.sourceServerId}"]`)
  276. .$('[data-remote-connection-status="online"]')
  277. .waitForDisplayed();
  278. await activate(`[data-testid="${TID_SETTINGS_BACK_BUTTON}"]`);
  279. await activate('[data-testid="virtual-project-add"]');
  280. await $('[data-testid="virtual-project-name"]').waitForDisplayed();
  281. await activate('[data-testid="virtual-project-device"]');
  282. await $(`[role="option"][data-device-id="${hostId}"]`).waitForDisplayed();
  283. for (let index = 0; index < 50; index += 1) {
  284. if (
  285. await browser.execute(
  286. (id) => document.activeElement?.getAttribute("data-device-id") === id,
  287. hostId,
  288. )
  289. )
  290. break;
  291. await browser.keys("ArrowDown");
  292. }
  293. expect(
  294. await browser.execute(() => document.activeElement?.getAttribute("data-device-id")),
  295. ).toBe(hostId);
  296. await browser.keys("Enter");
  297. await activate('[data-testid="virtual-project-browse"]');
  298. const directory = '[data-testid="virtual-project-directory-browser"]';
  299. await $(directory).waitForDisplayed();
  300. await capture("directory");
  301. await tabTo(`${directory} input[aria-label="输入路径"]`);
  302. await browser.keys([process.platform === "darwin" ? "Meta" : "Control", "a"]);
  303. await browser.keys("Backspace");
  304. await browser.keys(config.workspacePaths[0]);
  305. await browser.keys("Enter");
  306. await $(`${directory} [data-testid="directory-browser-confirm"]`).waitForEnabled();
  307. expect(await $(`${directory} input[aria-label="输入路径"]`).getValue()).toBe(
  308. config.workspacePaths[0],
  309. );
  310. await activate(`${directory} [data-testid="directory-browser-confirm"]`);
  311. // 新目录会进入项目编辑器;继续用键盘保存并从项目创建任务,不能借全局本地草稿。
  312. await $('[data-testid="virtual-project-name"]').waitForDisplayed();
  313. expect(await $('[data-testid="virtual-project-root-name"]').getAttribute("title")).toBe(
  314. config.workspacePaths[0],
  315. );
  316. await activate('[data-testid="virtual-project-save"]');
  317. await activate('[data-testid="project-folder-trust-confirm"]');
  318. const remoteRow = `[data-project-workspace-identity="${hostId}:${config.workspacePaths[0]}"]`;
  319. await $(remoteRow).waitForDisplayed();
  320. await activate(`${remoteRow} [data-testid="virtual-project-create-task"]`);
  321. await waitForWorkspaceApp(config.workspacePaths[0], 120_000);
  322. const tab = await waitForRemoteTab({
  323. caseMarker: marker,
  324. expectedPath: config.workspacePaths[0],
  325. });
  326. const row = `[data-project-workspace-identity="${tab.workspaceIdentity}"]`;
  327. // 项目详情改由项目编辑器承载,设备信息在设置页;保留键盘打开、关闭和路径验证。
  328. await activate(`${row} [data-testid="virtual-project-menu"]`);
  329. let editFocused = false;
  330. for (let index = 0; index < 10; index++) {
  331. await browser.keys("ArrowDown");
  332. editFocused = await browser.execute(
  333. () => document.activeElement?.getAttribute("data-testid") === "virtual-project-edit",
  334. );
  335. if (editFocused) break;
  336. }
  337. expect(editFocused).toBe(true);
  338. await browser.keys("Enter");
  339. const projectEditor = $('[role="dialog"][data-slot="dialog-content"]');
  340. await projectEditor.waitForDisplayed();
  341. expect(
  342. await projectEditor.$('[data-testid="virtual-project-root-name"]').getAttribute("title"),
  343. ).toBe(config.workspacePaths[0]);
  344. await capture("project-editor");
  345. await browser.keys("Escape");
  346. // Escape 关闭失败即终止此路径;不能用取消按钮替代被测键盘行为。
  347. await projectEditor.waitForDisplayed({ reverse: true });
  348. await activate(`${row} button[aria-label="更多"]`);
  349. await $('[role="menu"]').waitForDisplayed();
  350. await browser.keys("ArrowDown");
  351. expect(await browser.execute(() => document.activeElement?.getAttribute("role"))).toMatch(
  352. /^menuitem/,
  353. );
  354. await browser.keys("Escape");
  355. await $('[role="menu"]').waitForDisplayed({ reverse: true });
  356. // 新项目排序移动真实行,不再创建旧 WorkspaceDragOverlay;验证实际位移和设备标签。
  357. const dragSelector = `${row} [data-testid="virtual-project-toggle"]`;
  358. const deviceLabel = $(row).$('[data-testid="project-device"]');
  359. const deviceBeforeDrag = await deviceLabel.getText();
  360. const position = await startProjectPointerDrag(dragSelector);
  361. await browser.waitUntil(
  362. () =>
  363. browser.execute(
  364. (selector, top) =>
  365. Math.abs(document.querySelector(selector)!.getBoundingClientRect().top - top) >= 6,
  366. dragSelector,
  367. position.top,
  368. ),
  369. { timeout: 5000, timeoutMsg: "项目行未随拖拽移动" },
  370. );
  371. expect(await deviceLabel.isDisplayed()).toBe(true);
  372. expect(await deviceLabel.getText()).toBe(deviceBeforeDrag);
  373. expect(deviceBeforeDrag).not.toBe("");
  374. await browser.saveScreenshot(resolve(artifact, "drag-device.png"));
  375. await browser.keys("Escape");
  376. await browser.releaseActions();
  377. await browser.waitUntil(
  378. () =>
  379. browser.execute(
  380. (selector, top) =>
  381. Math.abs(document.querySelector(selector)!.getBoundingClientRect().top - top) < 1,
  382. dragSelector,
  383. position.top,
  384. ),
  385. { timeout: 5000, timeoutMsg: "取消拖拽后项目位置未恢复" },
  386. );
  387. await activate(`[data-testid="${TID_TASK_SETTINGS_BUTTON}"]`);
  388. const remoteNavigation = `[data-testid="${testId(TID_SETTINGS_SECTION_NAV, "remoteDevices")}"]`;
  389. await tabTo(remoteNavigation);
  390. expect(await $(remoteNavigation).getAttribute("data-settings-section-nav")).toBe(
  391. "remoteDevices",
  392. );
  393. expect(await browser.execute(() => document.activeElement!.matches(":focus-visible"))).toBe(
  394. true,
  395. );
  396. await browser.keys("Enter");
  397. await $("[data-source-server-card]").waitForDisplayed();
  398. // RDUX-13:键盘展开设备行,详情(日志等)在展开区。
  399. await activate("[data-source-server-card] [data-source-server-toggle]");
  400. expect(
  401. await $("[data-source-server-card] [data-source-server-toggle]").getAttribute(
  402. "aria-expanded",
  403. ),
  404. ).toBe("true");
  405. await activate("[data-source-server-card] button", "更多");
  406. await $("[data-device-info]").waitForDisplayed();
  407. await browser.keys("Escape");
  408. await $("[data-source-server-card] [data-source-server-log-toggle]").waitForDisplayed();
  409. await activate("[data-source-server-card] [data-source-server-log-toggle]");
  410. await $("[data-source-server-log-timestamp]").waitForDisplayed();
  411. await capture("settings");
  412. // 断开在「更多」菜单:键盘打开后焦点在首项「编辑」,下移到「断开」再确认。
  413. await activate("[data-source-server-card] button", "更多");
  414. await browser.keys("ArrowDown");
  415. expect(
  416. await browser.execute(
  417. () =>
  418. document.activeElement?.matches('[role="menuitem"]') &&
  419. document.activeElement.textContent?.trim().startsWith("断开"),
  420. ),
  421. ).toBe(true);
  422. await browser.keys("Enter");
  423. await $(
  424. '[data-source-server-card] [role="status"][data-remote-connection-status="offline"]',
  425. ).waitForDisplayed();
  426. await activate("[data-source-server-card] button", "连接");
  427. await $('[data-source-server-card] [data-remote-connection-status="online"]').waitForDisplayed({
  428. timeout: 120_000,
  429. });
  430. await $(dialog).waitForExist({ reverse: true });
  431. expect(await $('[data-testid="settings-page"]').isDisplayed()).toBe(true);
  432. expect(await $('[data-testid="ssh-success"]').isExisting()).toBe(false);
  433. await activate("[data-settings-content-frame] button", "新建连接");
  434. // RDUX-27:新建连接表单打开时焦点直接落在主机字段。
  435. await $(`${dialog} [data-testid="ssh-host-input"]`).waitForDisplayed();
  436. expect(await browser.execute(() => document.activeElement?.getAttribute("data-testid"))).toBe(
  437. "ssh-host-input",
  438. );
  439. await capture("selection");
  440. await activate('[data-testid="remote-kind-ssh"]');
  441. await tabTo(`${dialog} [data-testid="ssh-host-input"]`);
  442. await browser.keys("ArrowDown");
  443. await browser.keys("Enter");
  444. expect(await $(`${dialog} [data-testid="ssh-host-input"]`).getValue()).toBe(config.host);
  445. expect(await $(`${dialog} [data-testid="ssh-host-input"]`).getAttribute("aria-expanded")).toBe(
  446. "false",
  447. );
  448. await activate(`${dialog} button`, "关闭");
  449. await $(dialog).waitForDisplayed({ reverse: true });
  450. await activate(`[data-testid="${TID_SETTINGS_BACK_BUTTON}"]`);
  451. await tabTo(`${row} [data-testid="virtual-project-toggle"]`);
  452. await browser.keys("Enter");
  453. expect(await $(row).getAttribute("data-connection-state")).toBe("online");
  454. });
  455. });