conversation-session-remote-device-search-list.test.ts 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250
  1. import { randomUUID } from "node:crypto";
  2. import { mkdir, writeFile } from "node:fs/promises";
  3. import { join, resolve } from "node:path";
  4. import {
  5. appSettingsSchema,
  6. buildServerRemoteWorkspaceIdentity,
  7. parseRemoteWorkspaceIdentity,
  8. type SourceServerRecord,
  9. } from "@zcode/shared";
  10. import { clearAppData, getE2EAppDataPaths, readSettings } from "#e2e/helpers/desktop-app";
  11. import { reloadElectronSessionPreservingBrowserProfile } from "#e2e/helpers/e2e-electron-reload";
  12. import {
  13. openRemoteDevicesSettings,
  14. waitForDeviceStatus,
  15. } from "#e2e/helpers/remote-project-actions";
  16. import { connectSSHWorkspace, readSSHRuntimeConfig } from "#e2e/helpers/ssh-remote-p0";
  17. import { waitForRendererAfterColdRestart } from "#e2e/helpers/ssh-remote-lifecycle";
  18. import { prepareV4ConversationE2E } from "#e2e/helpers/v4-conversation";
  19. const MARKER = "E2E_REMOTE_DEVICE_SEARCH_LIST";
  20. const artifactDir = resolve(process.env.ZCODE_E2E_ARTIFACT_DIR!, "remote-device-search-list");
  21. const LIST = "[data-source-server-device-list]";
  22. async function deviceIds(): Promise<string[]> {
  23. return browser.execute(
  24. (selector) =>
  25. [...document.querySelectorAll<HTMLElement>(`${selector} [data-source-server-card]`)].map(
  26. (row) => row.dataset.sourceServerCard!,
  27. ),
  28. LIST,
  29. );
  30. }
  31. async function search(query: string, expected: string[]): Promise<void> {
  32. const input = $('input[placeholder="搜索设备名、地址或项目"]');
  33. // 清空走产品实际按钮,不能用 WebDriver 的空 setValue 代替 React 受控输入的清空动作。
  34. if (query === "") await $('button[aria-label="清空搜索"]').click();
  35. else await input.setValue(query);
  36. expect(await input.getValue()).toBe(query);
  37. await browser.waitUntil(
  38. async () => JSON.stringify(await deviceIds()) === JSON.stringify(expected),
  39. {
  40. timeout: 15_000,
  41. timeoutMsg: `${MARKER}: 搜索 ${query} 的设备集合不正确`,
  42. },
  43. );
  44. }
  45. describe("RDUX-13-LIST-01:多设备列表搜索、展开与稳定排序", () => {
  46. after(async () => {
  47. await clearAppData();
  48. });
  49. it("17 条设备记录可搜索,同面板顺序冻结、连接重入后按最近使用排序", async function () {
  50. this.timeout(15 * 60_000);
  51. await mkdir(artifactDir, { recursive: true });
  52. await prepareV4ConversationE2E({ skipProvider: true });
  53. const config = readSSHRuntimeConfig(MARKER);
  54. const connected = await connectSSHWorkspace({
  55. caseMarker: MARKER,
  56. config,
  57. workspacePath: config.workspacePaths[0],
  58. });
  59. const realId = parseRemoteWorkspaceIdentity(connected.workspaceIdentity!)?.sourceServerId;
  60. expect(realId).toBeTruthy();
  61. const settings = await readSettings();
  62. const realServer = settings.sourceServers?.find((item) => item.sourceServerId === realId);
  63. const realProfile = settings.connectionProfiles?.find((item) => item.sourceServerId === realId);
  64. if (!realServer || !realProfile) throw new Error("缺少真实连接持久化记录");
  65. const baseTime = Date.now() - 30_000;
  66. const fixtures = Array.from({ length: 16 }, (_, index) => {
  67. const number = index + 1;
  68. const id = randomUUID();
  69. const profileId = randomUUID();
  70. const path = `/srv/project-needle-${number}`;
  71. const identity = buildServerRemoteWorkspaceIdentity({ serverId: id, workspacePath: path });
  72. return {
  73. id,
  74. server: {
  75. ...realServer,
  76. sourceServerId: id,
  77. displayName: `Rack ${number}`,
  78. hostname: `host-${number}`,
  79. preferredProfileId: profileId,
  80. lastOnlineAt: baseTime + number,
  81. declaredWorkspaces: [
  82. { workspacePath: path, workspaceIdentity: identity, label: `Project ${number}` },
  83. ],
  84. } satisfies SourceServerRecord,
  85. profile: {
  86. ...realProfile,
  87. profileId,
  88. sourceServerId: id,
  89. displayName: `fixture-${number}`,
  90. createdAt: baseTime + number,
  91. lastConnectedAt: baseTime + number,
  92. target: {
  93. ...realProfile.target,
  94. host: `address-${number}.example.test`,
  95. passwordCredentialKey: undefined,
  96. },
  97. },
  98. history: {
  99. workspacePath: path,
  100. workspaceIdentity: identity,
  101. profileId,
  102. sourceServerId: id,
  103. lastOpenedAt: baseTime + number,
  104. },
  105. };
  106. });
  107. // 先走生产 schema,缺必填字段时在当前进程失败,不能把无效夹具写入后再误判冷恢复。
  108. const fixtureSettings = appSettingsSchema.parse({
  109. ...settings,
  110. remoteStartupAutoReconnectEnabled: false,
  111. lastActiveWorkspace: undefined,
  112. lastActiveTabIndex: 0,
  113. lastWorkspaceSession: settings.lastWorkspaceSession?.filter(
  114. (entry) => entry.kind === "local",
  115. ),
  116. sourceServers: [
  117. { ...realServer, displayName: "Actual SSH device", lastOnlineAt: baseTime - 1000 },
  118. ...fixtures.map((item) => item.server),
  119. ],
  120. connectionProfiles: [
  121. { ...realProfile, lastConnectedAt: baseTime - 1000 },
  122. ...fixtures.map((item) => item.profile),
  123. ],
  124. sourceServerWorkspaceHistory: [
  125. ...(settings.sourceServerWorkspaceHistory ?? []).map((entry) => ({
  126. ...entry,
  127. lastOpenedAt: baseTime - 1000,
  128. })),
  129. ...fixtures.map((item) => item.history),
  130. ],
  131. });
  132. // 夹具只在 Main/Host 完整退出后写入,再由正常冷启动读取,避免覆盖活跃 owner 的状态。
  133. await reloadElectronSessionPreservingBrowserProfile(browser, {
  134. afterElectronProcessExit: async () => {
  135. const paths = getE2EAppDataPaths();
  136. await writeFile(join(paths.appDataDir, "setting.json"), JSON.stringify(fixtureSettings));
  137. },
  138. });
  139. await waitForRendererAfterColdRestart(MARKER);
  140. await openRemoteDevicesSettings();
  141. await browser.waitUntil(async () => (await deviceIds()).length === 17, { timeout: 30_000 });
  142. const order = await deviceIds();
  143. const expectedOrder: string[] = [...fixtures].reverse().map((item) => item.id);
  144. expectedOrder.push(realId!);
  145. expect(order).toEqual(expectedOrder);
  146. expect(
  147. await browser.execute(
  148. (selector) =>
  149. [...document.querySelectorAll(`${selector} [data-source-server-toggle]`)].every(
  150. (item) => item.getAttribute("aria-expanded") === "false",
  151. ),
  152. LIST,
  153. ),
  154. ).toBe(true);
  155. await search("rack 7", [fixtures[6]!.id]);
  156. await search(" RACK 7 ", [fixtures[6]!.id]);
  157. await search("host-12", [fixtures[11]!.id]);
  158. await search("address-9.example.test", [fixtures[8]!.id]);
  159. await search("Project 14", [fixtures[13]!.id]);
  160. await search("missing-device", []);
  161. await search("", order);
  162. const first = $(`[data-source-server-card="${order[0]}"] [data-source-server-toggle]`);
  163. const second = $(`[data-source-server-card="${order[1]}"] [data-source-server-toggle]`);
  164. await first.click();
  165. await second.click();
  166. expect(await first.getAttribute("aria-expanded")).toBe("true");
  167. expect(await second.getAttribute("aria-expanded")).toBe("true");
  168. await first.click();
  169. await second.click();
  170. const listBeforeConnect = (await $(LIST)).elementId;
  171. await $(`[data-source-server-card="${realId}"]`).$("button=连接").click();
  172. await waitForDeviceStatus(realId!, "online", MARKER, 120_000);
  173. await browser.waitUntil(
  174. () =>
  175. browser.execute((selector) => {
  176. const list = document.querySelector(selector);
  177. return (
  178. Boolean(list) &&
  179. !document.querySelector('[data-testid="ssh-dialog"]') &&
  180. list?.closest("[aria-busy]")?.getAttribute("aria-busy") !== "true"
  181. );
  182. }, LIST),
  183. { timeout: 30_000, timeoutMsg: `${MARKER}: 连接后的列表操作未结束` },
  184. );
  185. await browser.executeAsync((done) =>
  186. requestAnimationFrame(() => requestAnimationFrame(() => done())),
  187. );
  188. const panelRecreatedAfterConnect = (await $(LIST)).elementId !== listBeforeConnect;
  189. const orderAfterConnect = await deviceIds();
  190. // 冻结只作用于同一面板;连接向导返回并定位设备会重建面板,按合同重新计算最近使用顺序。
  191. if (panelRecreatedAfterConnect) {
  192. expect(orderAfterConnect).toEqual([realId, ...order.filter((id) => id !== realId)]);
  193. expect(
  194. await $(`[data-source-server-card="${realId}"] [data-source-server-toggle]`).getAttribute(
  195. "aria-expanded",
  196. ),
  197. ).toBe("true");
  198. } else expect(orderAfterConnect).toEqual(order);
  199. await writeFile(
  200. resolve(artifactDir, "facts.json"),
  201. JSON.stringify(
  202. {
  203. realSource: realId,
  204. fixtureCount: 16,
  205. order,
  206. searchFields: ["name", "hostname", "address", "project"],
  207. panelRecreatedAfterConnect,
  208. orderAfterConnect,
  209. orderMatchedPanelContract: true,
  210. },
  211. null,
  212. 2,
  213. ),
  214. );
  215. await $(LIST).scrollIntoView({ block: "start" });
  216. for (const locale of ["zh-CN", "en-US"]) {
  217. for (const theme of ["light", "dark"]) {
  218. await browser.execute(
  219. (lang, appearance) => {
  220. const actions = (
  221. window as Window & {
  222. __testActions?: { setLocale(value: string): void; setTheme(value: string): void };
  223. }
  224. ).__testActions;
  225. actions?.setLocale(lang);
  226. actions?.setTheme(appearance);
  227. },
  228. locale,
  229. theme,
  230. );
  231. for (const width of [1440, 700]) {
  232. await browser.electron.execute((electron, width) => {
  233. electron.BrowserWindow.getAllWindows()
  234. .find((window) => window.isVisible())
  235. ?.setSize(width, 900);
  236. }, width);
  237. await browser.executeAsync((done) =>
  238. requestAnimationFrame(() => requestAnimationFrame(() => done())),
  239. );
  240. await browser.saveScreenshot(resolve(artifactDir, `${locale}-${theme}-${width}.png`));
  241. }
  242. }
  243. }
  244. });
  245. });