conversation-session-project-device-visibility-ssh.test.ts 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385
  1. import { join } from "node:path";
  2. import { writeFile } from "node:fs/promises";
  3. import { parseRemoteWorkspaceIdentity } from "@zcode/shared";
  4. import {
  5. TID_SETTINGS_BACK_BUTTON,
  6. TID_TASK_SETTINGS_BUTTON,
  7. TID_TASK_ITEM,
  8. testId,
  9. } from "@zcode/shared/test-ids";
  10. import {
  11. clearAppData,
  12. clickTestIdByDom,
  13. readSettings,
  14. waitForTestIdByDom,
  15. } from "#e2e/helpers/desktop-app";
  16. import { reloadElectronSessionPreservingBrowserProfile } from "#e2e/helpers/e2e-electron-reload";
  17. import {
  18. disconnectRemoteSource,
  19. openRemoteDevicesSettings,
  20. requestRemoteProjectConnection,
  21. } from "#e2e/helpers/remote-project-actions";
  22. import {
  23. bringRemoteDeviceOnline,
  24. execInRemoteContainer,
  25. readRemoteDockerContainer,
  26. takeRemoteDeviceOffline,
  27. } from "#e2e/helpers/remote-docker-target";
  28. import {
  29. prepareSSHConnectionPage,
  30. readHostProcesses,
  31. waitForRemoteTab,
  32. } from "#e2e/helpers/ssh-remote-p0";
  33. import {
  34. connectSSHWorkspaceAndSendFirstTurn,
  35. prepareSSHLifecycle,
  36. readRemoteCoreIdentity,
  37. sendSSHFollowTurn,
  38. waitForRendererAfterColdRestart,
  39. type SSHLifecycleProvider,
  40. type SSHLifecycleTask,
  41. } from "#e2e/helpers/ssh-remote-lifecycle";
  42. import {
  43. selectV4TaskById,
  44. waitForV4AssistantMessageContaining,
  45. waitForV4Pane,
  46. } from "#e2e/helpers/v4-conversation";
  47. import { selectTaskOrganizeMode } from "#e2e/helpers/workspace-agent-warmup";
  48. const marker = "E2E_PROJECT_DEVICE_VISIBILITY_SSH";
  49. const sharedName = "E2E shared project";
  50. const switchSelector = '[data-testid="hide-project-device-names"]';
  51. const row = (identity: string) =>
  52. $(`[data-project-workspace-identity=${JSON.stringify(identity)}]`);
  53. async function screenshot(name: string) {
  54. await browser.saveScreenshot(join(process.env.ZCODE_E2E_ARTIFACT_DIR!, `device-${name}.png`));
  55. }
  56. async function leaveDetails() {
  57. const outside = await browser.execute(() => ({ x: innerWidth - 24, y: 24 }));
  58. await browser.action("pointer").move(outside).perform();
  59. await $('[data-testid="remote-identity-details"]').waitForDisplayed({ reverse: true });
  60. }
  61. async function setHidden(hidden: boolean) {
  62. await openRemoteDevicesSettings();
  63. const control = $(switchSelector);
  64. await control.waitForDisplayed();
  65. if ((await control.getAttribute("aria-checked")) !== String(hidden)) await control.click();
  66. expect(await control.getAttribute("aria-checked")).toBe(String(hidden));
  67. await clickTestIdByDom(TID_SETTINGS_BACK_BUTTON);
  68. }
  69. async function assertRows(tasks: SSHLifecycleTask[], hidden: boolean) {
  70. for (const task of tasks) {
  71. const project = row(task.identity);
  72. await project.waitForDisplayed();
  73. await project.$('[data-testid="project-device"]').waitForExist({ reverse: hidden });
  74. expect(await project.getAttribute("data-project-name")).toBe(sharedName);
  75. expect(await project.getAttribute("data-project-workspace-identity")).toBe(task.identity);
  76. expect(await project.$("[data-remote-state-icon]").isExisting()).toBe(true);
  77. }
  78. }
  79. async function renameProject(task: SSHLifecycleTask) {
  80. await row(task.identity).moveTo();
  81. await row(task.identity).$('[data-testid="virtual-project-menu"]').click();
  82. await $('[data-testid="virtual-project-edit"]').click();
  83. await $('[data-testid="virtual-project-name"]').setValue(sharedName);
  84. await $('[data-testid="virtual-project-save"]').click();
  85. await $('[data-testid="virtual-project-name"]').waitForExist({ reverse: true });
  86. await browser.waitUntil(
  87. async () => (await row(task.identity).getAttribute("data-project-name")) === sharedName,
  88. );
  89. }
  90. async function selectProjectTask(task: SSHLifecycleTask) {
  91. // 项目已被用户改名且跨 Source 同名,任务归属必须按稳定身份验证,不能由目录名反推项目名。
  92. const project = row(task.identity);
  93. const toggle = project.$('[data-testid="virtual-project-toggle"]');
  94. if ((await toggle.getAttribute("aria-expanded")) !== "true") await toggle.click();
  95. await project
  96. .$(`[data-testid=${JSON.stringify(testId(TID_TASK_ITEM, task.taskId))}]`)
  97. .waitForDisplayed();
  98. await selectV4TaskById(task.taskId, 30000);
  99. }
  100. async function verifyDetails(task: SSHLifecycleTask, deviceName: string) {
  101. await row(task.identity).$('[data-testid="virtual-project-toggle"]').moveTo();
  102. const details = $('[data-testid="remote-identity-details"]');
  103. await details.waitForDisplayed();
  104. const text = await details.getText();
  105. expect(text).toContain(deviceName);
  106. expect(text).toContain(task.workspacePath);
  107. expect(text).toContain("127.0.0.1");
  108. await screenshot(`details-${task.label}`);
  109. await leaveDetails();
  110. }
  111. async function verifyOtherWindowSynchronization() {
  112. const originalHandle = await browser.getWindowHandle();
  113. const previousHandles = await browser.getWindowHandles();
  114. // 复用产品 activate → createWindow 路径创建第二个真实窗口;不替换 store 或广播服务。
  115. const windowId = await browser.electron.execute(async (electron) => {
  116. const original = electron.BrowserWindow.getAllWindows;
  117. const created = new Promise<number>((resolve) => {
  118. electron.app.once("browser-window-created", (_event, window) => resolve(window.id));
  119. });
  120. electron.BrowserWindow.getAllWindows = () => [];
  121. try {
  122. electron.app.emit("activate");
  123. return await created;
  124. } finally {
  125. electron.BrowserWindow.getAllWindows = original;
  126. }
  127. });
  128. let secondHandle = "";
  129. try {
  130. await browser.waitUntil(
  131. async () => {
  132. secondHandle =
  133. (await browser.getWindowHandles()).find((handle) => !previousHandles.includes(handle)) ??
  134. "";
  135. return Boolean(secondHandle);
  136. },
  137. { timeout: 30000, timeoutMsg: "第二个应用窗口未创建" },
  138. );
  139. await browser.switchToWindow(secondHandle);
  140. await waitForTestIdByDom(TID_TASK_SETTINGS_BUTTON, { timeout: 60000 });
  141. await openRemoteDevicesSettings();
  142. expect(await $(switchSelector).getAttribute("aria-checked")).toBe("false");
  143. await browser.switchToWindow(originalHandle);
  144. await setHidden(true);
  145. await browser.switchToWindow(secondHandle);
  146. await browser.waitUntil(
  147. async () => (await $(switchSelector).getAttribute("aria-checked")) === "true",
  148. { timeout: 10000 },
  149. );
  150. await screenshot("second-window-synchronized");
  151. } finally {
  152. await browser.switchToWindow(originalHandle);
  153. await browser.electron.execute(
  154. (electron, id) => electron.BrowserWindow.fromId(id)?.close(),
  155. windowId,
  156. );
  157. }
  158. }
  159. describe(marker, () => {
  160. let provider: SSHLifecycleProvider | undefined;
  161. afterEach(async function () {
  162. if (this.currentTest?.state === "failed") {
  163. await screenshot("failure");
  164. await writeFile(
  165. join(process.env.ZCODE_E2E_ARTIFACT_DIR!, "device-failure-page.txt"),
  166. await $("body").getText(),
  167. );
  168. }
  169. });
  170. after(async () => {
  171. await provider?.tunnel.close().catch(() => undefined);
  172. await browser.electron.restoreAllMocks();
  173. await clearAppData();
  174. });
  175. it("真实 SSH 同名项目在隐藏设备名后仍能选任务、续发、重连与冷恢复", async function () {
  176. this.timeout(20 * 60_000);
  177. const container = readRemoteDockerContainer(marker);
  178. await prepareSSHConnectionPage(marker);
  179. const prepared = await prepareSSHLifecycle(marker);
  180. provider = prepared.provider;
  181. // 同一 Source 会给重名项目自动编号;独立账号拥有独立 Source,才能验证真正的同名项目。
  182. const secondConfig = { ...prepared.config, username: "visibility" };
  183. const secondPath = "/home/visibility/workspace";
  184. await execInRemoteContainer(
  185. container,
  186. ["useradd", "-m", "-s", "/bin/bash", secondConfig.username],
  187. { user: "0" },
  188. );
  189. await execInRemoteContainer(container, ["chpasswd"], {
  190. user: "0",
  191. input: `${secondConfig.username}:${prepared.config.password}\n`,
  192. });
  193. await execInRemoteContainer(container, ["mkdir", "-p", secondPath], {
  194. user: secondConfig.username,
  195. });
  196. const a = await connectSSHWorkspaceAndSendFirstTurn({
  197. caseMarker: marker,
  198. config: prepared.config,
  199. provider,
  200. label: "A",
  201. workspacePath: prepared.config.workspacePaths[0],
  202. });
  203. const b = await connectSSHWorkspaceAndSendFirstTurn({
  204. caseMarker: marker,
  205. config: secondConfig,
  206. provider,
  207. label: "B",
  208. workspacePath: secondPath,
  209. });
  210. const tasks = [a, b];
  211. const remoteCoreBefore = await readRemoteCoreIdentity(secondConfig, marker);
  212. await selectTaskOrganizeMode(["项目", "Project"]);
  213. const sourceIds = tasks.map(
  214. (task) => parseRemoteWorkspaceIdentity(task.identity)!.sourceServerId,
  215. );
  216. expect(sourceIds[0]).not.toBe(sourceIds[1]);
  217. const settings = await readSettings();
  218. const devices = sourceIds.map((id) => {
  219. const device = settings.sourceServers?.find((source) => source.sourceServerId === id);
  220. if (!device) throw new Error("真实 SSH Source 未登记");
  221. return device;
  222. });
  223. for (const task of tasks) await renameProject(task);
  224. await row(a.identity).moveTo();
  225. await row(a.identity).$('[data-testid="virtual-project-menu"]').click();
  226. await $('[data-testid="virtual-project-pin"]').click();
  227. await row(a.identity).$(".lucide-pin").waitForExist();
  228. await assertRows(tasks, false);
  229. await screenshot("default-visible");
  230. await verifyOtherWindowSynchronization();
  231. await assertRows(tasks, true);
  232. for (let index = 0; index < tasks.length; index++)
  233. await verifyDetails(tasks[index]!, devices[index]!.displayName);
  234. expect(await $("[data-workspace-device-name]").getText()).toBe(devices[1]!.displayName);
  235. // 已保存任务的项目固定;项目切换菜单只在新草稿中可用,不能用历史任务页面验证该入口。
  236. await row(b.identity).moveTo();
  237. await row(b.identity).$('[data-testid="virtual-project-create-task"]').click();
  238. await waitForRemoteTab({
  239. caseMarker: marker,
  240. expectedIdentity: b.identity,
  241. expectedPath: b.workspacePath,
  242. });
  243. await waitForV4Pane(
  244. (snapshot) => snapshot.sessionId === "draft",
  245. "项目新建没有进入草稿",
  246. 30000,
  247. );
  248. // 行尾新建需要悬停项目行,身份浮层可能再次打开;先走真实移出/关闭,再操作输入框菜单。
  249. await leaveDetails();
  250. expect(await $('[data-testid="composer-workspace-trigger"]').getText()).toBe(sharedName);
  251. await $('[data-testid="composer-workspace-trigger"]').click();
  252. const menu = $('[data-testid="composer-project-menu"]');
  253. await menu.waitForDisplayed();
  254. for (let index = 0; index < tasks.length; index++) {
  255. const task = tasks[index]!;
  256. const device = devices[index]!;
  257. await menu.$("input").setValue(device.displayName);
  258. const projectId = await row(task.identity).getAttribute("data-project-id");
  259. const option = menu.$(`[data-project-id=${JSON.stringify(projectId)}]`);
  260. await option.waitForDisplayed();
  261. expect(await option.getText()).toContain(device.displayName);
  262. expect(await option.getText()).toContain(sharedName);
  263. }
  264. await browser.keys("Escape");
  265. await leaveDetails();
  266. for (const task of tasks) {
  267. await selectProjectTask(task);
  268. await waitForV4AssistantMessageContaining(task.firstReply);
  269. await sendSSHFollowTurn(task, marker, task === a ? b.firstPrompt : a.firstPrompt);
  270. }
  271. await screenshot("hidden-tasks-working");
  272. await disconnectRemoteSource(sourceIds[0]!, marker, { workspaceIdentities: [a.identity] });
  273. expect(await row(b.identity).getAttribute("data-connection-state")).toBe("online");
  274. await disconnectRemoteSource(sourceIds[1]!, marker, { workspaceIdentities: [b.identity] });
  275. await assertRows(tasks, true);
  276. for (const task of tasks)
  277. expect(await row(task.identity).$('[data-testid="project-status-label"]').getText()).toBe(
  278. "离线",
  279. );
  280. await screenshot("hidden-offline");
  281. await requestRemoteProjectConnection(b.identity, marker);
  282. const reconnected = await waitForRemoteTab({
  283. caseMarker: marker,
  284. expectedIdentity: b.identity,
  285. expectedPath: b.workspacePath,
  286. });
  287. expect(reconnected.remoteSessionId).not.toBe(b.remoteSessionId);
  288. await assertRows(tasks, true);
  289. await selectProjectTask(b);
  290. await sendSSHFollowTurn(
  291. { ...b, remoteSessionId: reconnected.remoteSessionId! },
  292. marker,
  293. a.firstPrompt,
  294. );
  295. const oldHosts = await readHostProcesses();
  296. await reloadElectronSessionPreservingBrowserProfile(browser);
  297. await waitForRendererAfterColdRestart(marker);
  298. const cold = await waitForRemoteTab({
  299. caseMarker: marker,
  300. expectedIdentity: b.identity,
  301. expectedPath: b.workspacePath,
  302. });
  303. expect(cold.remoteSessionId).not.toBe(reconnected.remoteSessionId);
  304. expect(await readHostProcesses()).not.toEqual(oldHosts);
  305. await waitForV4Pane(
  306. (snapshot) => snapshot.sessionId === "draft",
  307. "冷启动未进入项目草稿",
  308. 60000,
  309. );
  310. await assertRows(tasks, true);
  311. await openRemoteDevicesSettings();
  312. expect(await $(switchSelector).getAttribute("aria-checked")).toBe("true");
  313. for (const device of devices)
  314. expect(
  315. await $(`[data-source-server-card=${JSON.stringify(device.sourceServerId)}]`).getText(),
  316. ).toContain(device.displayName);
  317. await clickTestIdByDom(TID_SETTINGS_BACK_BUTTON);
  318. await row(a.identity).$(".lucide-pin").waitForExist();
  319. await selectProjectTask(b);
  320. await waitForV4AssistantMessageContaining(b.firstReply);
  321. await sendSSHFollowTurn(
  322. { ...b, remoteSessionId: cold.remoteSessionId! },
  323. marker,
  324. a.firstPrompt,
  325. );
  326. await screenshot("hidden-cold-restored");
  327. for (let index = 0; index < tasks.length; index++) {
  328. if ((await row(tasks[index]!.identity).getAttribute("data-connection-state")) === "online")
  329. await disconnectRemoteSource(sourceIds[index]!, marker, {
  330. workspaceIdentities: [tasks[index]!.identity],
  331. });
  332. }
  333. await takeRemoteDeviceOffline(container);
  334. try {
  335. await assertRows(tasks, true);
  336. } finally {
  337. await bringRemoteDeviceOnline(container, prepared.config);
  338. }
  339. await requestRemoteProjectConnection(b.identity, marker);
  340. await waitForRemoteTab({
  341. caseMarker: marker,
  342. expectedIdentity: b.identity,
  343. expectedPath: b.workspacePath,
  344. });
  345. await assertRows(tasks, true);
  346. await setHidden(false);
  347. await assertRows(tasks, false);
  348. const remoteCoreAfter = await readRemoteCoreIdentity(secondConfig, marker);
  349. await screenshot("restored-after-container-restart");
  350. await writeFile(
  351. join(process.env.ZCODE_E2E_ARTIFACT_DIR!, "device-ssh-evidence.json"),
  352. JSON.stringify(
  353. {
  354. sourceIds,
  355. deviceNames: devices.map((device) => device.displayName),
  356. remoteCoreBefore,
  357. remoteCoreAfter,
  358. projects: tasks.map(({ identity, taskId, workspacePath }) => ({
  359. identity,
  360. taskId,
  361. workspacePath,
  362. })),
  363. verified: [
  364. "real-ssh",
  365. "same-name-projects",
  366. "pinned-project",
  367. "two-real-windows",
  368. "project-menu-search",
  369. "full-device-details",
  370. "task-history",
  371. "follow-turns",
  372. "disconnect-reconnect",
  373. "electron-cold-restart",
  374. "container-restart",
  375. "visibility-restored",
  376. ],
  377. },
  378. null,
  379. 2,
  380. ),
  381. );
  382. });
  383. });