conversation-session-remote-device-cards.test.ts 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364
  1. import { mkdir } from "node:fs/promises";
  2. import { resolve } from "node:path";
  3. import { createServer } from "node:net";
  4. import { buildRemoteHostWorkspaceIdentity, ServiceChannels } from "@zcode/shared";
  5. import type { RemoteProjectDirectory } from "@zcode/services";
  6. import { callHandoffHost, installHandoffRpcProbe } from "#e2e/helpers/remote-project-handoff-probe";
  7. import {
  8. TID_CONFIRM_DIALOG_CONFIRM,
  9. TID_REMOTE_KIND_SSH,
  10. TID_TASK_SETTINGS_BUTTON,
  11. TID_SETTINGS_SECTION_NAV,
  12. testId,
  13. } from "@zcode/shared/test-ids";
  14. import { clearAppData, clickTestIdByDom, waitForWorkspaceApp } from "#e2e/helpers/desktop-app";
  15. import { prepareV4ConversationE2E } from "#e2e/helpers/v4-conversation";
  16. import { selectTaskOrganizeMode } from "#e2e/helpers/workspace-agent-warmup";
  17. import {
  18. clickLastEnabledSSHDialogButton,
  19. fillSSHPasswordSettings,
  20. openSSHRemoteDialog,
  21. readSSHRuntimeConfig,
  22. prepareSSHConnectionPage,
  23. selectSSHRemoteDirectory,
  24. waitForSSHDirectoryStep,
  25. waitForSSHError,
  26. waitForRemoteTab,
  27. } from "#e2e/helpers/ssh-remote-p0";
  28. const CASE_MARKER = "E2E_REMOTE_DEVICE_CARDS";
  29. async function button(text: string, selector = "[data-settings-content-frame]") {
  30. await browser.waitUntil(
  31. async () =>
  32. browser.execute(
  33. (label, root) => {
  34. const found = [
  35. ...(document.querySelector(root)?.querySelectorAll<HTMLButtonElement>("button") ?? []),
  36. ].find(
  37. (item) =>
  38. (item.textContent?.trim() === label || item.getAttribute("aria-label") === label) &&
  39. !item.disabled,
  40. );
  41. found?.click();
  42. return Boolean(found);
  43. },
  44. text,
  45. selector,
  46. ),
  47. { timeout: 10_000, timeoutMsg: `Missing ${text}` },
  48. );
  49. }
  50. async function settings() {
  51. await clickTestIdByDom(TID_TASK_SETTINGS_BUTTON);
  52. await clickTestIdByDom(testId(TID_SETTINGS_SECTION_NAV, "remoteDevices"));
  53. }
  54. /** RDUX-13:设备默认收起成一行;连接、项目、日志等详情在展开区。 */
  55. async function expandDevice() {
  56. const toggle = $("[data-source-server-card] [data-source-server-toggle]");
  57. await toggle.waitForDisplayed();
  58. if ((await toggle.getAttribute("aria-expanded")) !== "true") await toggle.click();
  59. await $("[data-source-server-card] [data-device-details]").waitForDisplayed();
  60. }
  61. async function deviceMenuTexts(): Promise<string[]> {
  62. await $('[data-source-server-card] button[aria-label="更多"]').click();
  63. await $("[data-device-info]").waitForDisplayed({ timeout: 5000 });
  64. return browser.execute(() =>
  65. [...document.querySelectorAll('[role="menuitem"]')].map(
  66. (item) => item.textContent?.trim() ?? "",
  67. ),
  68. );
  69. }
  70. async function selectDeviceMenuItem(prefix: string) {
  71. await $('[data-source-server-card] button[aria-label="更多"]').click();
  72. await browser.waitUntil(
  73. () =>
  74. browser.execute((label) => {
  75. const item = [...document.querySelectorAll<HTMLElement>('[role="menuitem"]')].find(
  76. (candidate) =>
  77. candidate.textContent?.trim().startsWith(label) &&
  78. !candidate.hasAttribute("data-disabled"),
  79. );
  80. item?.click();
  81. return Boolean(item);
  82. }, prefix),
  83. { timeout: 10_000, timeoutMsg: `Missing menu item ${prefix}` },
  84. );
  85. }
  86. describe(`${CASE_MARKER}: 设置设备列表与未完成连接`, () => {
  87. after(async () => {
  88. await browser.electron.restoreAllMocks();
  89. await clearAppData();
  90. });
  91. it("RDUX-13 真实设备行展开、搜索、菜单与定位高亮,失败连接隔离,项目可打开,主题与窄屏", async function () {
  92. this.timeout(15 * 60_000);
  93. const config = readSSHRuntimeConfig(CASE_MARKER);
  94. await prepareSSHConnectionPage(CASE_MARKER);
  95. await prepareV4ConversationE2E({ skipProvider: true });
  96. await openSSHRemoteDialog(CASE_MARKER);
  97. await fillSSHPasswordSettings(config);
  98. await clickLastEnabledSSHDialogButton(CASE_MARKER);
  99. await waitForSSHDirectoryStep(CASE_MARKER);
  100. await selectSSHRemoteDirectory(config.workspacePaths[0], CASE_MARKER);
  101. await waitForWorkspaceApp(config.workspacePaths[0], 120_000);
  102. await installHandoffRpcProbe();
  103. const originalDirectory = await callHandoffHost<RemoteProjectDirectory>(
  104. ServiceChannels.RemoteProjects,
  105. "readDirectory",
  106. );
  107. const original = originalDirectory.entries.find((entry) =>
  108. entry.roots.some((root) => root.rootPath === config.workspacePaths[0]),
  109. );
  110. if (!original?.projectId) throw new Error(`${CASE_MARKER}: 缺少原项目身份`);
  111. const identity = buildRemoteHostWorkspaceIdentity(original.hostId, config.workspacePaths[0]);
  112. const openRecentProject = async (cachedProjectId: string | null) => {
  113. // 模拟旧版本缺少草稿范围或同目录残留其他项目;最近项目必须由 Host 入口决定归属。
  114. await browser.execute(
  115. (identity, hostId, projectId) => {
  116. const key = `zcode-composer-workspace-scope:v1:${JSON.stringify(["desktop", identity])}`;
  117. if (projectId === null) localStorage.removeItem(key);
  118. else
  119. localStorage.setItem(
  120. key,
  121. JSON.stringify({ clientNamespace: "desktop", hostId, projectId }),
  122. );
  123. },
  124. identity,
  125. original.hostId,
  126. cachedProjectId,
  127. );
  128. await $("[data-device-project]").click();
  129. await browser.waitUntil(
  130. async () => {
  131. // 旧断言反而等待创建器,掩盖了已保存项目被当作新目录的回归。
  132. expect(await $('[data-testid="virtual-project-name"]').isDisplayed()).toBe(false);
  133. return (
  134. !(await $('[role="dialog"]').isDisplayed()) &&
  135. !(await $('[data-testid="settings-page"]').isDisplayed())
  136. );
  137. },
  138. { timeout: 30_000, timeoutMsg: `${CASE_MARKER}: 最近项目未完成原项目导航` },
  139. );
  140. await waitForRemoteTab({
  141. caseMarker: CASE_MARKER,
  142. expectedIdentity: identity,
  143. expectedPath: config.workspacePaths[0],
  144. });
  145. await waitForWorkspaceApp(config.workspacePaths[0], 30_000);
  146. expect(await $('[data-testid="virtual-project-name"]').isDisplayed()).toBe(false);
  147. const projectId = await browser.execute(
  148. (path, identity) => {
  149. const bridge = window as Window & {
  150. __zcodeSessionStoreE2E?: {
  151. getState(): {
  152. getWorkspaceState(
  153. path: string,
  154. identity: string,
  155. ): { draftProjectId?: string | null };
  156. };
  157. };
  158. };
  159. return bridge.__zcodeSessionStoreE2E?.getState().getWorkspaceState(path, identity)
  160. .draftProjectId;
  161. },
  162. config.workspacePaths[0],
  163. identity,
  164. );
  165. expect(projectId).toBe(original.projectId);
  166. const rememberedProjectId = await browser.execute((identity) => {
  167. const key = `zcode-composer-workspace-scope:v1:${JSON.stringify(["desktop", identity])}`;
  168. return JSON.parse(localStorage.getItem(key) ?? "null")?.projectId;
  169. }, identity);
  170. expect(rememberedProjectId).toBe(original.projectId);
  171. const current = await callHandoffHost<RemoteProjectDirectory>(
  172. ServiceChannels.RemoteProjects,
  173. "readDirectory",
  174. );
  175. expect(current.entries.map((entry) => [entry.id, entry.projectId]).sort()).toEqual(
  176. originalDirectory.entries.map((entry) => [entry.id, entry.projectId]).sort(),
  177. );
  178. };
  179. await browser.execute(() => {
  180. (
  181. window as Window & { __testActions?: { setLocale(locale: string): void } }
  182. ).__testActions?.setLocale("zh-CN");
  183. });
  184. await settings();
  185. await $("[data-source-server-card]").waitForDisplayed();
  186. expect(await $$("[data-source-server-card]").length).toBe(1);
  187. // RDUX-13:设置导航「远程设备」不再显示汇总状态点。
  188. expect(await $("[data-remote-navigation-status]").isExisting()).toBe(false);
  189. // 默认收起成一行,只显示名称、地址与短状态;已连接时行上没有断开按钮。
  190. const row = $("[data-source-server-card] [data-source-server-row]");
  191. expect(
  192. await $("[data-source-server-card] [data-source-server-toggle]").getAttribute(
  193. "aria-expanded",
  194. ),
  195. ).toBe("false");
  196. expect(await $("[data-device-details]").isExisting()).toBe(false);
  197. expect(await row.getText()).toContain(`${config.username}@`);
  198. expect(await row.getText()).not.toContain("断开");
  199. expect(await row.$('[data-remote-connection-status="online"]').getText()).toBe("已连接");
  200. await expandDevice();
  201. // 单条连接不再标记“当前 / 默认”;连接行展示目标与远端版本。
  202. const connectionText = await $("[data-device-connection]").getText();
  203. expect(connectionText).toContain(`${config.username}@`);
  204. expect(connectionText).not.toContain("当前");
  205. expect(connectionText).toMatch(/v\d+\.\d+/u);
  206. // 最近项目每行带完整远端路径;任务继续提示只在更多菜单的断开项里。
  207. await $("[data-device-project]").waitForDisplayed();
  208. expect(await $("[data-device-projects]").getText()).toContain("最近项目");
  209. expect(await $("[data-device-project]").getText()).toContain(config.workspacePaths[0]);
  210. expect(await $("[data-settings-content-frame]").getText()).not.toContain("远端任务会继续运行");
  211. await openRecentProject(null);
  212. await settings();
  213. // 搜索匹配项目名;无匹配时列表内显示空态,清空后恢复。
  214. const search = $('[data-settings-content-frame] input[type="search"]');
  215. await search.setValue(config.workspacePaths[0].split("/").filter(Boolean).at(-1)!);
  216. expect(await $$("[data-source-server-card]").length).toBe(1);
  217. await search.setValue("no-such-device-e2e");
  218. await browser.waitUntil(async () => (await $$("[data-source-server-card]").length) === 0, {
  219. timeout: 5000,
  220. timeoutMsg: `${CASE_MARKER}: 搜索无匹配时仍显示设备`,
  221. });
  222. expect(await $("[data-source-server-device-list]").getText()).toContain("没有匹配");
  223. await $('[data-settings-content-frame] button[aria-label="清空搜索"]').click();
  224. await $("[data-source-server-card]").waitForDisplayed();
  225. // 更多菜单首组为编辑、断开(菜单项内常驻任务继续提示),之后是设备信息。
  226. const menuTexts = await deviceMenuTexts();
  227. expect(menuTexts[0]).toBe("编辑");
  228. expect(menuTexts[1]).toContain("断开");
  229. expect(menuTexts[1]).toContain("远端任务会继续运行");
  230. expect(await $("[data-device-info]").getText()).toContain("设备 ID");
  231. await browser.keys("Escape");
  232. await $("[data-device-info]").waitForDisplayed({ reverse: true });
  233. // 最近日志收在展开区页脚;短密码不能把固定文案按子串遮蔽(曾出现 "[redacted]ice")。
  234. await expandDevice();
  235. await $("[data-source-server-card] [data-source-server-log-toggle]").click();
  236. await $("[data-source-server-log-timestamp]").waitForDisplayed();
  237. const logText = await $("[data-source-server-log]").getText();
  238. expect(logText).toContain("Checking the remote device");
  239. expect(logText).not.toContain("[redacted]ice");
  240. await selectDeviceMenuItem("断开");
  241. await $(
  242. '[data-source-server-card] [data-remote-connection-status="offline"]',
  243. ).waitForDisplayed();
  244. await expandDevice();
  245. await openRecentProject("stale-project");
  246. // 项目菜单「远程设备设置」:打开设置后只展开所属设备行、聚焦设备名按钮并持续高亮。
  247. await selectTaskOrganizeMode(["项目", "Project"]);
  248. const projectRow = $(`[data-project-workspace-identity="${identity}"]`);
  249. await projectRow.moveTo();
  250. await projectRow.$('[data-testid="virtual-project-menu"]').click();
  251. await $('[data-testid="virtual-project-device-settings"]').click();
  252. const card = $("[data-source-server-card]");
  253. await browser.waitUntil(async () => (await card.getAttribute("data-highlighted")) !== null, {
  254. timeout: 15_000,
  255. timeoutMsg: `${CASE_MARKER}: 设置页没有高亮项目所属设备`,
  256. });
  257. expect(await card.$("[data-source-server-toggle]").getAttribute("aria-expanded")).toBe("true");
  258. expect(
  259. await browser.execute(() =>
  260. document.activeElement?.matches("[data-source-server-card] [data-source-server-toggle]"),
  261. ),
  262. ).toBe(true);
  263. const artifactRoot = resolve(
  264. process.env.ZCODE_E2E_ARTIFACT_DIR ?? ".e2e-artifacts/remote-device-cards",
  265. );
  266. await mkdir(artifactRoot, { recursive: true });
  267. await browser.saveScreenshot(resolve(artifactRoot, "device-row-deep-link-highlight.png"));
  268. const listener = createServer();
  269. await new Promise<void>((done) => listener.listen(0, "127.0.0.1", done));
  270. const address = listener.address();
  271. if (!address || typeof address === "string") throw new Error("Missing unused port");
  272. await new Promise<void>((done, reject) =>
  273. listener.close((error) => (error ? reject(error) : done())),
  274. );
  275. await button("新建连接");
  276. await clickTestIdByDom(TID_REMOTE_KIND_SSH);
  277. await fillSSHPasswordSettings({ ...config, host: "localhost", port: address.port });
  278. await clickLastEnabledSSHDialogButton(CASE_MARKER);
  279. expect(await waitForSSHError(CASE_MARKER)).toMatch(/无法连接到主机|Unable to connect to host/u);
  280. const unusedPort = address.port;
  281. const reservedHosts = async () =>
  282. (
  283. await callHandoffHost<RemoteProjectDirectory>(
  284. ServiceChannels.RemoteProjects,
  285. "readDirectory",
  286. )
  287. ).hosts.filter((host) => host.target?.kind === "ssh" && host.target.port === unusedPort);
  288. // 首次连接在 probe 前按地址写入本机成员预留;握手前失败时它只属于这条未完成连接。
  289. expect(await reservedHosts()).toHaveLength(1);
  290. // 默认折叠针对历史记录;收起会保留后台 owner 并主动展开,须先关闭失败的当前流程。
  291. await button("关闭", '[data-testid="ssh-dialog"]');
  292. await $('[data-testid="ssh-dialog"]').waitForDisplayed({ reverse: true });
  293. const unfinished = $("[data-unfinished-connections]");
  294. await unfinished.waitForExist();
  295. expect(await unfinished.getAttribute("open")).toBeNull();
  296. expect(await $$("[data-source-server-card]").length).toBe(1);
  297. await $("[data-unfinished-connections] summary").click();
  298. expect(await unfinished.getText()).toContain(String(address.port));
  299. const artifact = artifactRoot;
  300. for (const theme of ["light", "dark"]) {
  301. await browser.execute(
  302. (value) =>
  303. (
  304. window as Window & { __testActions?: { setTheme(theme: string): void } }
  305. ).__testActions?.setTheme(value),
  306. theme,
  307. );
  308. for (const width of [1440, 900, 480]) {
  309. await browser.electron.execute(
  310. (electron, size) =>
  311. electron.BrowserWindow.getAllWindows()
  312. .find((window) => !window.isDestroyed())
  313. ?.setSize(size, 1000),
  314. width,
  315. );
  316. await browser.executeAsync((done) =>
  317. requestAnimationFrame(() => requestAnimationFrame(() => done())),
  318. );
  319. await browser.saveScreenshot(resolve(artifact, `device-cards-${theme}-${width}.png`));
  320. }
  321. }
  322. // Bug 原因:IPv6 主机不能构成地址成员 ID,释放预留时对剩余线路逐条计算并抛错,
  323. // 只要列表里有这样一条线路,清理任何未完成连接都会失败。
  324. await browser.electron.execute((electron) =>
  325. electron.BrowserWindow.getAllWindows()
  326. .find((window) => !window.isDestroyed())
  327. ?.setSize(1440, 1000),
  328. );
  329. await button("新建连接");
  330. await clickTestIdByDom(TID_REMOTE_KIND_SSH);
  331. await fillSSHPasswordSettings({ ...config, host: "::1", port: unusedPort });
  332. await clickLastEnabledSSHDialogButton(CASE_MARKER);
  333. await waitForSSHError(CASE_MARKER);
  334. await button("关闭", '[data-testid="ssh-dialog"]');
  335. await $('[data-testid="ssh-dialog"]').waitForDisplayed({ reverse: true });
  336. await browser.waitUntil(
  337. () =>
  338. browser.execute(() =>
  339. Boolean(
  340. document.querySelector("[data-unfinished-connections]")?.textContent?.includes("::1"),
  341. ),
  342. ),
  343. { timeout: 10_000, timeoutMsg: `${CASE_MARKER}: IPv6 失败线路没有进入未完成列表` },
  344. );
  345. // 地址不能构成成员身份时 admission 在写入前失败,不产生预留。
  346. expect(await reservedHosts()).toHaveLength(1);
  347. // 同一原因曾让 connectHost 选线时抛错:一条 IPv6 线路会让所有设备的侧栏重连失败。
  348. expect(
  349. (
  350. await callHandoffHost<{ id: string }>(ServiceChannels.RemoteProjects, "connectHost", [
  351. original.hostId,
  352. ])
  353. ).id,
  354. ).toBe(original.hostId);
  355. await button("清理全部", "[data-unfinished-connections]");
  356. await clickTestIdByDom(TID_CONFIRM_DIALOG_CONFIRM);
  357. await unfinished.waitForExist({ reverse: true });
  358. expect(await $$("[data-source-server-card]").length).toBe(1);
  359. // Bug 原因:清理只改 settings,预留行成为孤儿,侧栏每次刷新都对它 readTree 并持续报 host-offline。
  360. expect(await reservedHosts()).toHaveLength(0);
  361. });
  362. });