conversation-session-ssh-remote-three-screen.test.ts 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254
  1. import { mkdir, writeFile, rm, readFile } from "node:fs/promises";
  2. import { dirname, join, resolve } from "node:path";
  3. import { createServer, type Socket } from "node:net";
  4. import { TID_TASK_SETTINGS_BUTTON, TID_SETTINGS_SECTION_NAV, testId } from "@zcode/shared/test-ids";
  5. import {
  6. DEFAULT_WORKSPACE,
  7. clearAppData,
  8. readSettings,
  9. clickTestIdByDom,
  10. } from "#e2e/helpers/desktop-app";
  11. import { prepareV4ConversationE2E } from "#e2e/helpers/v4-conversation";
  12. import { selectRemoteDeviceMenuItem } from "#e2e/helpers/remote-project-actions";
  13. import {
  14. prepareSSHConnectionPage,
  15. openRemoteConnectionSelection as openSelection,
  16. readSSHRuntimeConfig,
  17. fillSSHPasswordSettings,
  18. clickLastEnabledSSHDialogButton,
  19. waitForSSHDirectoryStep,
  20. } from "#e2e/helpers/ssh-remote-p0";
  21. const MARKER = "E2E_SSH_THREE_SCREEN";
  22. const alias = "rdux10-first-connect";
  23. const artifactDir = resolve(process.env.ZCODE_E2E_ARTIFACT_DIR ?? ".e2e-artifacts/three-screen");
  24. async function clickButton(text: string) {
  25. await browser.waitUntil(
  26. () =>
  27. browser.execute((label) => {
  28. const button = Array.from(
  29. document.querySelectorAll<HTMLButtonElement>('[data-testid="ssh-dialog"] button'),
  30. ).find(
  31. (item) =>
  32. item.getClientRects().length &&
  33. !item.disabled &&
  34. (item.textContent?.includes(label) || item.getAttribute("aria-label") === label),
  35. );
  36. if (!button) return false;
  37. button.click();
  38. return true;
  39. }, text),
  40. { timeout: 30_000, timeoutMsg: `${MARKER}: missing action ${text}` },
  41. );
  42. }
  43. async function capture(name: string) {
  44. await mkdir(artifactDir, { recursive: true });
  45. for (const theme of ["light", "dark"]) {
  46. await browser.execute((value) => {
  47. const actions = (window as Window & { __testActions?: { setTheme(value: string): void } })
  48. .__testActions;
  49. if (!actions) throw new Error("Missing theme test actions");
  50. actions.setTheme(value);
  51. }, theme);
  52. for (const width of [1440, 900]) {
  53. await browser.electron.execute((electron, size) => {
  54. electron.BrowserWindow.getAllWindows()
  55. .find((window) => !window.isDestroyed())
  56. ?.setSize(size, 900);
  57. }, width);
  58. await browser.executeAsync((done) =>
  59. requestAnimationFrame(() => requestAnimationFrame(() => done())),
  60. );
  61. await browser.saveScreenshot(join(artifactDir, `${name}-${theme}-${width}.png`));
  62. const overflow = await browser.execute(() => {
  63. const dialog = document.querySelector<HTMLElement>('[data-testid="ssh-dialog"]');
  64. return Boolean(
  65. dialog &&
  66. (dialog.scrollWidth > dialog.clientWidth + 1 ||
  67. dialog.getBoundingClientRect().bottom > innerHeight),
  68. );
  69. });
  70. expect(overflow).toBe(false);
  71. }
  72. }
  73. }
  74. describe(`${MARKER}: 设置分类添加与连接反馈`, () => {
  75. after(async () => {
  76. await browser.electron.restoreAllMocks();
  77. await clearAppData();
  78. });
  79. it("RDUX-10-01/03/04 首次添加、离线重连、收起失败与关闭草稿", async function () {
  80. this.timeout(20 * 60_000);
  81. const config = readSSHRuntimeConfig(MARKER);
  82. await prepareSSHConnectionPage(MARKER);
  83. await prepareV4ConversationE2E({ skipProvider: true });
  84. const sshDir = join(dirname(DEFAULT_WORKSPACE), ".ssh");
  85. const configPath = join(sshDir, "config");
  86. await mkdir(sshDir, { recursive: true });
  87. await writeFile(
  88. configPath,
  89. `Host ${alias}\n HostName ${config.host}\n Port ${config.port}\n User ${config.username}\n`,
  90. { mode: 0o600 },
  91. );
  92. const sockets = new Set<Socket>();
  93. let acceptedConnections = 0;
  94. const pendingServer = createServer((socket) => {
  95. acceptedConnections += 1;
  96. sockets.add(socket);
  97. socket.on("error", () => undefined);
  98. socket.on("close", () => sockets.delete(socket));
  99. });
  100. try {
  101. await openSelection();
  102. await capture("selection");
  103. await browser.execute(() => {
  104. const counts = { clicks: 0, inputs: [] as string[] };
  105. (window as Window & { __wizardCounts?: typeof counts }).__wizardCounts = counts;
  106. document.addEventListener("click", (event) => {
  107. if ((event.target as Element)?.closest('[data-testid="ssh-dialog"] button'))
  108. counts.clicks += 1;
  109. });
  110. document.addEventListener("input", (event) => {
  111. const element = event.target as HTMLInputElement;
  112. if (!element.closest('[data-testid="ssh-dialog"]')) return;
  113. const id = element.dataset.testid || element.name || element.type;
  114. if (!counts.inputs.includes(id)) counts.inputs.push(id);
  115. });
  116. });
  117. await $('[data-testid="remote-ssh-config-import"]').waitForEnabled({ timeout: 30_000 });
  118. await $('[data-testid="remote-ssh-config-import"]').click();
  119. await $(`//*[@cmdk-item and .//*[normalize-space(.)=${JSON.stringify(alias)}]]`).click();
  120. await $('[data-testid="ssh-dialog"] input[type="password"]').setValue(config.password);
  121. await clickLastEnabledSSHDialogButton(MARKER);
  122. await browser.waitUntil(
  123. () =>
  124. browser.execute(() =>
  125. Array.from(
  126. document.querySelectorAll<HTMLButtonElement>('[data-testid="ssh-dialog"] button'),
  127. ).some((button) => /安装并继续|Install and continue/u.test(button.textContent ?? "")),
  128. ),
  129. { timeout: 60_000, timeoutMsg: `${MARKER}: 首装 fixture 未出现安装确认` },
  130. );
  131. const releaseVersion = (
  132. JSON.parse(
  133. // 按当前 spec 位置读取仓库版本,不能沿用 pending 的目录深度。
  134. await readFile(new URL("../../../../../../../package.json", import.meta.url), "utf8"),
  135. ) as { version: string }
  136. ).version;
  137. expect(await $('[data-testid="remote-install-version"]').getText()).toBe(releaseVersion);
  138. expect(await $('[data-testid="remote-install-path"]').getText()).toBe(
  139. `/home/${config.username}/.zcode/server`,
  140. );
  141. expect(
  142. await browser.execute(() =>
  143. Boolean(document.querySelector('[data-testid="remote-install-path"]')?.closest("li")),
  144. ),
  145. ).toBe(true);
  146. expect(await $('[data-testid="remote-connection-log"]').isExisting()).toBe(false);
  147. await capture("install-confirmation");
  148. expect(await waitForSSHDirectoryStep(MARKER)).toBe("closed");
  149. expect(await $('[data-testid="settings-page"]').isDisplayed()).toBe(true);
  150. expect(await $$('[data-testid="virtual-project-name"]').length).toBe(0);
  151. await capture("device-added");
  152. const counts = await browser.execute(
  153. () =>
  154. (window as Window & { __wizardCounts?: { clicks: number; inputs: string[] } })
  155. .__wizardCounts,
  156. );
  157. await writeFile(
  158. join(artifactDir, "first-connect-actions.json"),
  159. JSON.stringify(counts, null, 2),
  160. );
  161. const settings = await readSettings();
  162. const profile = settings.connectionProfiles?.find(
  163. (item) => item.target.kind === "ssh" && item.target.sshConfigAlias === alias,
  164. );
  165. if (!profile?.sourceServerId) throw new Error(`${MARKER}: missing saved Source`);
  166. // 通用项目 helper 断开后会返回侧栏;本场景留在设置,按 Source 设备行完成断开与状态断言。
  167. const deviceCard = $(`[data-source-server-card="${profile.sourceServerId}"]`);
  168. await selectRemoteDeviceMenuItem(profile.sourceServerId, ["断开", "Disconnect"], MARKER);
  169. await deviceCard.$('[data-remote-connection-status="offline"]').waitForExist();
  170. await openSelection();
  171. await $('[data-testid="remote-ssh-config-import"]').waitForEnabled({ timeout: 30_000 });
  172. await $('[data-testid="remote-ssh-config-import"]').click();
  173. await $(`//*[@cmdk-item and .//*[normalize-space(.)=${JSON.stringify(alias)}]]`).click();
  174. await $('[data-testid="ssh-password-input"]').setValue(config.password);
  175. await clickLastEnabledSSHDialogButton(MARKER);
  176. expect(await waitForSSHDirectoryStep(MARKER)).toBe("closed");
  177. expect(await $$("[data-source-server-card]").length).toBe(1);
  178. await capture("device-reconnected");
  179. await new Promise<void>((yes, no) => {
  180. pendingServer.once("error", no);
  181. pendingServer.listen(0, "127.0.0.1", yes);
  182. });
  183. const address = pendingServer.address();
  184. if (!address || typeof address === "string") throw new Error("Missing test port");
  185. await openSelection();
  186. await $('[data-testid="remote-kind-ssh"]').click();
  187. await capture("new-ssh");
  188. await fillSSHPasswordSettings({ ...config, host: "127.0.0.1", port: address.port });
  189. await clickLastEnabledSSHDialogButton(MARKER);
  190. await browser.waitUntil(() => sockets.size > 0, { timeout: 15_000 });
  191. await clickButton("收起");
  192. // 缺陷原因:进度卡已迁到设置,旧用例离开设置后仍等侧栏卡会永久超时。
  193. // 先验证后台不抢项目页,再由用户返回设置查看同一连接。
  194. await $('[data-testid="settings-back-button"]').click();
  195. await $('[data-testid="project-section"]').waitForDisplayed();
  196. await $('[data-testid="ssh-dialog"]').waitForExist({ reverse: true });
  197. expect(await $('[data-testid="remote-connection-minimized"]').isDisplayed()).toBe(false);
  198. await clickTestIdByDom(TID_TASK_SETTINGS_BUTTON);
  199. await clickTestIdByDom(testId(TID_SETTINGS_SECTION_NAV, "remoteDevices"));
  200. await $('[data-testid="remote-connection-minimized"]').waitForDisplayed();
  201. expect(await $('[data-testid="remote-connection-minimized"]').getText()).toContain(
  202. `127.0.0.1:${address.port}`,
  203. );
  204. for (const socket of sockets) socket.destroy();
  205. await browser.waitUntil(
  206. async () =>
  207. /失败|failed/iu.test(await $('[data-testid="remote-connection-minimized"]').getText()),
  208. { timeout: 60_000 },
  209. );
  210. // 收起的退出动画会短暂保留 DOM;等待卸载后再验证后台失败没有重新打开。
  211. await $('[data-testid="ssh-dialog"]').waitForExist({ reverse: true, timeout: 5000 });
  212. await capture("minimized-failure");
  213. const connectionsBeforeReview = acceptedConnections;
  214. await $('[data-testid="remote-connection-minimized"]').click();
  215. await $('[data-testid="ssh-error"]').waitForDisplayed();
  216. expect(acceptedConnections).toBe(connectionsBeforeReview);
  217. const failureActions = await browser.execute(() =>
  218. Array.from(
  219. document.querySelectorAll<HTMLButtonElement>('[data-testid="ssh-dialog"] button'),
  220. ).map((button) => button.textContent?.trim() ?? ""),
  221. );
  222. expect(failureActions).toContain("新建连接");
  223. expect(failureActions).not.toContain("取消连接");
  224. // 查看保留 A 的失败;先显式取消 A,再发起 B,不能用新入口静默覆盖后台操作。
  225. await clickButton("收起");
  226. await $("[data-background-connection]")
  227. .$('.//button[normalize-space(.)="取消此连接"]')
  228. .click();
  229. await $('[data-testid="remote-connection-minimized"]').waitForExist({ reverse: true });
  230. await openSelection();
  231. await $('[data-testid="ssh-host-input"]').waitForDisplayed();
  232. expect(await $('[data-testid="ssh-error"]').isExisting()).toBe(false);
  233. await fillSSHPasswordSettings(config);
  234. await clickLastEnabledSSHDialogButton(MARKER);
  235. expect(await waitForSSHDirectoryStep(MARKER)).toBe("closed");
  236. await capture("new-intent-device-complete");
  237. await openSelection();
  238. await $('[data-testid="remote-kind-ssh"]').click();
  239. expect(await $('[data-testid="ssh-host-input"]').getValue()).toBe("");
  240. expect(await $('[data-testid="ssh-port-input"]').getValue()).toBe("22");
  241. expect(await $('[data-testid="ssh-password-input"]').getValue()).toBe("");
  242. await clickButton("关闭");
  243. } finally {
  244. for (const socket of sockets) socket.destroy();
  245. if (pendingServer.listening)
  246. await new Promise<void>((yes) => pendingServer.close(() => yes()));
  247. await rm(configPath, { force: true });
  248. }
  249. });
  250. });