conversation-session-settings-connection-completion.test.ts 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696
  1. import { mkdir, writeFile } from "node:fs/promises";
  2. import { resolve } from "node:path";
  3. import { parseRemoteWorkspaceIdentity, ServiceChannels } from "@zcode/shared";
  4. import {
  5. TID_DOCKER_CONTAINER_INPUT,
  6. TID_CONFIRM_DIALOG_CONFIRM,
  7. TID_REMOTE_KIND_DOCKER,
  8. TID_REMOTE_KIND_SSH,
  9. TID_SETTINGS_PAGE,
  10. TID_SETTINGS_BACK_BUTTON,
  11. TID_SETTINGS_SECTION_NAV,
  12. TID_SSH_DIALOG,
  13. TID_SSH_HOST_INPUT,
  14. TID_SSH_PASSWORD_INPUT,
  15. TID_SSH_CONFIG_ALIAS_CHIP,
  16. TID_SSH_CONFIG_IMPORT,
  17. TID_REMOTE_NEW_CONNECTION_PREVIEW,
  18. TID_SSH_PORT_INPUT,
  19. TID_SSH_USERNAME_INPUT,
  20. TID_DOCKER_CONTAINER_SELECT,
  21. TID_SSH_SUCCESS,
  22. TID_TASK_SETTINGS_BUTTON,
  23. testId,
  24. } from "@zcode/shared/test-ids";
  25. import {
  26. installHandoffRpcProbe,
  27. callHandoffHost,
  28. restoreHandoffProbes,
  29. } from "#e2e/helpers/remote-project-handoff-probe";
  30. import type { RemoteProjectDirectory } from "@zcode/services";
  31. import { clearAppData, clickTestIdByDom } from "#e2e/helpers/desktop-app";
  32. import {
  33. requestRemoteProjectConnection,
  34. selectRemoteDeviceMenuItem,
  35. } from "#e2e/helpers/remote-project-actions";
  36. import { prepareV4ConversationE2E } from "#e2e/helpers/v4-conversation";
  37. import {
  38. clickLastEnabledSSHDialogButton,
  39. fillSSHPasswordSettings,
  40. readSSHRuntimeConfig,
  41. createFirstConnectionStallingSSHProxy,
  42. connectSSHWorkspace,
  43. waitForRemoteTab,
  44. waitForSSHError,
  45. waitForSSHDirectoryStep,
  46. } from "#e2e/helpers/ssh-remote-p0";
  47. const marker = "E2E_SETTINGS_CONNECTION_COMPLETION";
  48. async function dialogTop() {
  49. return browser.execute(
  50. () =>
  51. document
  52. .querySelector('[data-testid="ssh-dialog"]')
  53. ?.closest('[role="dialog"]')
  54. ?.getBoundingClientRect().top ?? null,
  55. );
  56. }
  57. /** 用真实 ClipboardEvent 模拟粘贴,覆盖主机框的 onPaste 拆分(RDUX-27)。 */
  58. async function pasteIntoHost(text: string) {
  59. return browser.execute(
  60. (hostTestId, value) => {
  61. const host = document.querySelector<HTMLInputElement>(`[data-testid="${hostTestId}"]`)!;
  62. host.focus();
  63. const clipboardData = new DataTransfer();
  64. clipboardData.setData("text/plain", value);
  65. const event = new ClipboardEvent("paste", { clipboardData, bubbles: true, cancelable: true });
  66. host.dispatchEvent(event);
  67. return event.defaultPrevented;
  68. },
  69. TID_SSH_HOST_INPUT,
  70. text,
  71. );
  72. }
  73. async function measureAddingForm() {
  74. return browser.execute(() => {
  75. const submit = document
  76. .querySelector('[data-testid="ssh-dialog"] button[type="submit"]')
  77. ?.getBoundingClientRect();
  78. const dialogElement = document
  79. .querySelector('[data-testid="ssh-dialog"]')
  80. ?.closest('[role="dialog"]');
  81. const dialog = dialogElement?.getBoundingClientRect();
  82. const scroll = document.querySelector('[data-testid="remote-connection-settings-scroll"]');
  83. return {
  84. viewport: { width: innerWidth, height: innerHeight },
  85. dialog: dialog?.toJSON(),
  86. transition: dialogElement
  87. ? {
  88. property: getComputedStyle(dialogElement).transitionProperty,
  89. duration: getComputedStyle(dialogElement).transitionDuration,
  90. animations: dialogElement.getAnimations({ subtree: true }).map((animation) => ({
  91. playState: animation.playState,
  92. duration: animation.effect?.getComputedTiming().duration,
  93. iterations: animation.effect?.getComputedTiming().iterations,
  94. })),
  95. }
  96. : null,
  97. submit: submit?.toJSON(),
  98. scroll: scroll
  99. ? {
  100. bounds: scroll.getBoundingClientRect().toJSON(),
  101. contentHeight: scroll.scrollHeight,
  102. clientHeight: scroll.clientHeight,
  103. }
  104. : null,
  105. visible: Boolean(
  106. submit && submit.width > 0 && submit.right <= innerWidth && submit.bottom <= innerHeight,
  107. ),
  108. };
  109. });
  110. }
  111. async function captureAddingForms(kind: string) {
  112. const artifacts = resolve(process.env.ZCODE_E2E_ARTIFACT_DIR!);
  113. await mkdir(artifacts, { recursive: true });
  114. for (const locale of ["zh-CN", "en-US"]) {
  115. for (const theme of ["light", "dark"]) {
  116. await browser.execute(
  117. (language, color) => {
  118. const actions = (
  119. window as Window & {
  120. __testActions?: {
  121. setLocale(locale: string): void;
  122. setTheme(theme: string): void;
  123. };
  124. }
  125. ).__testActions;
  126. actions?.setLocale(language);
  127. actions?.setTheme(color);
  128. },
  129. locale,
  130. theme,
  131. );
  132. for (const width of [1440, 480]) {
  133. await browser.electron.execute((electron, size) => {
  134. electron.BrowserWindow.getAllWindows()
  135. .find((window) => window.isVisible())
  136. ?.setSize(size, 900);
  137. }, width);
  138. const beforeLayout = await measureAddingForm();
  139. // 等待 resize 的布局帧,不用超时猜测 DOM 已更新。
  140. await browser.executeAsync((done) =>
  141. requestAnimationFrame(() => requestAnimationFrame(() => done())),
  142. );
  143. // 尺寸过渡可能长于两帧,等待浏览器动画完成事件,不能把中间宽度当成稳定布局。
  144. await browser.executeAsync((done) => {
  145. const dialog = document
  146. .querySelector('[data-testid="ssh-dialog"]')
  147. ?.closest('[role="dialog"]');
  148. const animations = (dialog?.getAnimations({ subtree: true }) ?? []).filter(
  149. (animation) =>
  150. animation.playState === "running" &&
  151. animation.effect?.getComputedTiming().iterations !== Infinity,
  152. );
  153. void Promise.all(
  154. animations.map((animation) => animation.finished.catch(() => undefined)),
  155. ).then(() => requestAnimationFrame(() => done()));
  156. });
  157. const afterLayout = await measureAddingForm();
  158. await browser.saveScreenshot(
  159. resolve(artifacts, `adding-${kind}-${locale}-${theme}-${width}.png`),
  160. );
  161. await writeFile(
  162. resolve(artifacts, `adding-${kind}-${locale}-${theme}-${width}.json`),
  163. JSON.stringify({ beforeLayout, afterLayout }),
  164. );
  165. expect(afterLayout.visible).toBe(true);
  166. }
  167. }
  168. }
  169. await browser.electron.execute((electron) => {
  170. electron.BrowserWindow.getAllWindows()
  171. .find((window) => window.isVisible())
  172. ?.setSize(1440, 900);
  173. });
  174. await browser.execute(() =>
  175. (
  176. window as Window & { __testActions?: { setLocale(locale: string): void } }
  177. ).__testActions?.setLocale("zh-CN"),
  178. );
  179. }
  180. const settingsContent = "[data-settings-content-frame]";
  181. /** RDUX-13:断开在设备行「更多」菜单里;未指定时取唯一的设备行。 */
  182. async function disconnectDevice(sourceId?: string) {
  183. const id =
  184. sourceId ?? (await $("[data-source-server-card]").getAttribute("data-source-server-card"));
  185. if (!id) throw new Error(`${marker}: 缺少设备行`);
  186. await selectRemoteDeviceMenuItem(id, ["断开", "Disconnect"], marker);
  187. }
  188. async function clickButton(label: string, scope = settingsContent) {
  189. const button = $(scope).$(`.//button[normalize-space(.)=${JSON.stringify(label)}]`);
  190. await button.waitForClickable({ timeout: 20_000 });
  191. await button.click();
  192. }
  193. async function counts() {
  194. const localProjects = await callHandoffHost<unknown[]>(ServiceChannels.Project, "readProjects");
  195. const directory = await callHandoffHost<RemoteProjectDirectory>(
  196. ServiceChannels.RemoteProjects,
  197. "readDirectory",
  198. );
  199. const workspaceScopes = await browser.execute(() => {
  200. const store = (
  201. window as Window & {
  202. __zcodeTabStoreE2E?: {
  203. getState(): {
  204. tabs: Array<{ type: string; workspacePath?: string; workspaceIdentity?: string }>;
  205. };
  206. };
  207. }
  208. ).__zcodeTabStoreE2E;
  209. if (!store) throw new Error("E2E tab store unavailable");
  210. return store
  211. .getState()
  212. .tabs.filter((tab) => tab.type === "workspace" && tab.workspacePath)
  213. .map((tab) => ({
  214. workspacePath: tab.workspacePath!,
  215. workspaceIdentity: tab.workspaceIdentity,
  216. }));
  217. });
  218. const tasks = await callHandoffHost<{ total: number }>(
  219. ServiceChannels.WindowController,
  220. "listTaskList",
  221. [{ kind: "timeline", workspaceScopes, sortBy: "updated" }],
  222. );
  223. return { projects: localProjects.length + directory.entries.length, tasks: tasks.total };
  224. }
  225. async function openSettings() {
  226. await ensureSettingsSidebar();
  227. await clickTestIdByDom(TID_TASK_SETTINGS_BUTTON);
  228. await clickTestIdByDom(testId(TID_SETTINGS_SECTION_NAV, "remoteDevices"));
  229. }
  230. async function ensureSettingsSidebar() {
  231. if (!(await $(`[data-testid="${TID_TASK_SETTINGS_BUTTON}"]`).isDisplayed())) {
  232. // 窄屏截图会收起工作区侧栏,恢复窗口宽度并不自动展开;通过真实按钮恢复入口。
  233. await $('button[aria-label="Toggle sidebar"], button[aria-label="切换侧边栏"]').click();
  234. }
  235. await $(`[data-testid="${TID_TASK_SETTINGS_BUTTON}"]`).waitForDisplayed();
  236. }
  237. async function expectDeviceCompletion(before: Awaited<ReturnType<typeof counts>>, devices = 1) {
  238. expect(await waitForSSHDirectoryStep(marker)).toBe("closed");
  239. await $(`[data-testid="${TID_SETTINGS_PAGE}"]`).waitForDisplayed();
  240. await $("[data-source-server-card] [data-remote-connection-status=online]").waitForExist({
  241. timeout: 30_000,
  242. });
  243. expect(await $$('[data-testid="virtual-project-name"]').length).toBe(0);
  244. expect(await $$(`[data-testid="${TID_SSH_SUCCESS}"]`).length).toBe(0);
  245. expect(await $$("[data-source-server-card]").length).toBe(devices);
  246. // RDUX-13:完成后定位到设备行:焦点在设备名按钮上,该行展开并高亮。
  247. expect(
  248. await browser.execute(() => {
  249. const toggle = document.activeElement;
  250. return (
  251. toggle?.matches("[data-source-server-card] [data-source-server-toggle]") === true &&
  252. toggle.getAttribute("aria-expanded") === "true" &&
  253. toggle.closest("[data-source-server-card]")?.hasAttribute("data-highlighted") === true
  254. );
  255. }),
  256. ).toBe(true);
  257. // 设置页卸载项目树;返回侧栏,并通过真实 Host 服务核对持久化项目与任务数量。
  258. await clickTestIdByDom(TID_SETTINGS_BACK_BUTTON);
  259. await ensureSettingsSidebar();
  260. const after = await counts();
  261. expect(after).toEqual(before);
  262. await openSettings();
  263. return after;
  264. }
  265. let settingsE2EPrepared = false;
  266. /** 同一 spec 只准备一次 App;单独筛选运行某个场景时也能自行完成准备。 */
  267. async function prepareSettingsE2E() {
  268. if (settingsE2EPrepared) return;
  269. await prepareV4ConversationE2E({ skipProvider: true });
  270. await browser.execute(() => {
  271. (
  272. window as Window & { __testActions?: { setLocale(locale: string): void } }
  273. ).__testActions?.setLocale("zh-CN");
  274. });
  275. await installHandoffRpcProbe();
  276. settingsE2EPrepared = true;
  277. }
  278. /** 编辑连接弹窗以「保存更改」按钮定位,避免和向导弹窗混淆。 */
  279. const editConnectionDialog = '//div[@role="dialog"][.//button[normalize-space(.)="保存更改"]]';
  280. async function replaceInputValue(selector: string, value: string) {
  281. const input = $(selector);
  282. await input.click();
  283. await browser.keys([process.platform === "darwin" ? "Meta" : "Control", "a"]);
  284. await browser.keys("Backspace");
  285. if (value) await input.addValue(value);
  286. }
  287. describe(`${marker}: 设置内连接独立完成`, () => {
  288. after(async () => {
  289. await restoreHandoffProbes();
  290. await browser.electron.restoreAllMocks();
  291. await clearAppData();
  292. });
  293. it("RDUX15-10/18/21 SSH 添加、普通重连与在线复用、Docker 添加保持设置和项目数量", async function () {
  294. this.timeout(15 * 60_000);
  295. const config = readSSHRuntimeConfig(marker);
  296. const container = process.env.ZCODE_E2E_SSH_CONTAINER;
  297. if (!container) throw new Error(`${marker}: ZCODE_E2E_SSH_CONTAINER required`);
  298. const home = process.env.ZCODE_E2E_HOME_DIR;
  299. if (!home) throw new Error("isolated E2E home required");
  300. await mkdir(resolve(home, ".ssh"), { recursive: true });
  301. await writeFile(
  302. resolve(home, ".ssh", "config"),
  303. [
  304. "Host e2e-device-addition",
  305. ` HostName ${config.host}`,
  306. ` Port ${config.port}`,
  307. ` User ${config.username}`,
  308. "",
  309. ].join("\n"),
  310. );
  311. await prepareSettingsE2E();
  312. const before = await counts();
  313. await openSettings();
  314. await clickButton("新建连接");
  315. // 设置新建直接是默认 SSH 表单;不得先出现已保存设备统一列表。
  316. await $(
  317. `[data-testid="${TID_SSH_DIALOG}"] [data-testid="${TID_SSH_HOST_INPUT}"]`,
  318. ).waitForDisplayed();
  319. // RDUX-27:设置入口没有步骤条和说明句,焦点在主机,头部显示目标占位。
  320. expect(await browser.execute(() => document.activeElement?.getAttribute("data-testid"))).toBe(
  321. TID_SSH_HOST_INPUT,
  322. );
  323. expect(await $(`[data-testid="${TID_SSH_DIALOG}"] nav`).isExisting()).toBe(false);
  324. expect(await $(`[data-testid="${TID_REMOTE_NEW_CONNECTION_PREVIEW}"]`).getText()).toBe(
  325. "user@host:22",
  326. );
  327. // 空表单提交:错误在字段下方、焦点回到主机,不发起连接。
  328. await $('[data-testid="ssh-dialog"] button[type="submit"]').click();
  329. await browser.waitUntil(
  330. async () =>
  331. (await $(`[data-testid="${TID_SSH_HOST_INPUT}"]`).getAttribute("aria-invalid")) === "true",
  332. { timeout: 5_000, timeoutMsg: `${marker}: 主机未标记为错误` },
  333. );
  334. const hostErrorId = await $(`[data-testid="${TID_SSH_HOST_INPUT}"]`).getAttribute(
  335. "aria-describedby",
  336. );
  337. expect(await $(`[id="${hostErrorId}"]`).getText()).toBe("请输入主机");
  338. expect(await browser.execute(() => document.activeElement?.getAttribute("data-testid"))).toBe(
  339. TID_SSH_HOST_INPUT,
  340. );
  341. expect(await $$("[data-source-server-card]").length).toBe(0);
  342. expect(await $(`[data-testid="${TID_REMOTE_KIND_SSH}"]`).getAttribute("aria-pressed")).toBe(
  343. "true",
  344. );
  345. expect(await $(`[data-testid="${TID_REMOTE_KIND_DOCKER}"]`).isDisplayed()).toBe(true);
  346. // 分类切换使用真实 Tab / Enter;焦点可见,选择不会触发连接。
  347. for (const kindId of [TID_REMOTE_KIND_DOCKER, TID_REMOTE_KIND_SSH]) {
  348. for (let step = 0; step < 30; step += 1) {
  349. if (
  350. await browser.execute(
  351. (id) => document.activeElement?.getAttribute("data-testid") === id,
  352. kindId,
  353. )
  354. )
  355. break;
  356. await browser.keys("Tab");
  357. }
  358. expect(
  359. await browser.execute(
  360. (id) => document.activeElement?.getAttribute("data-testid") === id,
  361. kindId,
  362. ),
  363. ).toBe(true);
  364. // 全局样式已禁用 focus outline(2bb283f474),这里改为确认处于键盘可见焦点态,
  365. // 分段控件在该状态下用背景提示焦点。
  366. expect(await browser.execute(() => document.activeElement!.matches(":focus-visible"))).toBe(
  367. true,
  368. );
  369. await browser.keys("Enter");
  370. expect(await $(`[data-testid="${kindId}"]`).getAttribute("aria-pressed")).toBe("true");
  371. expect(await $$("[data-source-server-card]").length).toBe(0);
  372. }
  373. expect(await $('[data-testid="remote-kind-wsl"]').isExisting()).toBe(
  374. process.platform === "win32",
  375. );
  376. await $(`[data-testid="${TID_SSH_CONFIG_IMPORT}"]`).waitForEnabled({ timeout: 30_000 });
  377. await $(`[data-testid="${TID_SSH_CONFIG_IMPORT}"]`).click();
  378. const alias = $("//*[@cmdk-item and .//*[normalize-space(.)='e2e-device-addition']]");
  379. // 候选仍走真实本机 SSH config 发现;选中后不拨号。
  380. await alias.waitForDisplayed();
  381. await alias.click();
  382. expect(await $(`[data-testid="${TID_SSH_HOST_INPUT}"]`).getValue()).toBe(config.host);
  383. expect(await $(`[data-testid="${TID_SSH_CONFIG_ALIAS_CHIP}"]`).getText()).toContain(
  384. "已关联 Host e2e-device-addition",
  385. );
  386. expect(await $(`[data-testid="${TID_REMOTE_NEW_CONNECTION_PREVIEW}"]`).getText()).toBe(
  387. `${config.username}@${config.host}:${config.port}`,
  388. );
  389. // config Host 未提供私钥,导入后焦点移到第一个空必填项:密码。
  390. expect(await browser.execute(() => document.activeElement?.getAttribute("data-testid"))).toBe(
  391. TID_SSH_PASSWORD_INPUT,
  392. );
  393. expect(await $$("[data-source-server-card]").length).toBe(0);
  394. // 切换认证方式会改变表单高度,弹窗上边缘保持不动。
  395. const topBeforeAuthSwitch = await dialogTop();
  396. await $('[data-testid="ssh-auth-private-key"]').click();
  397. expect(await dialogTop()).toBe(topBeforeAuthSwitch);
  398. await $('[data-testid="ssh-auth-password"]').click();
  399. expect(await dialogTop()).toBe(topBeforeAuthSwitch);
  400. await captureAddingForms("ssh");
  401. await $(`[data-testid="${TID_SSH_PASSWORD_INPUT}"]`).setValue(`${config.password}-wrong`);
  402. await clickLastEnabledSSHDialogButton(marker);
  403. await waitForSSHError(marker, 90_000);
  404. expect(await $$("[data-source-server-card]").length).toBe(0);
  405. // 认证失败不能声称凭据已保存;修正同一表单后沿原连接流程重试。
  406. expect(await $('[data-testid="ssh-error"]').getText()).not.toContain("凭据已保存");
  407. await clickButton("返回配置", '[data-testid="ssh-dialog"]');
  408. await $(`[data-testid="${TID_SSH_PASSWORD_INPUT}"]`).setValue(config.password);
  409. expect(await $('[data-testid="ssh-dialog"] button[type="submit"]').getText()).toBe(
  410. "添加并连接",
  411. );
  412. await clickLastEnabledSSHDialogButton(marker);
  413. const afterSSH = await expectDeviceCompletion(before);
  414. // 普通断开/重连必须复用已保存 Profile,不能自动打开目录或项目编辑器。
  415. await disconnectDevice();
  416. await $("[data-source-server-card] [data-remote-connection-status=offline]").waitForExist();
  417. await clickButton("连接");
  418. const afterReconnect = await expectDeviceCompletion(before);
  419. // alias 与手填可以形成不同 Profile;第二条线路用真实凭据识别同一 Source,不新增设备。
  420. await clickButton("新建连接");
  421. await clickTestIdByDom(TID_REMOTE_KIND_SSH);
  422. // 粘贴 user@host:port 一次拆出三个字段(RDUX-27);不匹配的文本按原样粘贴。
  423. expect(await pasteIntoHost(`${config.username}@${config.host}:${config.port}`)).toBe(true);
  424. expect(await $(`[data-testid="${TID_SSH_HOST_INPUT}"]`).getValue()).toBe(config.host);
  425. expect(await $(`[data-testid="${TID_SSH_USERNAME_INPUT}"]`).getValue()).toBe(config.username);
  426. expect(await $(`[data-testid="${TID_SSH_PORT_INPUT}"]`).getValue()).toBe(String(config.port));
  427. expect(await $(`[data-testid="${TID_SSH_DIALOG}"]`).getText()).toContain(
  428. `已识别 ${config.username}@${config.host}:${config.port}`,
  429. );
  430. expect(await browser.execute(() => document.activeElement?.getAttribute("data-testid"))).toBe(
  431. TID_SSH_PASSWORD_INPUT,
  432. );
  433. expect(await pasteIntoHost(config.host)).toBe(false);
  434. await fillSSHPasswordSettings(config);
  435. await clickLastEnabledSSHDialogButton(marker);
  436. await expectDeviceCompletion(before);
  437. // 已识别的同一手填线路再次复用,不使用新密码认证,也不能新增设备或项目。
  438. await clickButton("新建连接");
  439. await fillSSHPasswordSettings({ ...config, password: "unused-reuse-password" });
  440. await clickLastEnabledSSHDialogButton(marker);
  441. const afterReuse = await expectDeviceCompletion(before);
  442. // Docker 默认进入 root,和 SSH 的 dev 是独立数据环境;两台设备均留在设置管理。
  443. await clickButton("新建连接");
  444. await clickTestIdByDom(TID_REMOTE_KIND_DOCKER);
  445. await clickButton("选择运行中的容器", '[data-testid="ssh-dialog"]');
  446. // Docker 类型切换使用类型色;说明段已删除,限制提示放在选择器下方。
  447. expect(await $(`[data-testid="${TID_REMOTE_KIND_DOCKER}"]`).getAttribute("class")).toContain(
  448. "bg-remote-docker-surface",
  449. );
  450. expect(await $(`[data-testid="${TID_SSH_DIALOG}"]`).getText()).not.toContain(
  451. "连接本机 Docker 容器。",
  452. );
  453. await $(`[data-testid="${TID_DOCKER_CONTAINER_SELECT}"]`).click();
  454. const dockerOption = $(
  455. `//*[@cmdk-item and .//*[normalize-space(.)=${JSON.stringify(container)}]]`,
  456. );
  457. await dockerOption.waitForDisplayed();
  458. await dockerOption.click();
  459. expect(await $$("[data-source-server-card]").length).toBe(1);
  460. await captureAddingForms("docker");
  461. await clickLastEnabledSSHDialogButton(marker);
  462. const afterDocker = await expectDeviceCompletion(before, 2);
  463. await clickButton("新建连接");
  464. await clickTestIdByDom(TID_REMOTE_KIND_DOCKER);
  465. await $(`[data-testid="${TID_DOCKER_CONTAINER_INPUT}"]`).setValue(container);
  466. await clickLastEnabledSSHDialogButton(marker);
  467. await expectDeviceCompletion(before, 2);
  468. const stalled = await createFirstConnectionStallingSSHProxy(config, marker);
  469. try {
  470. await clickButton("新建连接");
  471. await clickTestIdByDom(TID_REMOTE_KIND_SSH);
  472. await fillSSHPasswordSettings({ ...config, host: "127.0.0.1", port: stalled.port });
  473. await clickLastEnabledSSHDialogButton(marker);
  474. await stalled.firstConnectionAccepted;
  475. await browser.keys("Escape");
  476. await clickTestIdByDom(TID_CONFIRM_DIALOG_CONFIRM);
  477. await stalled.waitForFirstConnectionClosed();
  478. await $(`[data-testid="${TID_SSH_DIALOG}"]`).waitForExist({ reverse: true });
  479. await $("[data-source-server-card] [data-remote-connection-status=online]").waitForExist();
  480. expect(await $$("[data-source-server-card]").length).toBe(2);
  481. await clickTestIdByDom(TID_SETTINGS_BACK_BUTTON);
  482. expect(await counts()).toEqual(before);
  483. await openSettings();
  484. } finally {
  485. await stalled.close();
  486. }
  487. await $("[data-source-server-card]").moveTo();
  488. await browser.waitUntil(
  489. async () => !(await $("body").getText()).includes("已直接使用现有连接"),
  490. { timeout: 15_000, timeoutMsg: "复用提示未收起" },
  491. );
  492. const artifacts = resolve(process.env.ZCODE_E2E_ARTIFACT_DIR!);
  493. await mkdir(artifacts, { recursive: true });
  494. for (const locale of ["zh-CN", "en-US"]) {
  495. for (const theme of ["light", "dark"]) {
  496. await browser.execute(
  497. (language, color) => {
  498. const actions = (
  499. window as Window & {
  500. __testActions?: { setLocale(locale: string): void; setTheme(theme: string): void };
  501. }
  502. ).__testActions;
  503. actions?.setLocale(language);
  504. actions?.setTheme(color);
  505. },
  506. locale,
  507. theme,
  508. );
  509. for (const width of [1440, 480]) {
  510. await browser.electron.execute((electron, size) => {
  511. electron.BrowserWindow.getAllWindows()
  512. .find((window) => window.isVisible())
  513. ?.setSize(size, 900);
  514. }, width);
  515. await browser.saveScreenshot(
  516. resolve(artifacts, `settings-${locale}-${theme}-${width}.png`),
  517. );
  518. }
  519. }
  520. }
  521. await writeFile(
  522. resolve(artifacts, "settings-completion-facts.json"),
  523. JSON.stringify(
  524. {
  525. before,
  526. afterSSH,
  527. afterReconnect,
  528. afterDocker,
  529. afterReuse,
  530. transports: ["ssh", "docker"],
  531. dialogClosed: !(await $(`[data-testid="${TID_SSH_DIALOG}"]`).isExisting()),
  532. },
  533. null,
  534. 2,
  535. ),
  536. );
  537. });
  538. it("RDUX15-22 侧栏明确连接原项目,在重连后保留原 identity 和项目数量", async function () {
  539. this.timeout(10 * 60_000);
  540. const config = readSSHRuntimeConfig(marker);
  541. await browser.electron.execute((electron) =>
  542. electron.BrowserWindow.getAllWindows()
  543. .find((window) => window.isVisible())
  544. ?.setSize(1440, 900),
  545. );
  546. await browser.execute(() =>
  547. (
  548. window as Window & { __testActions?: { setLocale(locale: string): void } }
  549. ).__testActions?.setLocale("zh-CN"),
  550. );
  551. // 前一场景失败时也先通过真实关闭操作释放表单,避免级联前置失败掩盖本场景结果。
  552. if (await $(`[data-testid="${TID_SSH_DIALOG}"]`).isExisting()) {
  553. await clickButton("关闭", '[data-testid="ssh-dialog"]');
  554. if (await $(`[data-testid="${TID_CONFIRM_DIALOG_CONFIRM}"]`).isExisting()) {
  555. await clickTestIdByDom(TID_CONFIRM_DIALOG_CONFIRM);
  556. }
  557. await $(`[data-testid="${TID_SSH_DIALOG}"]`).waitForExist({ reverse: true });
  558. }
  559. if (await $(`[data-testid="${TID_SETTINGS_PAGE}"]`).isExisting()) {
  560. await clickTestIdByDom(TID_SETTINGS_BACK_BUTTON);
  561. }
  562. await ensureSettingsSidebar();
  563. const original = await connectSSHWorkspace({
  564. config,
  565. workspacePath: config.workspacePaths[0],
  566. caseMarker: marker,
  567. });
  568. const before = await counts();
  569. await openSettings();
  570. // 设备按最近使用排序,可能存在多台设备;按原项目所属 Source 断开。
  571. const originalSourceId = parseRemoteWorkspaceIdentity(
  572. original.workspaceIdentity!,
  573. )?.sourceServerId;
  574. if (!originalSourceId) throw new Error(`${marker}: 缺少原项目设备身份`);
  575. await disconnectDevice(originalSourceId);
  576. await $(
  577. `[data-source-server-card="${originalSourceId}"] [data-remote-connection-status=offline]`,
  578. ).waitForExist();
  579. await clickTestIdByDom(TID_SETTINGS_BACK_BUTTON);
  580. await requestRemoteProjectConnection(original.workspaceIdentity!, marker);
  581. await waitForSSHDirectoryStep(marker);
  582. const restored = await waitForRemoteTab({
  583. caseMarker: marker,
  584. expectedIdentity: original.workspaceIdentity!,
  585. expectedPath: config.workspacePaths[0],
  586. });
  587. expect(restored.workspaceIdentity).toBe(original.workspaceIdentity);
  588. expect(await $$("[data-testid=virtual-project-name]").length).toBe(0);
  589. expect(await counts()).toEqual(before);
  590. });
  591. it("RDUX27-1 修改主机入口:校验失败时焦点落在真正出错的字段", async function () {
  592. this.timeout(10 * 60_000);
  593. const config = readSSHRuntimeConfig(marker);
  594. await prepareSettingsE2E();
  595. if (await $(`[data-testid="${TID_SSH_DIALOG}"]`).isExisting()) {
  596. await clickButton("关闭", '[data-testid="ssh-dialog"]');
  597. if (await $(`[data-testid="${TID_CONFIRM_DIALOG_CONFIRM}"]`).isExisting()) {
  598. await clickTestIdByDom(TID_CONFIRM_DIALOG_CONFIRM);
  599. }
  600. await $(`[data-testid="${TID_SSH_DIALOG}"]`).waitForExist({ reverse: true });
  601. }
  602. if (!(await $(`[data-testid="${TID_SETTINGS_PAGE}"]`).isExisting())) await openSettings();
  603. // 手填真实 SSH 线路;已存在同一线路时复用,不影响本场景。
  604. await clickButton("新建连接");
  605. await fillSSHPasswordSettings(config);
  606. await clickLastEnabledSSHDialogButton(marker);
  607. // 首次连接全新容器会经过安装确认,由共享 helper 处理到设置内完成(弹窗关闭)。
  608. expect(await waitForSSHDirectoryStep(marker)).toBe("closed");
  609. const card = $(
  610. `//*[@data-source-server-card][.//*[@data-remote-connection-status]][contains(normalize-space(.), ${JSON.stringify(config.host)})]`,
  611. );
  612. await card.waitForExist({ timeout: 30_000 });
  613. const cardSourceId = await card.getAttribute("data-source-server-card");
  614. if (!cardSourceId) throw new Error(`${marker}: 缺少设备行`);
  615. await disconnectDevice(cardSourceId);
  616. await card.$('[data-remote-connection-status="offline"]').waitForExist({ timeout: 30_000 });
  617. // 主机改成不可解析的 .invalid 域名,连接后由真实 ENOTFOUND 给出「修改主机」操作。
  618. const missingHost = "zcode-e2e-missing.invalid";
  619. await selectRemoteDeviceMenuItem(cardSourceId, ["编辑", "Edit"], marker);
  620. await $(editConnectionDialog).waitForDisplayed();
  621. await replaceInputValue(
  622. `${editConnectionDialog}//*[@data-testid="${TID_SSH_HOST_INPUT}"]`,
  623. missingHost,
  624. );
  625. await $(editConnectionDialog).$('.//button[normalize-space(.)="保存更改"]').click();
  626. await $(editConnectionDialog).waitForExist({ reverse: true });
  627. const missingCard = $(
  628. `//*[@data-source-server-card][contains(normalize-space(.), ${JSON.stringify(missingHost)})]`,
  629. );
  630. await missingCard.waitForExist({ timeout: 30_000 });
  631. await missingCard.$('.//button[normalize-space(.)="连接"]').click();
  632. const editHost = missingCard.$('.//button[normalize-space(.)="修改主机"]');
  633. // 设置内连接会打开向导展示失败;关闭向导后回到卡片,用卡片的「修改主机」进入编辑弹窗。
  634. await $(`[data-testid="${TID_SSH_DIALOG}"]`).waitForExist({ timeout: 30_000 });
  635. await $(`[data-testid="${TID_SSH_DIALOG}"]`)
  636. .$('.//*[contains(normalize-space(.), "找不到主机")]')
  637. .waitForExist({ timeout: 120_000 });
  638. await clickButton("关闭", '[data-testid="ssh-dialog"]');
  639. if (await $(`[data-testid="${TID_CONFIRM_DIALOG_CONFIRM}"]`).isExisting()) {
  640. await clickTestIdByDom(TID_CONFIRM_DIALOG_CONFIRM);
  641. }
  642. await $(`[data-testid="${TID_SSH_DIALOG}"]`).waitForExist({ reverse: true });
  643. await editHost.waitForClickable({ timeout: 30_000 });
  644. await editHost.click();
  645. await $(editConnectionDialog).waitForDisplayed();
  646. // 入口把主机标为待修改;用户名才是本次真正的校验错误,焦点必须给用户名。
  647. const username = `${editConnectionDialog}//*[@data-testid="${TID_SSH_USERNAME_INPUT}"]`;
  648. await replaceInputValue(username, "");
  649. await $(editConnectionDialog).$('.//button[normalize-space(.)="保存更改"]').click();
  650. await browser.waitUntil(
  651. async () => (await $(username).getAttribute("aria-invalid")) === "true",
  652. { timeout: 5_000, timeoutMsg: `${marker}: 用户名未标记为错误` },
  653. );
  654. const usernameErrorId = await $(username).getAttribute("aria-describedby");
  655. expect(await $(`[id="${usernameErrorId}"]`).getText()).toBe("请输入用户名");
  656. expect(await browser.execute(() => document.activeElement?.getAttribute("data-testid"))).toBe(
  657. TID_SSH_USERNAME_INPUT,
  658. );
  659. await browser.saveScreenshot(
  660. resolve(process.env.ZCODE_E2E_ARTIFACT_DIR!, "edit-host-validation-focus.png"),
  661. );
  662. // 恢复真实线路,保存成功后弹窗关闭。
  663. await replaceInputValue(username, config.username);
  664. await replaceInputValue(
  665. `${editConnectionDialog}//*[@data-testid="${TID_SSH_HOST_INPUT}"]`,
  666. config.host,
  667. );
  668. await $(editConnectionDialog).$('.//button[normalize-space(.)="保存更改"]').click();
  669. await $(editConnectionDialog).waitForExist({ reverse: true });
  670. });
  671. });