conversation-session-ssh-probe-validation.test.ts 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261
  1. import { mkdir, writeFile } from "node:fs/promises";
  2. import { resolve } from "node:path";
  3. import {
  4. parseRemoteWorkspaceIdentity,
  5. ServiceChannels,
  6. type SourceServerManagementSnapshot,
  7. } from "@zcode/shared";
  8. import { TID_SETTINGS_BACK_BUTTON } from "@zcode/shared/test-ids";
  9. import { clearAppData, clickTestIdByDom, readSettings } from "#e2e/helpers/desktop-app";
  10. import {
  11. execInRemoteContainer,
  12. readRemoteContainerFile,
  13. readRemoteDockerContainer,
  14. writeRemoteContainerFile,
  15. } from "#e2e/helpers/remote-docker-target";
  16. import {
  17. connectRemoteSourceFromSettings,
  18. disconnectRemoteSource,
  19. waitForDeviceStatus,
  20. } from "#e2e/helpers/remote-project-actions";
  21. import { callHandoffHost, installHandoffRpcProbe } from "#e2e/helpers/remote-project-handoff-probe";
  22. import {
  23. clickLastEnabledSSHDialogButton,
  24. connectSSHWorkspace,
  25. fillSSHPasswordSettings,
  26. openSSHRemoteDialog,
  27. readSSHRuntimeConfig,
  28. } from "#e2e/helpers/ssh-remote-p0";
  29. import { prepareV4ConversationE2E } from "#e2e/helpers/v4-conversation";
  30. const MARKER = "E2E_SSH_PROBE_VALIDATION";
  31. const FIXTURE_ROOT = "/tmp/zcode-probe-validation";
  32. const artifactDir = resolve(
  33. process.env.ZCODE_E2E_ARTIFACT_DIR ?? ".e2e-artifacts/ssh-probe-validation",
  34. );
  35. const INVALID_CASES = [
  36. { mode: "empty", detail: "PLATFORM" },
  37. { mode: "missing-platform", detail: "PLATFORM" },
  38. { mode: "missing-arch", detail: "ARCH" },
  39. { mode: "missing-root", detail: "ROOT" },
  40. { mode: "missing-installed", detail: "INSTALLED" },
  41. { mode: "invalid-installed", detail: "INSTALLED" },
  42. { mode: "missing-end", detail: "END" },
  43. { mode: "uname-failure", detail: "E2E_PROBE_UNAME_FAILED" },
  44. ] as const;
  45. // 只影响本次容器 dev 用户的探测命令:正常执行仍进入原登录 shell,SFTP、安装与 daemon 不替换。
  46. // 故障来自真实 SSH shell 的输出或命令失败,不 mock Host probe、连接管理器或安装状态。
  47. function fixtureShell(originalShell: string): string {
  48. return `#!/bin/sh
  49. case "$*" in
  50. *__ZCODE_PROBE_PLATFORM__*)
  51. mode=$(cat ${FIXTURE_ROOT}/mode)
  52. case "$mode" in
  53. empty) printf 'E2E_PROBE_EMPTY_OUTPUT\\n' >&2; exit 0 ;;
  54. missing-platform) ${originalShell} "$@" | sed '/^__ZCODE_PROBE_PLATFORM__$/ {n;s/.*//;}'; exit 0 ;;
  55. missing-arch) ${originalShell} "$@" | sed '/^__ZCODE_PROBE_ARCH__$/ {n;s/.*//;}'; exit 0 ;;
  56. missing-root) ${originalShell} "$@" | sed '/^__ZCODE_PROBE_ROOT__$/ {n;s/.*//;}'; exit 0 ;;
  57. missing-installed) ${originalShell} "$@" | sed '/^__ZCODE_PROBE_INSTALLED__$/ {N;d;}'; exit 0 ;;
  58. invalid-installed) ${originalShell} "$@" | sed '/^__ZCODE_PROBE_INSTALLED__$/ {n;s/.*/unknown/;}'; exit 0 ;;
  59. missing-end) ${originalShell} "$@" | sed '/^__ZCODE_PROBE_END__$/d'; exit 0 ;;
  60. uname-failure) PATH=${FIXTURE_ROOT}/bin:$PATH; export PATH ;;
  61. esac
  62. ;;
  63. esac
  64. exec ${originalShell} "$@"
  65. `;
  66. }
  67. async function closeConnectionDialog() {
  68. await browser.keys("Escape");
  69. await $('[data-testid="ssh-dialog"]').waitForExist({ reverse: true, timeout: 15_000 });
  70. }
  71. /** 同时观察错误和安装等待点,旧实现不能靠停在安装确认把失败场景假装成仍在连接。 */
  72. async function readProbeOutcome() {
  73. let outcome = { kind: "pending", text: "", details: "" };
  74. await browser.waitUntil(
  75. async () => {
  76. outcome = await browser.execute(() => {
  77. const panel = document.querySelector<HTMLElement>('[data-testid="ssh-error"]');
  78. if (panel?.getClientRects().length) {
  79. return {
  80. kind: "error",
  81. text: panel.innerText,
  82. details: panel.querySelector("details pre")?.textContent ?? "",
  83. };
  84. }
  85. const install = Array.from(
  86. document.querySelectorAll<HTMLButtonElement>('[data-testid="ssh-dialog"] button'),
  87. ).some(
  88. (item) =>
  89. item.getClientRects().length && /安装并继续|Install and continue/u.test(item.innerText),
  90. );
  91. return { kind: install ? "install" : "pending", text: "", details: "" };
  92. });
  93. return outcome.kind !== "pending";
  94. },
  95. { timeout: 60_000, timeoutMsg: `${MARKER}: 探测没有返回错误或安装等待点` },
  96. );
  97. return outcome;
  98. }
  99. describe(`${MARKER}: 探测失败不伪装为系统不支持或未安装`, () => {
  100. const facts: Record<string, unknown> = {};
  101. let container: string;
  102. let originalShell: string;
  103. before(async () => {
  104. container = readRemoteDockerContainer(MARKER);
  105. const config = readSSHRuntimeConfig(MARKER);
  106. // fixture 限定 runner 新建的 dev 用户,不能改共享机器或其它账号的登录 shell。
  107. expect(config.username).toBe("dev");
  108. originalShell = (await execInRemoteContainer(container, ["getent", "passwd", "dev"])).stdout
  109. .trim()
  110. .split(":")
  111. .at(-1)!;
  112. expect(originalShell).toMatch(/^\/bin\/(?:ba)?sh$/u);
  113. facts.architecture = (await execInRemoteContainer(container, ["uname", "-m"])).stdout.trim();
  114. await writeRemoteContainerFile(container, `${FIXTURE_ROOT}/mode`, "normal\n");
  115. await writeRemoteContainerFile(container, `${FIXTURE_ROOT}/shell`, fixtureShell(originalShell));
  116. await writeRemoteContainerFile(
  117. container,
  118. `${FIXTURE_ROOT}/bin/uname`,
  119. "#!/bin/sh\nprintf 'E2E_PROBE_UNAME_FAILED\\n' >&2\nexit 9\n",
  120. );
  121. await execInRemoteContainer(container, [
  122. "chmod",
  123. "+x",
  124. `${FIXTURE_ROOT}/shell`,
  125. `${FIXTURE_ROOT}/bin/uname`,
  126. ]);
  127. await execInRemoteContainer(container, ["usermod", "-s", `${FIXTURE_ROOT}/shell`, "dev"], {
  128. user: "0",
  129. });
  130. await mkdir(artifactDir, { recursive: true });
  131. await prepareV4ConversationE2E({ skipProvider: true });
  132. });
  133. after(async () => {
  134. if (container && originalShell) {
  135. await execInRemoteContainer(container, ["usermod", "-s", originalShell, "dev"], {
  136. user: "0",
  137. });
  138. await execInRemoteContainer(container, ["rm", "-rf", FIXTURE_ROOT]);
  139. }
  140. await mkdir(artifactDir, { recursive: true });
  141. await writeFile(resolve(artifactDir, "probe-validation.json"), JSON.stringify(facts, null, 2));
  142. await browser.electron.restoreAllMocks();
  143. await clearAppData();
  144. });
  145. afterEach(async () => {
  146. await writeRemoteContainerFile(container, `${FIXTURE_ROOT}/mode`, "normal\n");
  147. if (await $('[data-testid="ssh-dialog"]').isExisting()) await closeConnectionDialog();
  148. if (await $('[data-testid="settings-page"]').isDisplayed())
  149. await clickTestIdByDom(TID_SETTINGS_BACK_BUTTON);
  150. });
  151. it("RDUX-11-11 空输出、必需字段缺失或非法、uname 失败均在安装前报告探测失败", async function () {
  152. this.timeout(10 * 60_000);
  153. const config = readSSHRuntimeConfig(MARKER);
  154. for (const item of INVALID_CASES) {
  155. await writeRemoteContainerFile(container, `${FIXTURE_ROOT}/mode`, `${item.mode}\n`);
  156. await openSSHRemoteDialog(MARKER, { entry: "settings" });
  157. await fillSSHPasswordSettings(config);
  158. await clickLastEnabledSSHDialogButton(MARKER);
  159. const outcome = await readProbeOutcome();
  160. facts[item.mode] = outcome;
  161. expect(outcome.kind).toBe("error");
  162. expect(outcome.text).toContain("远端环境检查失败");
  163. expect(outcome.text).not.toContain("不支持该设备的系统");
  164. expect(outcome.details).toContain(item.detail);
  165. expect(outcome.details).not.toContain(config.password);
  166. if (item.mode === "empty") expect(outcome.details).toContain("E2E_PROBE_EMPTY_OUTPUT");
  167. await browser.saveScreenshot(resolve(artifactDir, `${item.mode}.png`));
  168. await closeConnectionDialog();
  169. }
  170. await clickTestIdByDom(TID_SETTINGS_BACK_BUTTON);
  171. });
  172. it("RDUX-11-12 已有设备探测结果不完整时保留安装状态,恢复后同一 Source 重连且不重装", async function () {
  173. this.timeout(15 * 60_000);
  174. await writeRemoteContainerFile(container, `${FIXTURE_ROOT}/mode`, "normal\n");
  175. const config = readSSHRuntimeConfig(MARKER);
  176. const tab = await connectSSHWorkspace({
  177. caseMarker: MARKER,
  178. config,
  179. workspacePath: config.workspacePaths[0],
  180. });
  181. const sourceId = parseRemoteWorkspaceIdentity(tab.workspaceIdentity!)?.sourceServerId;
  182. if (!sourceId) throw new Error(`${MARKER}: 正常首连没有 Source 身份`);
  183. await installHandoffRpcProbe();
  184. const readSnapshot = () =>
  185. callHandoffHost<SourceServerManagementSnapshot>(
  186. ServiceChannels.SourceServerManagement,
  187. "getSnapshot",
  188. );
  189. const before = await readSnapshot();
  190. const source = before.servers.find((item) => item.sourceServerId === sourceId)!;
  191. expect(source.installState).toBe("installed");
  192. const currentBefore = await readRemoteContainerFile(
  193. container,
  194. "/home/dev/.zcode/server/current.json",
  195. );
  196. await disconnectRemoteSource(sourceId, MARKER);
  197. await writeRemoteContainerFile(container, `${FIXTURE_ROOT}/mode`, "missing-installed\n");
  198. await connectRemoteSourceFromSettings(sourceId, MARKER);
  199. await waitForDeviceStatus(sourceId, "failed", MARKER);
  200. // 失败由连接弹窗展示,直接核对当前错误面板,避免点击遮罩后的设备行。
  201. const failure = await readProbeOutcome();
  202. facts.existingSourceFailure = failure;
  203. expect(failure.kind).toBe("error");
  204. expect(failure.text).toContain("远端环境检查失败");
  205. expect(failure.details).toContain("INSTALLED");
  206. const failed = await readSnapshot();
  207. facts.retainedState = { before, failed };
  208. expect(failed.servers.find((item) => item.sourceServerId === sourceId)?.installState).toBe(
  209. "installed",
  210. );
  211. expect(
  212. (await readSettings()).sourceServers?.find((item) => item.sourceServerId === sourceId)
  213. ?.installState,
  214. ).toBe("installed");
  215. expect(failed.profiles.map((item) => [item.profileId, item.sourceServerId])).toEqual(
  216. before.profiles.map((item) => [item.profileId, item.sourceServerId]),
  217. );
  218. expect(failed.workspaceHistory).toEqual(before.workspaceHistory);
  219. // 瞬态连接状态按 profileId 索引;握手前失败允许不带 sourceServerId,持久身份绑定已在上方断言。
  220. const profileId = before.profiles.find((item) => item.sourceServerId === sourceId)?.profileId;
  221. expect(profileId).toBeTruthy();
  222. expect(failed.states.find((item) => item.profileId === profileId)).toMatchObject({
  223. state: "failed",
  224. errorCode: "remote-preflight-failed",
  225. });
  226. await browser.saveScreenshot(resolve(artifactDir, "existing-source-probe-failed.png"));
  227. await writeRemoteContainerFile(container, `${FIXTURE_ROOT}/mode`, "normal\n");
  228. // failed 状态的主动作是“重试”,直接使用当前错误面板,不误用仅匹配“连接”的离线设备 helper。
  229. await $('[data-testid="ssh-error"]')
  230. .$('.//button[normalize-space(.)="重试" or normalize-space(.)="Retry"]')
  231. .click();
  232. await waitForDeviceStatus(sourceId, "online", MARKER, 120_000);
  233. const recovered = await readSnapshot();
  234. facts.recovered = recovered;
  235. expect(recovered.servers.find((item) => item.sourceServerId === sourceId)?.installState).toBe(
  236. "installed",
  237. );
  238. expect(await readRemoteContainerFile(container, "/home/dev/.zcode/server/current.json")).toBe(
  239. currentBefore,
  240. );
  241. const profile = recovered.profiles.find((item) => item.sourceServerId === sourceId)!;
  242. const logs = await callHandoffHost<Array<{ message: string }>>(
  243. ServiceChannels.SourceServerManagement,
  244. "getRecentOperationLogs",
  245. [profile.profileId],
  246. );
  247. expect(logs.some((item) => /Uploading|Extracting|Installing/u.test(item.message))).toBe(false);
  248. await browser.saveScreenshot(resolve(artifactDir, "existing-source-recovered.png"));
  249. });
  250. });