conversation-session-r3-install-faults.test.ts 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370
  1. import { selectTaskOrganizeMode } from "#e2e/helpers/workspace-agent-warmup";
  2. import { disconnectRemoteSource } from "#e2e/helpers/remote-project-actions";
  3. import { createHash } from "node:crypto";
  4. import { mkdir, readFile, stat, writeFile } from "node:fs/promises";
  5. import { join, resolve } from "node:path";
  6. import {
  7. SOURCE_SERVER_RELEASE_DESCRIPTOR_FILE_NAME,
  8. parseRemoteWorkspaceIdentity,
  9. sourceServerReleaseDescriptorSchema,
  10. type SourceServerReleaseArchive,
  11. } from "@zcode/shared";
  12. import {
  13. selectSourceServerReleaseArchive,
  14. withSourceServerReleaseFileFault,
  15. } from "#e2e/helpers/source-server-release-faults";
  16. import { clearAppData, DEFAULT_WORKSPACE } from "#e2e/helpers/desktop-app";
  17. import { prepareV4ConversationE2E } from "#e2e/helpers/v4-conversation";
  18. import { openWorkspaceDraftFromSidebar } from "#e2e/helpers/workspace-agent-warmup";
  19. import {
  20. clickLastEnabledSSHDialogButton,
  21. connectSSHWorkspace,
  22. fillSSHPasswordSettings,
  23. openSSHRemoteDialog,
  24. readDualSSHRuntimeConfig,
  25. readHostProcesses,
  26. readRemoteTabSnapshot,
  27. readSSHRuntimeConfig,
  28. runSSHCommand,
  29. selectSSHRemoteDirectory,
  30. waitForRemoteTab,
  31. waitForSSHDirectoryStep,
  32. type SSHConnectionConfig,
  33. } from "#e2e/helpers/ssh-remote-p0";
  34. const CASE_MARKER = "E2E_R3_INSTALL_FAULTS";
  35. // 从当前 spec 回到 desktop,保持隔离 mock-cdn 与版本文件定位正确。
  36. const DESKTOP_ROOT = resolve(import.meta.dirname, "../../../../..");
  37. const artifactDir = resolve(
  38. process.env.ZCODE_E2E_ARTIFACT_DIR ?? ".e2e-artifacts/r3-install-faults",
  39. );
  40. interface FaultRecord {
  41. fault: string;
  42. target: string;
  43. archiveFileName: string;
  44. port: number;
  45. dialogState: string;
  46. errorText: string;
  47. remoteInstalledAfter: string;
  48. remoteTabSessionId: string | null;
  49. hostsUnchanged: boolean;
  50. }
  51. /** WDIO 每次 run 会把 mock-cdn release 硬链接到 runId 隔离目录;这里只改隔离目录里的文件,先解链再写。 */
  52. async function stagedReleaseDir(): Promise<string> {
  53. const runId = process.env.ZCODE_E2E_RUN_ID?.trim();
  54. if (!runId) throw new Error(`${CASE_MARKER}: ZCODE_E2E_RUN_ID 缺失`);
  55. // WDIO worker 的 ZCODE_VERSION 是 dev 值,staged 目录使用仓库版本;文件读取保持异步。
  56. const { version } = JSON.parse(
  57. await readFile(resolve(DESKTOP_ROOT, "../../package.json"), "utf8"),
  58. );
  59. return join(DESKTOP_ROOT, ".e2e-cache", runId, "mock-cdn", "releases", version);
  60. }
  61. async function remoteInstalledState(config: SSHConnectionConfig): Promise<string> {
  62. const result = await runSSHCommand(
  63. config,
  64. 'if [ -f "$HOME/.zcode/server/current.json" ]; then grep -o \'"archiveSha256": *"[0-9a-f]*"\' "$HOME/.zcode/server/current.json"; else echo none; fi',
  65. );
  66. return result.stdout.trim() || `exit=${result.code}`;
  67. }
  68. async function attemptConnectExpectingFailure(
  69. config: SSHConnectionConfig,
  70. fault: string,
  71. initialHosts: Array<{ name: string; pid: number }>,
  72. archive: SourceServerReleaseArchive,
  73. ): Promise<FaultRecord> {
  74. await openSSHRemoteDialog(CASE_MARKER);
  75. await fillSSHPasswordSettings(config);
  76. await clickLastEnabledSSHDialogButton(CASE_MARKER);
  77. // 未安装目标会先出现安装确认;确认后 release 解析必须以明确错误结束,不能回退到未知旧包。
  78. let errorText = "";
  79. let dialogState = "waiting";
  80. let record: FaultRecord;
  81. try {
  82. await browser.waitUntil(
  83. async () => {
  84. const state = await browser.execute(() => {
  85. const error = document.querySelector<HTMLElement>('[data-testid="ssh-error"]');
  86. if (error?.getClientRects().length) return `error:${error.innerText.trim()}`;
  87. const dialog = document.querySelector('[data-testid="ssh-dialog"]');
  88. const install = Array.from(
  89. dialog?.querySelectorAll<HTMLButtonElement>("button") ?? [],
  90. ).find(
  91. (item) =>
  92. item.getClientRects().length &&
  93. !item.disabled &&
  94. ["安装并继续", "Install and continue"].includes(item.innerText.trim()),
  95. );
  96. if (install) {
  97. install.click();
  98. return "confirmed";
  99. }
  100. return dialog ? "waiting" : "dialog-gone";
  101. });
  102. dialogState = state.startsWith("error:") ? "error" : state;
  103. // 终态交给循环外断言,避免 waitUntil 吞掉异常后继续轮询 120 秒。
  104. if (state === "dialog-gone") return true;
  105. if (state.startsWith("error:")) {
  106. errorText = state.slice("error:".length);
  107. return true;
  108. }
  109. return false;
  110. },
  111. { timeout: 120_000, interval: 300, timeoutMsg: `${CASE_MARKER}: ${fault} 没有显示明确错误` },
  112. );
  113. } finally {
  114. const snapshot = await readRemoteTabSnapshot();
  115. record = {
  116. fault,
  117. target: archive.target,
  118. archiveFileName: archive.fileName,
  119. port: config.port,
  120. dialogState,
  121. errorText,
  122. remoteInstalledAfter: await remoteInstalledState(config),
  123. remoteTabSessionId: snapshot.remoteSessionId,
  124. hostsUnchanged: JSON.stringify(await readHostProcesses()) === JSON.stringify(initialHosts),
  125. };
  126. await mkdir(artifactDir, { recursive: true });
  127. await writeFile(resolve(artifactDir, `${fault}.json`), JSON.stringify(record, null, 2));
  128. }
  129. if (dialogState === "dialog-gone") {
  130. throw new Error(`${CASE_MARKER}: ${fault} 未停留在错误态: ${JSON.stringify(record)}`);
  131. }
  132. // 当前错误面板默认展示用户可读分类,原始内部异常收进详细信息;不能再要求主面板直接显示英文实现名。
  133. expect(record.errorText).toMatch(/资源|校验|安装包|release|archive|verification/iu);
  134. expect(record.errorText).not.toContain(config.password);
  135. expect(record.hostsUnchanged).toBe(true);
  136. await closeSSHDialogFromError();
  137. return record;
  138. }
  139. async function closeSSHDialogFromError(): Promise<void> {
  140. await browser.waitUntil(
  141. () =>
  142. browser.execute(() => {
  143. const dialog = document.querySelector<HTMLElement>('[data-testid="ssh-dialog"]');
  144. if (!dialog) return true;
  145. const back = Array.from(dialog.querySelectorAll<HTMLButtonElement>("button")).find(
  146. (item) =>
  147. item.getClientRects().length &&
  148. !item.disabled &&
  149. ["返回配置", "Back to settings", "关闭", "Close"].includes(item.innerText.trim()),
  150. );
  151. back?.click();
  152. const close = document.querySelector<HTMLButtonElement>(
  153. '[data-testid="ssh-dialog"] button[aria-label="Close"], [data-testid="ssh-dialog"] button[aria-label="关闭"]',
  154. );
  155. close?.click();
  156. return false;
  157. }),
  158. { timeout: 30_000, interval: 300, timeoutMsg: `${CASE_MARKER}: 失败后无法关闭 SSH 向导` },
  159. );
  160. await browser.keys(["Escape"]);
  161. await browser.waitUntil(
  162. () => browser.execute(() => !document.querySelector('[data-testid="ssh-dialog"]')),
  163. { timeout: 15_000, timeoutMsg: `${CASE_MARKER}: SSH 向导没有关闭` },
  164. );
  165. }
  166. describe(`${CASE_MARKER}: 本地 release 产物缺失/校验失败与安装确认取消`, () => {
  167. const records: FaultRecord[] = [];
  168. after(async () => {
  169. await mkdir(artifactDir, { recursive: true });
  170. await writeFile(resolve(artifactDir, "install-faults.json"), JSON.stringify(records, null, 2));
  171. await browser.electron.restoreAllMocks();
  172. await clearAppData();
  173. });
  174. it("R3A-BLD-04/06 descriptor 缺失、archive 缺失、SHA/size 不符均明确失败且不落地;取消确认后重试成功", async function () {
  175. this.timeout(30 * 60_000);
  176. const fresh = readSSHRuntimeConfig(CASE_MARKER);
  177. const dual = readDualSSHRuntimeConfig(CASE_MARKER);
  178. const installedTarget = dual.targets[1];
  179. // 预装对照目标也要先完成桌面初始化;不能在登录/恢复尚未就绪时直接点击新任务。
  180. await prepareV4ConversationE2E({ skipProvider: true });
  181. const initialHosts = await readHostProcesses();
  182. expect(initialHosts).toHaveLength(1);
  183. expect(await remoteInstalledState(fresh)).toBe("none");
  184. // runner 的 dual 是两个全新容器:B 作为“已安装目标”对照(installed-target
  185. // tampered 步骤与下方 installedBefore 断言的前置),必须先完整走一次连接安装。
  186. const preinstalled = await connectSSHWorkspace({
  187. caseMarker: CASE_MARKER,
  188. config: installedTarget,
  189. workspacePath: dual.workspacePath,
  190. });
  191. expect(preinstalled.remoteSessionId).toBeTruthy();
  192. const installedBefore = await remoteInstalledState(installedTarget);
  193. expect(installedBefore).toContain("archiveSha256");
  194. // 根因:B 首装后仍在线时会直接复用现有会话,根本不读取被篡改的本地包。
  195. // 通过真实 UI 断开并等待同一 identity 离线,才能覆盖已安装目标的重新校验路径。
  196. const installedIdentity = preinstalled.workspaceIdentity!;
  197. const installedSourceId = parseRemoteWorkspaceIdentity(installedIdentity)?.sourceServerId;
  198. expect(installedSourceId).toBeTruthy();
  199. await selectTaskOrganizeMode(["项目", "Project"]);
  200. await disconnectRemoteSource(installedSourceId!, CASE_MARKER, {
  201. workspaceIdentities: [installedIdentity],
  202. });
  203. // 断开后主区域仍停在 B 的离线页,准备 helper 只等待就绪,不负责切回本地。
  204. await openWorkspaceDraftFromSidebar(DEFAULT_WORKSPACE);
  205. const releaseDir = await stagedReleaseDir();
  206. const descriptorPath = join(releaseDir, SOURCE_SERVER_RELEASE_DESCRIPTOR_FILE_NAME);
  207. const originalDescriptor = await readFile(descriptorPath, "utf8");
  208. const descriptor = sourceServerReleaseDescriptorSchema.parse(JSON.parse(originalDescriptor));
  209. const readTargetArchive = async (config: SSHConnectionConfig) => {
  210. const environment = await runSSHCommand(config, "uname -s && uname -m");
  211. expect(environment.code).toBe(0);
  212. const [platform = "", arch = ""] = environment.stdout.trim().split(/\r?\n/);
  213. const entry = selectSourceServerReleaseArchive(descriptor, { platform, arch });
  214. const path = join(releaseDir, entry.fileName);
  215. const bytes = await readFile(path);
  216. expect(createHash("sha256").update(bytes).digest("hex")).toBe(entry.sha256);
  217. expect((await stat(path)).size).toBe(entry.sizeBytes);
  218. return { entry, path, bytes };
  219. };
  220. const freshArchive = await readTargetArchive(fresh);
  221. const installedArchive = await readTargetArchive(installedTarget);
  222. expect(installedBefore).toContain(installedArchive.entry.sha256);
  223. expect(await readHostProcesses()).toEqual(initialHosts);
  224. const expectFreshFailure = async (fault: string) => {
  225. const record = await attemptConnectExpectingFailure(
  226. fresh,
  227. fault,
  228. initialHosts,
  229. freshArchive.entry,
  230. );
  231. records.push(record);
  232. expect(record.remoteInstalledAfter).toBe("none");
  233. expect(record.remoteTabSessionId).toBeNull();
  234. };
  235. // 1. descriptor 缺失;后续每次注入都在 finally 恢复,不依赖成功断言收尾。
  236. await withSourceServerReleaseFileFault(descriptorPath, null, () =>
  237. expectFreshFailure("descriptor-missing"),
  238. );
  239. // 2. 必须移走 A 实际使用的包,不能用 x64 常量模拟 ARM64 的安装失败。
  240. await withSourceServerReleaseFileFault(freshArchive.path, null, () =>
  241. expectFreshFailure("archive-missing"),
  242. );
  243. // 3. 保持 size 不变,只破坏 SHA,避免 size 校验提前拒绝而未覆盖 SHA 校验。
  244. const tamperedArchive = Buffer.from(freshArchive.bytes);
  245. tamperedArchive[0] = tamperedArchive[0]! ^ 1;
  246. await withSourceServerReleaseFileFault(freshArchive.path, tamperedArchive, () =>
  247. expectFreshFailure("archive-sha-mismatch"),
  248. );
  249. // 4. 仅修改 A 对应 descriptor 条目的 size,SHA 和 archive 保持正确。
  250. const sizeTampered = {
  251. ...descriptor,
  252. archives: descriptor.archives.map((entry) =>
  253. entry.target === freshArchive.entry.target
  254. ? { ...entry, sizeBytes: entry.sizeBytes + 1 }
  255. : entry,
  256. ),
  257. };
  258. await withSourceServerReleaseFileFault(descriptorPath, JSON.stringify(sizeTampered), () =>
  259. expectFreshFailure("descriptor-size-mismatch"),
  260. );
  261. // 5. B 的架构独立选取;损坏本地产物不得改写 B 的既有远端安装。
  262. await withSourceServerReleaseFileFault(
  263. installedArchive.path,
  264. Buffer.concat([installedArchive.bytes, Buffer.from("e2e-tamper")]),
  265. async () => {
  266. const record = await attemptConnectExpectingFailure(
  267. installedTarget,
  268. "installed-target-local-archive-tampered",
  269. initialHosts,
  270. installedArchive.entry,
  271. );
  272. records.push(record);
  273. expect(record.remoteInstalledAfter).toBe(installedBefore);
  274. },
  275. );
  276. // 6. BLD-06:产物恢复后,安装确认点取消 -> 远端无安装、无 pending 会话;重连确认 -> 成功安装
  277. await openSSHRemoteDialog(CASE_MARKER);
  278. await fillSSHPasswordSettings(fresh);
  279. await clickLastEnabledSSHDialogButton(CASE_MARKER);
  280. await browser.waitUntil(
  281. () =>
  282. browser.execute(() => {
  283. const dialog = document.querySelector('[data-testid="ssh-dialog"]');
  284. const buttons = Array.from(dialog?.querySelectorAll<HTMLButtonElement>("button") ?? []);
  285. const install = buttons.find(
  286. (item) =>
  287. item.getClientRects().length &&
  288. ["安装并继续", "Install and continue"].includes(item.innerText.trim()),
  289. );
  290. if (!install) return false;
  291. const cancel = buttons.find(
  292. (item) =>
  293. item.getClientRects().length &&
  294. !item.disabled &&
  295. ["取消", "Cancel"].includes(item.innerText.trim()),
  296. );
  297. if (!cancel) return false;
  298. cancel.click();
  299. return true;
  300. }),
  301. { timeout: 90_000, interval: 300, timeoutMsg: `${CASE_MARKER}: 没有出现可取消的安装确认` },
  302. );
  303. await browser.pause(3000);
  304. const afterCancel = {
  305. remoteInstalled: await remoteInstalledState(fresh),
  306. remoteTabSessionId: (await readRemoteTabSnapshot()).remoteSessionId,
  307. dialogState: await browser.execute(() => {
  308. const dialog = document.querySelector<HTMLElement>('[data-testid="ssh-dialog"]');
  309. return dialog ? dialog.innerText.slice(0, 400) : "dialog-gone";
  310. }),
  311. hosts: await readHostProcesses(),
  312. };
  313. expect(afterCancel.remoteInstalled).toBe("none");
  314. expect(afterCancel.remoteTabSessionId).toBeNull();
  315. expect(afterCancel.hosts).toEqual(initialHosts);
  316. await mkdir(artifactDir, { recursive: true });
  317. await writeFile(
  318. resolve(artifactDir, "install-cancel.json"),
  319. JSON.stringify(afterCancel, null, 2),
  320. );
  321. if (afterCancel.dialogState !== "dialog-gone") {
  322. await browser.keys(["Escape"]);
  323. await browser.waitUntil(
  324. () => browser.execute(() => !document.querySelector('[data-testid="ssh-dialog"]')),
  325. { timeout: 15_000, timeoutMsg: `${CASE_MARKER}: 取消安装后向导没有关闭` },
  326. );
  327. }
  328. await openSSHRemoteDialog(CASE_MARKER);
  329. await fillSSHPasswordSettings(fresh);
  330. await clickLastEnabledSSHDialogButton(CASE_MARKER);
  331. // 取消安装后远端仍无 server,再次连接还会停在安装确认(inline 在 connecting
  332. // 步);缺这一步安装确认悬挂,conversation 永不打开(settings-scopes 0910
  333. // 实锤:auth 成功 → probe INSTALLED=0 → 无后续 channel 活动直至超时)。
  334. await waitForSSHDirectoryStep(CASE_MARKER);
  335. await selectSSHRemoteDirectory(fresh.workspacePaths[0], CASE_MARKER);
  336. const tab = await waitForRemoteTab({
  337. caseMarker: CASE_MARKER,
  338. expectedPath: fresh.workspacePaths[0],
  339. });
  340. expect(tab.remoteSessionId).toBeTruthy();
  341. expect(await remoteInstalledState(fresh)).toContain(freshArchive.entry.sha256);
  342. expect(await readHostProcesses()).toEqual(initialHosts);
  343. const project = await connectSSHWorkspace({
  344. caseMarker: CASE_MARKER,
  345. config: fresh,
  346. workspacePath: fresh.workspacePaths[0],
  347. });
  348. expect(project.remoteSessionId).toBeTruthy();
  349. });
  350. });