conversation-session-ssh-remote-connection-management.test.ts 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411
  1. import { mkdir, readFile, writeFile } from "node:fs/promises";
  2. import { resolve } from "node:path";
  3. import { parseRemoteWorkspaceIdentity } from "@zcode/shared";
  4. import {
  5. TID_SETTINGS_BACK_BUTTON,
  6. TID_SETTINGS_PAGE,
  7. TID_SETTINGS_SECTION_NAV,
  8. TID_TASK_SETTINGS_BUTTON,
  9. TID_SSH_PORT_INPUT,
  10. TID_REMOTE_KIND_SSH,
  11. TID_CONFIRM_DIALOG_CONFIRM,
  12. testId,
  13. } from "@zcode/shared/test-ids";
  14. import {
  15. clearAppData,
  16. clickTestIdByDom,
  17. getE2EAppDataPaths,
  18. readSettings,
  19. } from "#e2e/helpers/desktop-app";
  20. import {
  21. disconnectRemoteSource,
  22. connectRemoteSourceFromSettings,
  23. selectRemoteDeviceMenuItem,
  24. requestRemoteProjectConnection,
  25. } from "#e2e/helpers/remote-project-actions";
  26. import { createStallableTcpProxy } from "#e2e/helpers/ssh-stallable-proxy";
  27. import {
  28. connectSSHWorkspace,
  29. openRemoteProjectSelection,
  30. fillSSHPasswordSettings,
  31. clickLastEnabledSSHDialogButton,
  32. waitForSSHDirectoryStep,
  33. selectSSHRemoteDirectory,
  34. readSSHRuntimeConfig,
  35. readRemoteTabSnapshot,
  36. runSSHCommand,
  37. waitForRemoteTab,
  38. } from "#e2e/helpers/ssh-remote-p0";
  39. import { prepareV4ConversationE2E } from "#e2e/helpers/v4-conversation";
  40. const MARKER = "E2E_SSH_CONNECTION_MANAGEMENT";
  41. const deviceName = "SSH guide device";
  42. const primaryName = "SSH guide primary";
  43. const scenario = process.env.R3_CONNECTION_MANAGEMENT_CASE ?? "edit";
  44. const artifactDir = resolve(
  45. process.env.ZCODE_E2E_ARTIFACT_DIR ?? ".e2e-artifacts/ssh-connection-management",
  46. );
  47. async function openSettings() {
  48. if (!(await $(`[data-testid="${TID_SETTINGS_PAGE}"]`).isDisplayed()))
  49. await clickTestIdByDom(TID_TASK_SETTINGS_BUTTON);
  50. await clickTestIdByDom(testId(TID_SETTINGS_SECTION_NAV, "remoteDevices"));
  51. }
  52. async function clickLabel(label: string, root = "[data-settings-content-frame]") {
  53. await browser.waitUntil(
  54. () =>
  55. browser.execute(
  56. (text, selector) => {
  57. const button = Array.from(
  58. document
  59. .querySelector(selector)
  60. ?.querySelectorAll<HTMLElement>('button, [role="menuitem"]') ?? [],
  61. ).find(
  62. (item) =>
  63. item.getClientRects().length &&
  64. item.textContent?.trim() === text &&
  65. !item.matches(":disabled"),
  66. );
  67. button?.click();
  68. return Boolean(button);
  69. },
  70. label,
  71. root,
  72. ),
  73. { timeout: 15_000, timeoutMsg: `${MARKER}: 缺少 ${label}` },
  74. );
  75. }
  76. async function clickLineAction(lineName: string, label: string) {
  77. await browser.waitUntil(
  78. () =>
  79. browser.execute(
  80. (name, text) => {
  81. const button = Array.from(
  82. document.querySelectorAll<HTMLButtonElement>("[data-settings-content-frame] button"),
  83. ).find((item) => {
  84. const line = item.closest("div.group\\/line") ?? item.parentElement;
  85. return (
  86. line?.textContent?.includes(name) &&
  87. (item.textContent?.trim() === text || item.getAttribute("aria-label") === text) &&
  88. !item.disabled
  89. );
  90. });
  91. button?.click();
  92. return Boolean(button);
  93. },
  94. lineName,
  95. label,
  96. ),
  97. { timeout: 15_000, timeoutMsg: `${MARKER}: ${lineName} 缺少 ${label}` },
  98. );
  99. }
  100. describe(`${MARKER}: 编辑、多连接默认值与移除`, () => {
  101. const facts: Record<string, unknown> = { scenario };
  102. let editedRoute: Awaited<ReturnType<typeof createStallableTcpProxy>> | undefined;
  103. after(async () => {
  104. await mkdir(artifactDir, { recursive: true });
  105. await writeFile(
  106. resolve(artifactDir, "connection-management.json"),
  107. JSON.stringify(facts, null, 2),
  108. );
  109. await editedRoute?.close();
  110. await browser.electron.restoreAllMocks();
  111. await clearAppData();
  112. });
  113. it(`SSH-GUIDE-MANAGE ${scenario}: 编辑重连或默认/移除的独立场景`, async function () {
  114. this.timeout(15 * 60_000);
  115. if (!["edit", "lifecycle"].includes(scenario)) throw new Error("未知设备管理场景");
  116. const config = readSSHRuntimeConfig(MARKER);
  117. await prepareV4ConversationE2E({ skipProvider: true });
  118. const first = await connectSSHWorkspace({
  119. caseMarker: MARKER,
  120. config,
  121. workspacePath: config.workspacePaths[0],
  122. });
  123. const second = await connectSSHWorkspace({
  124. caseMarker: MARKER,
  125. config,
  126. workspacePath: config.workspacePaths[1],
  127. });
  128. const sourceId = parseRemoteWorkspaceIdentity(first.workspaceIdentity!)?.sourceServerId;
  129. if (!sourceId) throw new Error("缺少设备身份");
  130. editedRoute = await createStallableTcpProxy(config);
  131. expect(
  132. (
  133. await runSSHCommand(
  134. config,
  135. `printf GUIDE_KEEP_REMOTE > '${config.workspacePaths[0]}/guide-remove-sentinel.txt'`,
  136. )
  137. ).code,
  138. ).toBe(0);
  139. await openSettings();
  140. // RDUX-13:编辑在设备行「更多」菜单里。
  141. await selectRemoteDeviceMenuItem(sourceId, ["编辑", "Edit"], MARKER);
  142. await $("#edit-connection-name").setValue(primaryName);
  143. await $("#edit-device-name").setValue(deviceName);
  144. if (scenario === "edit")
  145. await $(`[data-testid="${TID_SSH_PORT_INPUT}"]`).setValue(String(editedRoute.port));
  146. await clickLabel("保存更改", '[role="dialog"]');
  147. await $('[role="dialog"]').waitForDisplayed({ reverse: true });
  148. const savedProfile = (await readSettings()).connectionProfiles?.find(
  149. (profile) => profile.displayName === primaryName,
  150. );
  151. expect(savedProfile?.target.kind === "ssh" ? savedProfile.target.port : null).toBe(
  152. scenario === "edit" ? editedRoute.port : config.port,
  153. );
  154. facts.savedRoutePort = scenario === "edit" ? editedRoute.port : config.port;
  155. // 留空凭据后必须真实重连成功,单看保存反馈不能证明旧密码仍可用。
  156. await clickTestIdByDom(TID_SETTINGS_BACK_BUTTON);
  157. expect(
  158. (
  159. await waitForRemoteTab({
  160. caseMarker: MARKER,
  161. expectedIdentity: first.workspaceIdentity!,
  162. expectedPath: first.workspacePath!,
  163. requireActive: false,
  164. })
  165. ).remoteSessionId,
  166. ).toBe(first.remoteSessionId);
  167. expect(editedRoute.acceptedCount()).toBe(0);
  168. if (scenario === "edit") {
  169. await disconnectRemoteSource(sourceId, MARKER);
  170. // 断开按钮派发异步命令;必须等旧 attachment 释放,避免把旧在线 session 当重连成功。
  171. await browser.waitUntil(
  172. async () =>
  173. (await readRemoteTabSnapshot(first.workspaceIdentity!)).remoteSessionId === null,
  174. { timeout: 30_000 },
  175. );
  176. await requestRemoteProjectConnection(first.workspaceIdentity!, MARKER);
  177. await waitForRemoteTab({
  178. caseMarker: MARKER,
  179. expectedIdentity: first.workspaceIdentity!,
  180. expectedPath: first.workspacePath!,
  181. requireActive: false,
  182. });
  183. const restoredSibling = await waitForRemoteTab({
  184. caseMarker: MARKER,
  185. expectedIdentity: second.workspaceIdentity!,
  186. expectedPath: second.workspacePath!,
  187. requireActive: false,
  188. });
  189. expect(restoredSibling.remoteSessionId).not.toBe(second.remoteSessionId);
  190. // Tab 的旧线路是兼容历史的提示,不能当作物理连接事实;实际收到新端口连接才证明修改生效。
  191. expect(editedRoute.acceptedCount()).toBeGreaterThan(0);
  192. const reconnectedProfiles = (await readSettings()).connectionProfiles?.filter(
  193. (profile) => profile.sourceServerId === sourceId && profile.lifecycleState !== "retired",
  194. );
  195. // 旧 target 曾被 Host 当成新线路注册;恢复原项目必须继续使用编辑过的原 Profile。
  196. expect(reconnectedProfiles).toHaveLength(1);
  197. expect(reconnectedProfiles?.[0]?.profileId).toBe(savedProfile?.profileId);
  198. expect(reconnectedProfiles?.[0]?.target).toMatchObject({ port: editedRoute.port });
  199. facts.editedRouteAcceptedCount = editedRoute.acceptedCount();
  200. facts.profileCountAfterReconnect = reconnectedProfiles?.length;
  201. facts.siblingRestored = true;
  202. facts.editedConnectionWorkedWithRetainedPassword = true;
  203. return;
  204. }
  205. // 在线时重复旧 target 只是复用现有连接;先释放再用独立 Host alias 实际认证,才能构造第二线路。
  206. await disconnectRemoteSource(sourceId, MARKER);
  207. await browser.waitUntil(
  208. async () => (await readRemoteTabSnapshot(first.workspaceIdentity!)).remoteSessionId === null,
  209. { timeout: 30_000 },
  210. );
  211. await openRemoteProjectSelection();
  212. await clickTestIdByDom(TID_REMOTE_KIND_SSH);
  213. await fillSSHPasswordSettings({ ...config, host: "localhost" });
  214. await clickLastEnabledSSHDialogButton(MARKER);
  215. await waitForSSHDirectoryStep(MARKER);
  216. await selectSSHRemoteDirectory(config.workspacePaths[1], MARKER);
  217. await waitForRemoteTab({ caseMarker: MARKER, expectedPath: config.workspacePaths[1] });
  218. await browser.waitUntil(
  219. async () =>
  220. ((await readSettings()).connectionProfiles?.filter(
  221. (profile) => profile.sourceServerId === sourceId && profile.lifecycleState !== "retired",
  222. ).length ?? 0) === 2,
  223. { timeout: 30_000 },
  224. );
  225. const settings = await readSettings();
  226. const profiles =
  227. settings.connectionProfiles?.filter(
  228. (profile) => profile.sourceServerId === sourceId && profile.lifecycleState !== "retired",
  229. ) ?? [];
  230. expect(profiles).toHaveLength(2);
  231. const primary = profiles.find((profile) => profile.displayName === primaryName);
  232. const other = profiles.find((profile) => profile.profileId !== primary?.profileId);
  233. if (!primary || !other) throw new Error("两条连接未分别保留");
  234. const otherLabel =
  235. other.displayName ??
  236. (other.target.kind === "ssh" ? `${other.target.host}:${other.target.port}` : other.transport);
  237. expect(
  238. settings.sourceServers?.find((server) => server.sourceServerId === sourceId)
  239. ?.preferredProfileId,
  240. ).toBe(primary.profileId);
  241. await openSettings();
  242. // 保存线路默认折叠,展开后才有相应操作;不能把未展开的菜单当作按钮缺失。
  243. await browser.waitUntil(
  244. () =>
  245. browser.execute((id) => {
  246. const card = document.querySelector(`[data-source-server-card="${id}"]`);
  247. // RDUX-13:其他已保存连接在设备行展开区;先展开设备行。
  248. const toggle = card?.querySelector<HTMLElement>("[data-source-server-toggle]");
  249. if (toggle?.getAttribute("aria-expanded") === "false") {
  250. toggle.click();
  251. return false;
  252. }
  253. const button = card?.querySelector<HTMLButtonElement>(
  254. 'button[aria-label="其他已保存连接"]',
  255. );
  256. if (button?.getAttribute("aria-expanded") === "true") return true;
  257. button?.click();
  258. return Boolean(button);
  259. }, sourceId),
  260. { timeout: 15_000 },
  261. );
  262. await clickLineAction(otherLabel, "设为默认连接");
  263. await browser.waitUntil(
  264. async () =>
  265. (await readSettings()).sourceServers?.find((server) => server.sourceServerId === sourceId)
  266. ?.preferredProfileId === other.profileId,
  267. );
  268. expect(await $("[data-settings-content-frame]").getText()).toContain("默认");
  269. await browser.waitUntil(
  270. () =>
  271. browser.execute((id) => {
  272. const card = document.querySelector(`[data-source-server-card="${id}"]`);
  273. // RDUX-13:其他已保存连接在设备行展开区;先展开设备行。
  274. const toggle = card?.querySelector<HTMLElement>("[data-source-server-toggle]");
  275. if (toggle?.getAttribute("aria-expanded") === "false") {
  276. toggle.click();
  277. return false;
  278. }
  279. const button = card?.querySelector<HTMLButtonElement>(
  280. 'button[aria-label="其他已保存连接"]',
  281. );
  282. if (button?.getAttribute("aria-expanded") === "true") return true;
  283. button?.click();
  284. return Boolean(button);
  285. }, sourceId),
  286. { timeout: 15_000 },
  287. );
  288. await clickLabel("设为默认连接");
  289. await browser.waitUntil(
  290. async () =>
  291. (await readSettings()).sourceServers?.find((server) => server.sourceServerId === sourceId)
  292. ?.preferredProfileId === primary.profileId,
  293. );
  294. // 从设置按刚保存的默认线路重新连接,核验默认值实际生效,并让另一条线路成为可移除的保存线路。
  295. await clickTestIdByDom(TID_SETTINGS_BACK_BUTTON);
  296. await disconnectRemoteSource(sourceId, MARKER);
  297. await browser.waitUntil(
  298. async () => (await readRemoteTabSnapshot(first.workspaceIdentity!)).remoteSessionId === null,
  299. { timeout: 30_000 },
  300. );
  301. await connectRemoteSourceFromSettings(sourceId, MARKER);
  302. await waitForRemoteTab({
  303. caseMarker: MARKER,
  304. expectedIdentity: first.workspaceIdentity!,
  305. expectedPath: first.workspacePath!,
  306. requireActive: false,
  307. });
  308. const directoryStep = await waitForSSHDirectoryStep(MARKER);
  309. if (directoryStep === "directory") {
  310. // 设置页连接进入目录选择;先按当前用户流程关闭该屏,避免 DOM 点击穿透到被遮挡的设置页。
  311. await browser.waitUntil(
  312. () =>
  313. browser.execute(() => {
  314. const button = Array.from(
  315. document.querySelectorAll<HTMLButtonElement>('[data-testid="ssh-dialog"] button'),
  316. ).find((item) => /稍后选择|Choose later/iu.test(item.innerText) && !item.disabled);
  317. button?.click();
  318. return Boolean(button);
  319. }),
  320. { timeout: 15_000 },
  321. );
  322. await $('[data-testid="ssh-dialog"]').waitForDisplayed({ reverse: true, timeout: 15_000 });
  323. }
  324. await browser.waitUntil(
  325. () =>
  326. browser.execute((id) => {
  327. const card = document.querySelector(`[data-source-server-card="${id}"]`);
  328. // RDUX-13:其他已保存连接在设备行展开区;先展开设备行。
  329. const toggle = card?.querySelector<HTMLElement>("[data-source-server-toggle]");
  330. if (toggle?.getAttribute("aria-expanded") === "false") {
  331. toggle.click();
  332. return false;
  333. }
  334. const button = card?.querySelector<HTMLButtonElement>(
  335. 'button[aria-label="其他已保存连接"]',
  336. );
  337. if (button?.getAttribute("aria-expanded") === "true") return true;
  338. button?.click();
  339. return Boolean(button);
  340. }, sourceId),
  341. { timeout: 15_000 },
  342. );
  343. await clickLineAction(otherLabel, "移除连接");
  344. await clickTestIdByDom(TID_CONFIRM_DIALOG_CONFIRM);
  345. await browser.waitUntil(
  346. async () =>
  347. !(await readSettings()).connectionProfiles?.some(
  348. (profile) => profile.profileId === other.profileId,
  349. ),
  350. );
  351. expect(
  352. (await readSettings()).sourceServers?.some((server) => server.sourceServerId === sourceId),
  353. ).toBe(true);
  354. const primaryKey =
  355. primary.target.kind === "ssh" ? primary.target.passwordCredentialKey : undefined;
  356. const credentialsAfterLineRemoval = JSON.parse(
  357. await readFile(getE2EAppDataPaths().credentialsFile, "utf8"),
  358. );
  359. expect(Boolean(primaryKey && Object.hasOwn(credentialsAfterLineRemoval, primaryKey))).toBe(
  360. true,
  361. );
  362. facts.defaultAndRemoval = {
  363. retainedProfileId: primary.profileId,
  364. removedProfileId: other.profileId,
  365. };
  366. await $('[data-settings-content-frame] button[aria-label="更多"]').click();
  367. await clickLabel("移除设备", '[role="menu"]');
  368. const dialog = $('[role="dialog"]:has([data-testid="confirm-dialog-confirm"])');
  369. await dialog.waitForDisplayed();
  370. for (const path of config.workspacePaths) expect(await dialog.getText()).toContain(path);
  371. expect(await browser.execute(() => document.activeElement?.textContent)).toContain("取消");
  372. await browser.keys("Enter");
  373. await dialog.waitForDisplayed({ reverse: true });
  374. expect(
  375. (await readSettings()).sourceServers?.some((server) => server.sourceServerId === sourceId),
  376. ).toBe(true);
  377. await $('[data-settings-content-frame] button[aria-label="更多"]').click();
  378. await clickLabel("移除设备", '[role="menu"]');
  379. await clickTestIdByDom(TID_CONFIRM_DIALOG_CONFIRM);
  380. await browser.waitUntil(
  381. async () =>
  382. !(await readSettings()).sourceServers?.some((server) => server.sourceServerId === sourceId),
  383. );
  384. expect(
  385. (await readSettings()).connectionProfiles?.some(
  386. (profile) => profile.sourceServerId === sourceId,
  387. ),
  388. ).toBe(false);
  389. const credentialsAfterDeviceRemoval = JSON.parse(
  390. await readFile(getE2EAppDataPaths().credentialsFile, "utf8"),
  391. );
  392. expect(Boolean(primaryKey && Object.hasOwn(credentialsAfterDeviceRemoval, primaryKey))).toBe(
  393. false,
  394. );
  395. const remote = await runSSHCommand(
  396. config,
  397. `cat '${config.workspacePaths[0]}/guide-remove-sentinel.txt'; test -f "$HOME/.zcode/server/current.json"`,
  398. );
  399. expect(remote.code).toBe(0);
  400. expect(remote.stdout).toBe("GUIDE_KEEP_REMOTE");
  401. facts.remoteDataAndInstallationPreserved = true;
  402. });
  403. });