conversation-session-ssh-remote-legacy-install-handoff.test.ts 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523
  1. import { mkdir, readFile, rm, writeFile } from "node:fs/promises";
  2. import { join, resolve } from "node:path";
  3. import type { RemoteWorkspaceSessionEntry } from "@zcode/shared";
  4. import { PlatformChannels } from "@zcode/shared";
  5. import {
  6. clearAppData,
  7. getE2EAppDataPaths,
  8. pinE2ELocale,
  9. readSettings,
  10. seedSettings,
  11. } from "#e2e/helpers/desktop-app";
  12. import { reloadElectronSessionPreservingBrowserProfile } from "#e2e/helpers/e2e-electron-reload";
  13. import { clickRemoteHostConnect, waitForProjectRow } from "#e2e/helpers/project-sidebar";
  14. import {
  15. execInRemoteContainer,
  16. readRemoteDockerContainer,
  17. } from "#e2e/helpers/remote-docker-target";
  18. import {
  19. clickLastEnabledSSHDialogButton,
  20. fillSSHPasswordSettings,
  21. openSSHRemoteDialog,
  22. readSSHRuntimeConfig,
  23. selectSSHRemoteDirectory,
  24. waitForRemoteTab,
  25. waitForSSHDirectoryStep,
  26. type SSHConnectionConfig,
  27. } from "#e2e/helpers/ssh-remote-p0";
  28. import { waitForRendererAfterColdRestart } from "#e2e/helpers/ssh-remote-lifecycle";
  29. import { prepareV4ConversationE2E } from "#e2e/helpers/v4-conversation";
  30. // 3.16.2 工单的真实 SSH 验证(本机 Docker runner):
  31. // - 缺陷 A(ZCT-2113085028132474880 / ZCT-2113021923315200000):3.15 迁移的密码 SSH 项目,远端未装
  32. // Source Server。项目入口交给向导的目标不含凭据,确认安装后报“SSH 认证失败”。
  33. // - ZCT-2112984371086536704:第一次需要安装时取消,第二次点同一项目只看到过期的“连接失败”,
  34. // 不重连、没有安装确认;向导错误面板的“安装并连接”实际走不带确认的重试。
  35. // - 上一条的第一版修复在线路未识别时忽略全部失败记录:普通失败后每次点击都静默重拨,向导打不开
  36. // (违反项目导航规格 §2.2“再次点击进入向导……不自动再次拨号”)。LIH-03 覆盖该回归。
  37. // - CR-01:新重连失败没有错误码时仍被当成旧记录。LIH-04 在真实认证失败响应上移除码,覆盖该遗漏。
  38. // 迁移形状:App 退出后删除项目库,写入 3.15 的远程 workspace 条目与已存密码,清空 Source Directory
  39. // 迁移版本,冷启动时由当前版本完成迁移(与 legacy-remote-credential-decrypt 用例同一方式)。
  40. const MARKER = "E2E_SSH_LEGACY_INSTALL_HANDOFF";
  41. const PROJECT_DIR = "legacy-install-project";
  42. // LIH-03 的普通失败:远端 PAM 先记录每次认证尝试,再拒绝认证(不是等待点)。
  43. const AUTH_ATTEMPTS_FILE = "/tmp/zcode-e2e-auth-attempts";
  44. const AUTH_ATTEMPT_SCRIPT = "/usr/local/bin/zcode-e2e-auth-attempt";
  45. const PAM_COUNT_LINE = `auth optional pam_exec.so quiet ${AUTH_ATTEMPT_SCRIPT}`;
  46. const PAM_DENY_LINE = "auth requisite pam_deny.so";
  47. const artifactDir = resolve(
  48. process.env.ZCODE_E2E_ARTIFACT_DIR ?? ".e2e-artifacts/ssh-remote-legacy-install-handoff",
  49. );
  50. interface WizardState {
  51. open: boolean;
  52. installPanel: boolean;
  53. errorText: string | null;
  54. buttons: string[];
  55. }
  56. type LegacyConnectHandler = (...args: unknown[]) => Promise<unknown>;
  57. declare global {
  58. var __legacyTabConnectProbe:
  59. | { calls: number; removedCodes: string[]; restore(): void }
  60. | undefined;
  61. }
  62. /** 保留真实 SSH 失败,只在 Main 返回边界模拟旧 Host 没有 reasonCode 的响应。 */
  63. async function installLegacyConnectProbe(stripCode: boolean): Promise<void> {
  64. await browser.electron.execute(
  65. (electron, channel, stripCode) => {
  66. const handlers = (
  67. electron.ipcMain as unknown as { _invokeHandlers: Map<string, LegacyConnectHandler> }
  68. )._invokeHandlers;
  69. const original = handlers.get(channel);
  70. if (!original) throw new Error("ConnectRemote handler unavailable");
  71. const probe = {
  72. calls: 0,
  73. removedCodes: [] as string[],
  74. restore() {
  75. handlers.set(channel, original);
  76. delete globalThis.__legacyTabConnectProbe;
  77. },
  78. };
  79. handlers.set(channel, async (...args) => {
  80. probe.calls++;
  81. const result = await original(...args);
  82. if (!stripCode || !result || typeof result !== "object" || !("reasonCode" in result))
  83. return result;
  84. if (typeof result.reasonCode === "string") probe.removedCodes.push(result.reasonCode);
  85. const uncoded: { reasonCode?: unknown } = { ...result };
  86. delete uncoded.reasonCode;
  87. return uncoded;
  88. });
  89. globalThis.__legacyTabConnectProbe = probe;
  90. },
  91. PlatformChannels.ConnectRemote,
  92. stripCode,
  93. );
  94. }
  95. const readLegacyConnectProbe = () =>
  96. browser.electron.execute(() => ({
  97. calls: globalThis.__legacyTabConnectProbe?.calls ?? 0,
  98. removedCodes: globalThis.__legacyTabConnectProbe?.removedCodes ?? [],
  99. }));
  100. async function readWizardState(): Promise<WizardState> {
  101. return browser.execute(() => {
  102. const dialog = document.querySelector<HTMLElement>('[data-testid="ssh-dialog"]');
  103. const visibleButtons = Array.from(dialog?.querySelectorAll<HTMLButtonElement>("button") ?? [])
  104. .filter((button) => button.getClientRects().length > 0)
  105. .map((button) => button.textContent?.trim() ?? "");
  106. const error = dialog?.querySelector<HTMLElement>('[data-testid="ssh-error"]');
  107. return {
  108. open: Boolean(dialog && dialog.getClientRects().length > 0),
  109. installPanel: Boolean(dialog?.querySelector('[data-testid="remote-install-version"]')),
  110. errorText: error && error.getClientRects().length > 0 ? error.innerText.trim() : null,
  111. buttons: visibleButtons,
  112. };
  113. });
  114. }
  115. async function waitForWizard(
  116. predicate: (state: WizardState) => boolean,
  117. description: string,
  118. timeout = 90_000,
  119. ): Promise<WizardState> {
  120. let last: WizardState = { open: false, installPanel: false, errorText: null, buttons: [] };
  121. await browser.waitUntil(
  122. async () => {
  123. last = await readWizardState();
  124. return predicate(last);
  125. },
  126. {
  127. timeout,
  128. interval: 300,
  129. timeoutMsg: `${MARKER}: ${description} 未出现;最后状态 ${JSON.stringify(last)}`,
  130. },
  131. );
  132. return last;
  133. }
  134. /** 只在指定面板内按文案点击,避免误点页脚或其他面板的同名按钮。 */
  135. async function clickWizardButton(scope: "install" | "error", text: string): Promise<void> {
  136. const clicked = await browser.execute(
  137. (panel, label) => {
  138. const dialog = document.querySelector('[data-testid="ssh-dialog"]');
  139. const container =
  140. panel === "install"
  141. ? dialog?.querySelector('[data-testid="remote-install-version"]')?.closest("dl")
  142. ?.parentElement
  143. : dialog?.querySelector('[data-testid="ssh-error"]');
  144. const button = Array.from(
  145. container?.querySelectorAll<HTMLButtonElement>("button") ?? [],
  146. ).find(
  147. (candidate) =>
  148. candidate.getClientRects().length > 0 &&
  149. !candidate.disabled &&
  150. candidate.textContent?.trim() === label,
  151. );
  152. button?.click();
  153. return Boolean(button);
  154. },
  155. scope,
  156. text,
  157. );
  158. if (!clicked) throw new Error(`${MARKER}: ${scope} 面板没有可点击的「${text}」`);
  159. }
  160. /** 打开的项目 tab 记录在 lastActiveWorkspace(WSL 工单日志即此字段),其余在 lastWorkspaceSession。 */
  161. async function readSessionEntry(workspacePath: string) {
  162. const settings = await readSettings();
  163. const isTarget = (entry: unknown): entry is RemoteWorkspaceSessionEntry =>
  164. Boolean(entry) &&
  165. (entry as RemoteWorkspaceSessionEntry).kind === "remote" &&
  166. (entry as RemoteWorkspaceSessionEntry).workspacePath === workspacePath;
  167. return isTarget(settings.lastActiveWorkspace)
  168. ? settings.lastActiveWorkspace
  169. : settings.lastWorkspaceSession?.find(isTarget);
  170. }
  171. describe(`${MARKER}: 迁移的密码 SSH 项目首次安装`, () => {
  172. const facts: Record<string, unknown> = {};
  173. const { credentialsFile, homeDir } = getE2EAppDataPaths();
  174. const tasksIndexFile = join(homeDir, ".zcode/v2/tasks-index.sqlite");
  175. let config: SSHConnectionConfig;
  176. let container: string;
  177. let workspacePath: string;
  178. let legacyIdentity: string;
  179. let legacyPasswordKey: string;
  180. let ciphertext: string | undefined;
  181. /** 去掉 LIH-03 注入的认证拒绝;未注入时是空操作。 */
  182. async function restoreRemoteAuth(): Promise<void> {
  183. if (!container) return;
  184. await execInRemoteContainer(
  185. container,
  186. [
  187. "sh",
  188. "-c",
  189. `sed -i '\\|${PAM_COUNT_LINE}|d; \\|${PAM_DENY_LINE}|d' /etc/pam.d/sshd; rm -f ${AUTH_ATTEMPTS_FILE}`,
  190. ],
  191. { user: "0" },
  192. );
  193. }
  194. /** 远端 PAM 记录到的认证尝试次数;每次拨号至少一次。 */
  195. async function remoteAuthAttempts(): Promise<number> {
  196. const { stdout } = await execInRemoteContainer(
  197. container,
  198. ["sh", "-c", `cat ${AUTH_ATTEMPTS_FILE} 2>/dev/null | wc -l`],
  199. { user: "0" },
  200. );
  201. return Number(stdout.trim());
  202. }
  203. after(async () => {
  204. await browser.electron.execute(() => globalThis.__legacyTabConnectProbe?.restore());
  205. await restoreRemoteAuth().catch(() => undefined);
  206. await mkdir(artifactDir, { recursive: true });
  207. await writeFile(
  208. resolve(artifactDir, "ssh-remote-legacy-install-handoff.json"),
  209. JSON.stringify(facts, null, 2),
  210. );
  211. await browser.electron.restoreAllMocks();
  212. await clearAppData();
  213. });
  214. async function remoteInstallState(): Promise<string> {
  215. return (
  216. await execInRemoteContainer(container, [
  217. "sh",
  218. "-c",
  219. `test -e /home/${config.username}/.zcode/server/bin/zcode && echo installed || echo absent`,
  220. ])
  221. ).stdout.trim();
  222. }
  223. /** 让当前版本用本机密钥保存一次密码,取得能解密的密文;密码只在连接成功后保存,所以先完整连接一次。 */
  224. async function captureStoredPassword(): Promise<string> {
  225. await openSSHRemoteDialog(MARKER);
  226. await fillSSHPasswordSettings(config);
  227. await clickLastEnabledSSHDialogButton(MARKER);
  228. await waitForSSHDirectoryStep(MARKER, undefined, { allowBoundaryAcknowledgement: true });
  229. // 在远端登记该项目,模拟 3.15 远端已有的项目数据;之后只删除 Source Server 安装目录。
  230. await selectSSHRemoteDirectory(workspacePath, MARKER);
  231. await waitForRemoteTab({ caseMarker: MARKER, expectedPath: workspacePath });
  232. const profile = (await readSettings()).connectionProfiles?.find(
  233. (item) =>
  234. item.target.kind === "ssh" &&
  235. item.target.host === config.host &&
  236. item.target.port === config.port,
  237. );
  238. const key = profile?.target.kind === "ssh" ? profile.target.passwordCredentialKey : undefined;
  239. const credentials = JSON.parse(await readFile(credentialsFile, "utf-8")) as Record<
  240. string,
  241. string
  242. >;
  243. const value = key ? credentials[key] : undefined;
  244. if (!value) throw new Error(`${MARKER}: 没有取得已保存的密码密文`);
  245. return value;
  246. }
  247. /**
  248. * 模拟 3.15 设置首次进入 3.16:远端回到未安装,删除项目库,写入旧远程条目与旧密码,清空迁移版本。
  249. * withRestoredTab 同时写入 lastActiveWorkspace,冷启动后恢复旧项目 tab(WSL 工单的形状)。
  250. */
  251. async function seedLegacyUpgrade(label: string, withRestoredTab: boolean): Promise<string> {
  252. const legacyEntry = {
  253. kind: "remote" as const,
  254. workspacePath,
  255. workspaceIdentity: legacyIdentity,
  256. target: {
  257. kind: "ssh" as const,
  258. host: config.host,
  259. port: config.port,
  260. username: config.username,
  261. passwordCredentialKey: legacyPasswordKey,
  262. },
  263. lastOpenedAt: Date.now(),
  264. lastConnectionStatus: "connected" as const,
  265. };
  266. await reloadElectronSessionPreservingBrowserProfile(browser, {
  267. afterElectronProcessExit: async () => {
  268. // 停掉上一次留下的 Source Server,只删除其安装目录,保留远端项目数据。
  269. await execInRemoteContainer(
  270. container,
  271. [
  272. "sh",
  273. "-c",
  274. `pkill -9 -u ${config.username} -f '.zcode/server' || true; rm -rf /home/${config.username}/.zcode/server`,
  275. ],
  276. { user: "0" },
  277. );
  278. for (const suffix of ["", "-wal", "-shm"]) {
  279. await rm(`${tasksIndexFile}${suffix}`, { force: true });
  280. }
  281. const current = await readSettings();
  282. await seedSettings({
  283. sourceServerDirectoryMigrationVersion: undefined,
  284. sourceServers: [],
  285. connectionProfiles: [],
  286. sourceServerWorkspaceHistory: [],
  287. remoteStartupAutoReconnectEnabled: false,
  288. lastWorkspaceSession: [
  289. ...(current.lastWorkspaceSession ?? []).filter((entry) => entry.kind !== "remote"),
  290. legacyEntry,
  291. ],
  292. lastActiveWorkspace: withRestoredTab ? legacyEntry : null,
  293. });
  294. const credentials = JSON.parse(await readFile(credentialsFile, "utf-8")) as Record<
  295. string,
  296. string
  297. >;
  298. credentials[legacyPasswordKey] = ciphertext!;
  299. await writeFile(credentialsFile, JSON.stringify(credentials), "utf-8");
  300. },
  301. });
  302. await waitForRendererAfterColdRestart(MARKER);
  303. expect(await remoteInstallState()).toBe("absent");
  304. await waitForProjectRow(workspacePath, {
  305. timeout: 60_000,
  306. timeoutMsg: `${MARKER}: 迁移后侧栏没有旧远程项目`,
  307. });
  308. const migrated = (await readSettings()).connectionProfiles?.filter(
  309. (profile) => profile.target.kind === "ssh" && profile.target.port === config.port,
  310. );
  311. facts[`${label}.migratedProfiles`] = migrated?.map((profile) => ({
  312. profileId: profile.profileId,
  313. sourceServerId: profile.sourceServerId ?? null,
  314. hasPassword: profile.target.kind === "ssh" && Boolean(profile.target.passwordCredentialKey),
  315. }));
  316. // 前提:迁移出的线路带已存密码,但还没有 sourceServerId,入口按 sourceServerId 找不到它。
  317. expect(migrated).toHaveLength(1);
  318. expect(migrated![0]!.sourceServerId).toBeUndefined();
  319. return migrated![0]!.profileId;
  320. }
  321. /**
  322. * 第一次需要安装时取消并关闭向导,第二次连接后用错误面板的“安装并连接”完成安装。
  323. * expectFailedRecord:恢复的 tab 走原地重连,等待点按既有契约写成只有本地化文案的失败记录,
  324. * 这正是工单里第二次点击被判成“连接失败”的输入;侧栏入口不写这条记录。
  325. */
  326. async function cancelThenInstall(
  327. label: string,
  328. migratedProfileId: string,
  329. expectFailedRecord: boolean,
  330. ): Promise<void> {
  331. await clickRemoteHostConnect(workspacePath);
  332. facts[`${label}.firstAttempt`] = await waitForWizard(
  333. (state) => state.installPanel,
  334. "第一次连接的安装确认",
  335. );
  336. await clickWizardButton("install", "取消");
  337. // 取消安装后向导停在“已取消”,用户随后关闭向导。
  338. await waitForWizard((state) => !state.installPanel, "取消后的安装确认消失", 30_000);
  339. await browser.keys("Escape");
  340. await waitForWizard((state) => !state.open, "关闭向导", 30_000);
  341. const entryAfterCancel = await readSessionEntry(workspacePath);
  342. facts[`${label}.entryAfterCancel`] = entryAfterCancel;
  343. expect(entryAfterCancel?.lastConnectionStatus).toBe(
  344. expectFailedRecord ? "failed" : "connected",
  345. );
  346. // 第二次连接同一项目:仍应重新询问 Host 并显示安装确认,不能只显示过期的“连接失败”。
  347. await clickRemoteHostConnect(workspacePath);
  348. const second = await waitForWizard(
  349. (state) => state.installPanel || Boolean(state.errorText),
  350. "第二次连接的向导",
  351. );
  352. facts[`${label}.secondAttempt`] = second;
  353. expect(second.installPanel).toBe(true);
  354. // 点错误面板的“安装并连接”:执行安装确认,并带上迁移来的已存密码。
  355. expect(second.buttons).toContain("安装并连接");
  356. await clickWizardButton("error", "安装并连接");
  357. let finalState: WizardState | undefined;
  358. await browser.waitUntil(
  359. async () => {
  360. finalState = await readWizardState();
  361. if (
  362. /SSH 认证失败|需要先确认安装/u.test(finalState.errorText ?? "") &&
  363. !finalState.installPanel
  364. )
  365. return true;
  366. const profile = (await readSettings()).connectionProfiles?.find(
  367. (item) => item.profileId === migratedProfileId,
  368. );
  369. return Boolean(profile?.sourceServerId);
  370. },
  371. {
  372. timeout: 8 * 60_000,
  373. interval: 1_000,
  374. timeoutMsg: `${MARKER}: ${label} 安装后设备没有上线;最后状态 ${JSON.stringify(finalState)}`,
  375. },
  376. );
  377. facts[`${label}.finalState`] = finalState;
  378. // 修复前:确认安装只用 none 认证,报“SSH 认证失败”;或按钮走无确认重试,再次“需要先确认安装”。
  379. expect(finalState?.errorText ?? "").not.toMatch(/SSH 认证失败|需要先确认安装/u);
  380. expect(await remoteInstallState()).toBe("installed");
  381. // 用迁移来的线路(带已存密码)连上并识别出 Source,没有另建无凭据的线路。
  382. expect(
  383. (await readSettings()).connectionProfiles?.filter(
  384. (item) => item.target.kind === "ssh" && item.target.port === config.port,
  385. ),
  386. ).toHaveLength(1);
  387. // 原项目能否打开取决于远端是否有该旧 workspace 的历史会话;新容器没有,只记录结果,不作断言。
  388. await browser.pause(3_000);
  389. facts[`${label}.projectOpenOutcome`] = await readWizardState();
  390. await browser.keys("Escape");
  391. }
  392. it("LIH-01 侧栏项目(无 tab):取消安装后再次连接仍显示安装确认;“安装并连接”带迁移的已存密码完成安装并上线", async function () {
  393. this.timeout(15 * 60_000);
  394. config = readSSHRuntimeConfig(MARKER);
  395. container = readRemoteDockerContainer(MARKER);
  396. workspacePath = `/home/${config.username}/${PROJECT_DIR}`;
  397. legacyIdentity = `remote:ssh:${config.host}:${config.port}:${config.username}:${workspacePath}`;
  398. legacyPasswordKey = `remote-workspace:${legacyIdentity}:password`;
  399. await execInRemoteContainer(container, ["mkdir", "-p", workspacePath], {
  400. user: config.username,
  401. });
  402. await prepareV4ConversationE2E({ skipProvider: true });
  403. // 回放已观察到英文认证错误;本例按中文按钮和错误合同验收,先固定语言并随冷启动保留。
  404. await pinE2ELocale("zh-CN");
  405. ciphertext = await captureStoredPassword();
  406. const profileId = await seedLegacyUpgrade("LIH-01", false);
  407. await cancelThenInstall("LIH-01", profileId, false);
  408. });
  409. it("LIH-02 恢复的旧项目 tab:取消安装留下的失败记录不挡住第二次连接,仍显示安装确认并带已存密码完成安装", async function () {
  410. this.timeout(15 * 60_000);
  411. if (!ciphertext) this.skip();
  412. const profileId = await seedLegacyUpgrade("LIH-02", true);
  413. await cancelThenInstall("LIH-02", profileId, true);
  414. });
  415. for (const { label, stripCode, expectedCode } of [
  416. { label: "LIH-03", stripCode: false, expectedCode: "remote-authentication-failed" },
  417. { label: "LIH-04", stripCode: true, expectedCode: "remote-connection-unknown" },
  418. ]) {
  419. it(`${label} 恢复的旧项目 tab 普通重连失败(${stripCode ? "无码" : "带码"}):第二次点击打开向导查看失败,不再拨号`, async function () {
  420. this.timeout(10 * 60_000);
  421. if (!ciphertext) this.skip();
  422. await seedLegacyUpgrade(label, true);
  423. await execInRemoteContainer(
  424. container,
  425. ["sh", "-c", `cat > ${AUTH_ATTEMPT_SCRIPT} && chmod 755 ${AUTH_ATTEMPT_SCRIPT}`],
  426. { user: "0", input: `#!/bin/sh\necho attempt >> ${AUTH_ATTEMPTS_FILE}\n` },
  427. );
  428. // 两次插到最前:先记录尝试,再拒绝;密码与 keyboard-interactive 认证都经过这个栈。
  429. await execInRemoteContainer(
  430. container,
  431. [
  432. "sh",
  433. "-c",
  434. `rm -f ${AUTH_ATTEMPTS_FILE}; sed -i '1i ${PAM_DENY_LINE}' /etc/pam.d/sshd; sed -i '1i ${PAM_COUNT_LINE}' /etc/pam.d/sshd`,
  435. ],
  436. { user: "0" },
  437. );
  438. try {
  439. await installLegacyConnectProbe(stripCode);
  440. // 第一次点击:重连遇到普通失败,不弹向导;失败记录带上错误码。
  441. await clickRemoteHostConnect(workspacePath);
  442. let entry: RemoteWorkspaceSessionEntry | undefined;
  443. await browser.waitUntil(
  444. async () => {
  445. entry = await readSessionEntry(workspacePath);
  446. return entry?.lastConnectionStatus === "failed";
  447. },
  448. {
  449. timeout: 90_000,
  450. interval: 500,
  451. timeoutMsg: `${MARKER}: 第一次重连没有写入失败记录;最后记录 ${JSON.stringify(entry)}`,
  452. },
  453. );
  454. const attemptsAfterFirst = await remoteAuthAttempts();
  455. const firstProbe = await readLegacyConnectProbe();
  456. facts[`${label}.firstAttempt`] = {
  457. entry,
  458. probe: firstProbe,
  459. attempts: attemptsAfterFirst,
  460. wizard: await readWizardState(),
  461. };
  462. expect(entry?.lastConnectionErrorCode).toBe(expectedCode);
  463. expect(firstProbe.calls).toBe(1);
  464. expect(firstProbe.removedCodes).toEqual(stripCode ? ["remote-authentication-failed"] : []);
  465. expect(attemptsAfterFirst).toBeGreaterThan(0);
  466. expect((await readWizardState()).open).toBe(false);
  467. // 第二次点击:进入向导连接步骤查看失败,不自动再次拨号(修复前每次点击都静默重拨)。
  468. await clickRemoteHostConnect(workspacePath);
  469. const second = await waitForWizard(
  470. (state) => state.open && Boolean(state.errorText),
  471. "第二次点击的失败向导",
  472. 30_000,
  473. );
  474. const logPanel = await $('[data-testid="remote-connection-log"]');
  475. await expect(logPanel).toBeDisplayed();
  476. const logs = await logPanel.getText();
  477. expect(logs).toMatch(/\[(INFO|WARN|ERROR|SUCCESS)\]/u);
  478. // 留出一次拨号所需的时间,确认这次点击没有在后台再发起连接。
  479. await browser.pause(5_000);
  480. const attemptsAfterSecond = await remoteAuthAttempts();
  481. const secondProbe = await readLegacyConnectProbe();
  482. facts[`${label}.secondAttempt`] = {
  483. wizard: second,
  484. logs,
  485. attempts: attemptsAfterSecond,
  486. probe: secondProbe,
  487. };
  488. expect(second.installPanel).toBe(false);
  489. expect(second.errorText ?? "").toMatch(/SSH 认证失败/u);
  490. expect(attemptsAfterSecond).toBe(attemptsAfterFirst);
  491. expect(secondProbe.calls).toBe(firstProbe.calls);
  492. await browser.keys("Escape");
  493. } finally {
  494. await browser.electron.execute(() => globalThis.__legacyTabConnectProbe?.restore());
  495. await restoreRemoteAuth();
  496. }
  497. });
  498. }
  499. });