conversation-session-rpn-project-navigation.test.ts 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326
  1. import { DatabaseSync } from "node:sqlite";
  2. import { createRemoteProjectService } from "@zcode/services/node";
  3. import { requestRemoteProjectConnection } from "#e2e/helpers/remote-project-actions";
  4. import { reloadElectronSessionPreservingBrowserProfile } from "#e2e/helpers/e2e-electron-reload";
  5. import { mkdir } from "node:fs/promises";
  6. import { join, resolve } from "node:path";
  7. import { appSettingsSchema } from "@zcode/shared";
  8. import {
  9. TID_PROJECT_SECTION,
  10. TID_CONVERSATION_SECTION,
  11. TID_SSH_DIALOG,
  12. TID_SSH_PASSWORD_INPUT,
  13. TID_SSH_ERROR,
  14. } from "@zcode/shared/test-ids";
  15. import {
  16. clearAppData,
  17. getE2EAppDataPaths,
  18. readSettings,
  19. seedSettings,
  20. } from "#e2e/helpers/desktop-app";
  21. import { prepareV4ConversationE2E } from "#e2e/helpers/v4-conversation";
  22. import { waitForRendererAfterColdRestart } from "#e2e/helpers/ssh-remote-lifecycle";
  23. import { openSSHRemoteDialog, readRemoteTabSnapshot } from "#e2e/helpers/ssh-remote-p0";
  24. import { selectTaskOrganizeMode } from "#e2e/helpers/workspace-agent-warmup";
  25. const CASE_MARKER = "E2E_RPN_PROJECT_NAVIGATION";
  26. const SOURCE_A = "25db8db2-d27b-40de-a23e-697b3c127234";
  27. const SOURCE_B = "f6a0d063-3c52-4ce2-abf1-cb456d87f542";
  28. const PROJECT_PATH = "/srv/project";
  29. const CHAT_PATH = "/home/e2e/.zcode/workspace/default";
  30. const IDENTITY_A = `remote:server:${SOURCE_A}:${PROJECT_PATH}`;
  31. const IDENTITY_B = `remote:server:${SOURCE_B}:${PROJECT_PATH}`;
  32. const CHAT_IDENTITY = `remote:server:${SOURCE_A}:${CHAT_PATH}`;
  33. async function dialogButton(
  34. labels: readonly string[],
  35. partial = false,
  36. ): Promise<WebdriverIO.Element> {
  37. const dialog = $(`[data-testid="${TID_SSH_DIALOG}"]`);
  38. let matched: WebdriverIO.Element | undefined;
  39. // 高级区展开时按钮先挂载、文字仍被动画裁切;等待实际可见文案,不能把这一帧当成缺少选项。
  40. await browser.waitUntil(
  41. async () => {
  42. for (const button of await dialog.$$("button")) {
  43. const text = (await button.getText()).trim();
  44. if (
  45. (await button.isDisplayed()) &&
  46. labels.some((label) => (partial ? text.includes(label) : text === label))
  47. ) {
  48. matched = button;
  49. return true;
  50. }
  51. }
  52. return false;
  53. },
  54. { timeout: 10_000, timeoutMsg: `${CASE_MARKER}: 没有找到向导按钮 ${labels.join(" / ")}` },
  55. );
  56. return matched!;
  57. }
  58. async function completeInitialOnboarding() {
  59. const page = $('[data-testid="onboarding-page"]');
  60. await page.waitForDisplayed({ timeout: 30_000 });
  61. // 合入首次职业引导后,隔离 profile 没有完成记录;先走真实保存链,后面的冷重载才能验证项目恢复。
  62. await page.$("footer > div > button").click();
  63. const codingMode = page.$('.//button[.//span[text()="编程模式" or text()="Coding mode"]]');
  64. await codingMode.waitForDisplayed();
  65. await codingMode.click();
  66. await page.$("footer > div > button").click();
  67. await browser.waitUntil(
  68. async () =>
  69. ["开始使用", "Get started"].includes(await page.$("footer > div > button").getText()),
  70. { timeout: 10_000, timeoutMsg: `${CASE_MARKER}: 引导未进入偏好页` },
  71. );
  72. // 偏好页选择“跳过”仍持久化完成记录,并关闭与导航无关的主动推荐和记忆。
  73. await page.$("footer > button").click();
  74. await page.waitForDisplayed({ reverse: true, timeout: 10_000 });
  75. }
  76. // 只验证导航合同,不发 prompt、不连接真实远端;本机关闭端口用于隔离手动失败入口。
  77. describe(`${CASE_MARKER}: 项目平铺与远程无项目入口停用`, () => {
  78. afterEach(async () => {
  79. const artifactDir = resolve(
  80. process.env.ZCODE_E2E_ARTIFACT_DIR ?? ".e2e-artifacts/rpn-project-navigation",
  81. );
  82. await mkdir(artifactDir, { recursive: true });
  83. await browser.saveScreenshot(resolve(artifactDir, "rpn-final.png"));
  84. });
  85. after(async () => {
  86. await browser.electron.restoreAllMocks();
  87. await clearAppData();
  88. });
  89. it("RPN-01/02/04/09/10/14 keeps offline projects visible and distinct without restoring remote conversations", async function () {
  90. this.timeout(180_000);
  91. await completeInitialOnboarding();
  92. await prepareV4ConversationE2E({ skipProvider: true });
  93. const before = await readSettings();
  94. const sources = [SOURCE_A, SOURCE_B];
  95. const names = ["alpha-device", "beta-device"];
  96. const profiles = sources.map((sourceServerId, index) => ({
  97. profileId: ["294224b4-a6ad-4424-97ad-37f58c833e0f", "2abca774-d38f-44ca-95bf-cc659ab1183b"][
  98. index
  99. ]!,
  100. sourceServerId,
  101. displayName: names[index]!,
  102. transport: "ssh" as const,
  103. lifecycleState: "active" as const,
  104. createdAt: 1,
  105. target: {
  106. kind: "ssh" as const,
  107. host: "127.0.0.1",
  108. port: index + 1,
  109. username: "e2e",
  110. assetInstallMode: "remote-download" as const,
  111. },
  112. }));
  113. const entries = profiles.map((profile, index) => ({
  114. kind: "remote" as const,
  115. workspacePath: PROJECT_PATH,
  116. workspaceIdentity: index === 0 ? IDENTITY_A : IDENTITY_B,
  117. workspacePurpose: "project" as const,
  118. target: profile.target,
  119. lastOpenedAt: 1,
  120. lastConnectionStatus: "failed" as const,
  121. }));
  122. await reloadElectronSessionPreservingBrowserProfile(browser, {
  123. // 旧 Host 的 tab 持久化会覆盖 direct seed;退出屏障后再写,保证新进程读取完整项目列表。
  124. afterElectronProcessExit: async () => {
  125. await seedSettings(
  126. appSettingsSchema.parse({
  127. ...before,
  128. remoteStartupAutoReconnectEnabled: false,
  129. sourceServerDirectoryMigrationVersion: 1,
  130. sourceServers: sources.map((sourceServerId, index) => ({
  131. sourceServerId,
  132. displayName: names[index]!,
  133. installState: "installed" as const,
  134. preferredProfileId: profiles[index]!.profileId,
  135. declaredWorkspaces: [],
  136. })),
  137. connectionProfiles: profiles,
  138. sourceServerWorkspaceHistory: entries.map((entry, index) => ({
  139. workspacePath: entry.workspacePath,
  140. workspaceIdentity: entry.workspaceIdentity,
  141. sourceServerId: sources[index]!,
  142. profileId: profiles[index]!.profileId,
  143. lastOpenedAt: 1,
  144. })),
  145. remoteConversationWorkspaceBySourceServerId: {
  146. [SOURCE_A]: { workspacePath: CHAT_PATH, lastResolvedAt: 1 },
  147. },
  148. lastWorkspaceSession: [
  149. ...(before.lastWorkspaceSession ?? []).filter((entry) => entry.kind === "local"),
  150. ...entries,
  151. {
  152. ...entries[0]!,
  153. workspaceIdentity: CHAT_IDENTITY,
  154. workspacePath: CHAT_PATH,
  155. workspacePurpose: "conversation",
  156. },
  157. ],
  158. }),
  159. );
  160. // 项目入口权威已迁到 SQLite;仅写旧 tab/history 不会创建 membership。
  161. // node:sqlite 仅提供同步连接,此时旧 App 已退出,不与 Host 并发写库。
  162. const db = new DatabaseSync(join(getE2EAppDataPaths().appDataDir, "tasks-index.sqlite"));
  163. try {
  164. const projects = createRemoteProjectService({ database: async () => db });
  165. for (const [index, profile] of profiles.entries()) {
  166. const host = await projects.saveHost({
  167. id: `remote:server:${profile.sourceServerId}`,
  168. target: profile.target,
  169. });
  170. await projects.addEntry({
  171. hostId: host.id,
  172. expectedMembershipId: host.membershipId,
  173. project: {
  174. projectId: `rpn-project-${index}`,
  175. name: "project",
  176. roots: [{ rootPath: PROJECT_PATH, isPrimary: true, position: 0 }],
  177. },
  178. });
  179. }
  180. } finally {
  181. db.close();
  182. }
  183. },
  184. });
  185. await waitForRendererAfterColdRestart(CASE_MARKER);
  186. await selectTaskOrganizeMode(["项目", "Project"]);
  187. await browser.waitUntil(
  188. async () => (await $$("[data-project-workspace-identity]").length) === 2,
  189. {
  190. timeout: 30_000,
  191. timeoutMsg: `${CASE_MARKER}: 离线项目应直接展示为两条独立项目行`,
  192. },
  193. );
  194. expect(await $$("[data-source-group-key]")).toHaveLength(0);
  195. expect(await $$(`[data-testid="${TID_PROJECT_SECTION}"]`)).toHaveLength(1);
  196. expect(await $$(`[data-testid="${TID_CONVERSATION_SECTION}"]`)).toHaveLength(1);
  197. expect((await readRemoteTabSnapshot(CHAT_IDENTITY)).workspacePath).toBeNull();
  198. // Group 已退役;切换当前时间线/项目视图不应隐式连接或丢失离线 membership。
  199. // Radix 菜单依赖 pointerdown;DOM click 不打开菜单,不能据此误报时间线入口消失。
  200. // 上一次视图选择的菜单仍在退出时,trigger 点击会被吞掉;先等菜单卸载。
  201. await $('[role="menu"]').waitForExist({ reverse: true, timeout: 10_000 });
  202. await $('[data-testid="sidebar-view-menu"]').click();
  203. await $('[data-testid="sidebar-view-timeline"]').waitForDisplayed();
  204. await $('[data-testid="sidebar-view-timeline"]').click();
  205. // 先等时间线菜单退出,再开启下次选择,避免关闭动画吞掉紧接的 trigger click。
  206. await $('[role="menu"]').waitForExist({ reverse: true, timeout: 10_000 });
  207. expect((await readRemoteTabSnapshot(IDENTITY_A)).remoteSessionId).toBeNull();
  208. expect((await readRemoteTabSnapshot(IDENTITY_B)).remoteSessionId).toBeNull();
  209. await selectTaskOrganizeMode(["项目", "Project"]);
  210. expect(await $$("[data-project-workspace-identity]")).toHaveLength(2);
  211. for (const identity of [IDENTITY_A, IDENTITY_B]) {
  212. const row = $(`[data-project-workspace-identity="${identity}"]`);
  213. expect(await row.getAttribute("data-connection-state")).toBe("offline");
  214. // 设备全名已移到悬停详情,行内标签不再带 title;按可见文字判断设备可辨。
  215. expect(await row.$('[data-testid="project-device"]').getText()).toBe(
  216. identity === IDENTITY_A ? "alpha-device" : "beta-device",
  217. );
  218. await row.moveTo();
  219. await row.$('[data-testid="virtual-project-menu"]').click();
  220. await $('[data-testid="virtual-project-connect"]').waitForDisplayed();
  221. // RPN-17:离线远程项目也能从菜单进入设备设置。
  222. await $('[data-testid="virtual-project-device-settings"]').waitForDisplayed();
  223. expect(await row.$('[data-testid="virtual-project-create-task"]').isExisting()).toBe(false);
  224. // 悬停 300ms 后身份详情会叠在菜单上;Escape 按层关闭,先关详情再关菜单。
  225. await browser.waitUntil(
  226. async () => {
  227. await browser.keys("Escape");
  228. return !(await $('[role="menu"]').isDisplayed());
  229. },
  230. { timeout: 5_000, interval: 300, timeoutMsg: `${CASE_MARKER}: Escape 未关闭项目菜单` },
  231. );
  232. }
  233. expect((await readRemoteTabSnapshot(IDENTITY_A)).remoteSessionId).toBeNull();
  234. expect((await readRemoteTabSnapshot(IDENTITY_B)).remoteSessionId).toBeNull();
  235. // 数据保留依据是 canonical 历史映射,不把 UI open-set 是否保留误当作任务文件删除。
  236. expect(
  237. (await readSettings()).remoteConversationWorkspaceBySourceServerId?.[SOURCE_A]?.workspacePath,
  238. ).toBe(CHAT_PATH);
  239. const artifactDir = resolve(
  240. process.env.ZCODE_E2E_ARTIFACT_DIR ?? ".e2e-artifacts/rpn-project-navigation",
  241. );
  242. await mkdir(artifactDir, { recursive: true });
  243. await browser.saveScreenshot(resolve(artifactDir, "rpn-project-sidebar.png"));
  244. // 项目标题只展开历史;必须从项目菜单发起连接,再验证既有失败交接与凭据隔离。
  245. await requestRemoteProjectConnection(IDENTITY_A, CASE_MARKER);
  246. await $(`[data-testid="${TID_SSH_DIALOG}"]`).waitForDisplayed({ timeout: 20_000 });
  247. expect((await readRemoteTabSnapshot(CHAT_IDENTITY)).workspacePath).toBeNull();
  248. // RPN-06/08:真实表单必须隔离设备凭据,并保留已有线路下载方式;不发起网络连接。
  249. await $(`[data-testid="${TID_SSH_ERROR}"]`).waitForDisplayed({ timeout: 10_000 });
  250. await (await dialogButton(["返回配置", "Back to configuration"])).click();
  251. const password = $(`[data-testid="${TID_SSH_PASSWORD_INPUT}"]`);
  252. await password.waitForDisplayed();
  253. await password.setValue("E2E_RPN_SECRET_FOR_DEVICE_A");
  254. await (await dialogButton(["关闭", "Close"])).click();
  255. await $(`[data-testid="${TID_SSH_DIALOG}"]`).waitForDisplayed({ reverse: true });
  256. await requestRemoteProjectConnection(IDENTITY_B, CASE_MARKER);
  257. await $(`[data-testid="${TID_SSH_ERROR}"]`).waitForDisplayed({ timeout: 10_000 });
  258. await (await dialogButton(["返回配置", "Back to configuration"])).click();
  259. await password.waitForDisplayed();
  260. expect(await password.getValue()).toBe("");
  261. await (await dialogButton(["高级选项", "Advanced options"])).click();
  262. expect(
  263. await (
  264. await dialogButton(["远端服务器下载", "Download on remote server"])
  265. ).getAttribute("aria-pressed"),
  266. ).toBe("true");
  267. // 当前三屏已取消旧的两次返回/下一步;关闭清空旧意图,再从项目入口直接新建 SSH。
  268. await (await dialogButton(["关闭", "Close"])).click();
  269. await $(`[data-testid="${TID_SSH_DIALOG}"]`).waitForExist({ reverse: true });
  270. await openSSHRemoteDialog(CASE_MARKER);
  271. await password.waitForDisplayed();
  272. expect(await password.getValue()).toBe("");
  273. await (await dialogButton(["高级选项", "Advanced options"])).click();
  274. expect(
  275. await (
  276. await dialogButton(["本地下载后上传", "Download locally, then upload"])
  277. ).getAttribute("aria-pressed"),
  278. ).toBe("true");
  279. await browser.saveScreenshot(resolve(artifactDir, "rpn-connection-intent-isolation.png"));
  280. await (await dialogButton(["关闭", "Close"])).click();
  281. await $(`[data-testid="${TID_SSH_DIALOG}"]`).waitForExist({ reverse: true });
  282. // SSH 向导从「创建项目」进入,关闭后回到该弹窗;先取消,避免遮罩拦截侧栏点击。
  283. await browser.keys("Escape");
  284. await $('[data-slot="dialog-overlay"]').waitForExist({ reverse: true });
  285. // RPN-17:项目菜单「远程设备设置」只负责导航:只展开项目所属设备行、聚焦并高亮,不发起连接。
  286. const rowB = $(`[data-project-workspace-identity="${IDENTITY_B}"]`);
  287. await rowB.moveTo();
  288. await rowB.$('[data-testid="virtual-project-menu"]').click();
  289. const deviceSettings = $('[data-testid="virtual-project-device-settings"]');
  290. await deviceSettings.waitForDisplayed();
  291. await deviceSettings.click();
  292. await $(`[data-source-server-card="${SOURCE_B}"]`).waitForDisplayed({ timeout: 15_000 });
  293. await browser.waitUntil(
  294. () =>
  295. browser.execute((id) => {
  296. const card = document.querySelector(`[data-source-server-card="${id}"]`);
  297. const toggle = card?.querySelector("[data-source-server-toggle]");
  298. return (
  299. document.activeElement === toggle &&
  300. toggle?.getAttribute("aria-expanded") === "true" &&
  301. card?.hasAttribute("data-highlighted") === true
  302. );
  303. }, SOURCE_B),
  304. { timeout: 10_000, timeoutMsg: `${CASE_MARKER}: 设置页没有定位到项目所属设备行` },
  305. );
  306. // 只展开目标设备,其他设备保持收起。
  307. expect(
  308. await browser.execute(
  309. () =>
  310. [...document.querySelectorAll('[data-source-server-toggle][aria-expanded="true"]')]
  311. .length,
  312. ),
  313. ).toBe(1);
  314. expect((await readRemoteTabSnapshot(IDENTITY_B)).remoteSessionId).toBeNull();
  315. await browser.saveScreenshot(resolve(artifactDir, "rpn-project-device-settings.png"));
  316. });
  317. });