conversation-session-ssh-remote-retry-budget.test.ts 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196
  1. import { createConnection, createServer, type Socket } from "node:net";
  2. import { mkdir, writeFile } from "node:fs/promises";
  3. import { resolve } from "node:path";
  4. import { clearAppData } from "#e2e/helpers/desktop-app";
  5. import { requestRemoteProjectConnection } from "#e2e/helpers/remote-project-actions";
  6. import {
  7. connectSSHWorkspace,
  8. readHostProcesses,
  9. readRemoteTabSnapshot,
  10. readSSHRuntimeConfig,
  11. waitForRemoteTab,
  12. } from "#e2e/helpers/ssh-remote-p0";
  13. import { prepareV4ConversationE2E } from "#e2e/helpers/v4-conversation";
  14. const MARKER = "E2E_SSH_RETRY_BUDGET";
  15. const artifactDir = resolve(
  16. process.env.ZCODE_E2E_ARTIFACT_DIR ?? ".e2e-artifacts/ssh-retry-budget",
  17. );
  18. async function createNetworkGate(target: { host: string; port: number }) {
  19. const sockets = new Set<Socket>();
  20. let blocked = false;
  21. let attempts = 0;
  22. const server = createServer((client) => {
  23. if (blocked) {
  24. attempts += 1;
  25. client.destroy();
  26. return;
  27. }
  28. const upstream = createConnection(target);
  29. sockets.add(client);
  30. sockets.add(upstream);
  31. const close = () => {
  32. client.destroy();
  33. upstream.destroy();
  34. sockets.delete(client);
  35. sockets.delete(upstream);
  36. };
  37. client.once("error", close);
  38. upstream.once("error", close);
  39. client.once("close", close);
  40. upstream.once("close", close);
  41. upstream.once("connect", () => client.pipe(upstream).pipe(client));
  42. });
  43. await new Promise<void>((resolve, reject) => {
  44. server.once("error", reject);
  45. server.listen(0, "127.0.0.1", resolve);
  46. });
  47. const address = server.address();
  48. if (!address || typeof address === "string") throw new Error("缺少代理端口");
  49. return {
  50. port: address.port,
  51. block() {
  52. blocked = true;
  53. for (const socket of sockets) socket.destroy();
  54. },
  55. allow() {
  56. blocked = false;
  57. },
  58. attempts: () => attempts,
  59. async close() {
  60. for (const socket of sockets) socket.destroy();
  61. await new Promise<void>((resolve) => server.close(() => resolve()));
  62. },
  63. };
  64. }
  65. describe(`${MARKER}: 重试预算、静默恢复与手动接管`, () => {
  66. let gate: Awaited<ReturnType<typeof createNetworkGate>> | undefined;
  67. const facts: Record<string, unknown> = {};
  68. after(async () => {
  69. await mkdir(artifactDir, { recursive: true });
  70. await writeFile(resolve(artifactDir, "retry-budget.json"), JSON.stringify(facts, null, 2));
  71. await gate?.close();
  72. await browser.electron.restoreAllMocks();
  73. await clearAppData();
  74. });
  75. it("SSH-GUIDE-RETRY 显示 1/3、2/3、3/3,耗尽显示原因,网络恢复静默上线,手动恢复不重复连接", async function () {
  76. this.timeout(15 * 60_000);
  77. const direct = readSSHRuntimeConfig(MARKER);
  78. gate = await createNetworkGate(direct);
  79. await prepareV4ConversationE2E({ skipProvider: true });
  80. const hosts = await readHostProcesses();
  81. const config = { ...direct, port: gate.port };
  82. const tab = await connectSSHWorkspace({
  83. config,
  84. caseMarker: MARKER,
  85. workspacePath: direct.workspacePaths[0],
  86. });
  87. await browser.execute(() => {
  88. const state = window as Window & {
  89. __sshGuideRetry?: { attempts: number[]; observer: MutationObserver };
  90. };
  91. const attempts: number[] = [];
  92. const observer = new MutationObserver(() => {
  93. for (const match of document.body.innerText.matchAll(/([123])\s*\/\s*3/g)) {
  94. const attempt = Number(match[1]);
  95. if (!attempts.includes(attempt)) attempts.push(attempt);
  96. }
  97. });
  98. observer.observe(document.body, { childList: true, subtree: true, characterData: true });
  99. state.__sshGuideRetry = { attempts, observer };
  100. });
  101. gate.block();
  102. const row = $(`[data-project-workspace-identity="${tab.workspaceIdentity}"]`);
  103. const toggle = row.$('[data-testid="virtual-project-toggle"]');
  104. const leaveDetails = async () => {
  105. // 浮层可能盖住其他入口;移到视口右上角,确保鼠标真正离开触发区域和浮层。
  106. const outside = await browser.execute(() => ({ x: innerWidth - 24, y: 24 }));
  107. await browser.action("pointer").move(outside).perform();
  108. await $('[data-testid="remote-identity-details"]').waitForDisplayed({ reverse: true });
  109. };
  110. await browser.waitUntil(
  111. async () => (await row.getAttribute("data-connection-state")) === "connecting",
  112. { timeout: 30_000, timeoutMsg: `${MARKER}: 断网后没有进入连接中` },
  113. );
  114. // 修复前连接中只有一个读取空日志的 (i) Tooltip;现在项目行写“连接中”,详情顶部给出阶段与进度。
  115. expect(["连接中", "Connecting"]).toContain(
  116. await row.$('[data-testid="project-status-label"]').getText(),
  117. );
  118. expect(await row.$$('[aria-label="查看详情"], [aria-label="View details"]')).toHaveLength(0);
  119. await toggle.moveTo();
  120. const progress = $(
  121. '[data-testid="remote-identity-details"] [data-testid="remote-connection-progress"]',
  122. );
  123. await progress.waitForDisplayed({ timeout: 10_000 });
  124. facts.connectingProgress = await progress.getText();
  125. expect(await progress.$$("[data-progress-segment]")).toHaveLength(4);
  126. expect(await progress.$$('[data-progress-segment="active"]')).toHaveLength(1);
  127. await browser.saveScreenshot(resolve(artifactDir, "connecting-progress.png"));
  128. // 详情保持打开直到终态:自动恢复 n/3 须在同一浮层内实时递增,并原地切换为失败区。
  129. await browser.waitUntil(
  130. async () => (await row.getAttribute("data-connection-state")) === "offline",
  131. { timeout: 120_000, timeoutMsg: `${MARKER}: 三次重试后没有离线终态` },
  132. );
  133. const seen = await browser.execute(() => {
  134. const state = (
  135. window as Window & { __sshGuideRetry?: { attempts: number[]; observer: MutationObserver } }
  136. ).__sshGuideRetry;
  137. state?.observer.disconnect();
  138. return state?.attempts ?? [];
  139. });
  140. facts.displayedAttempts = seen;
  141. facts.rejectedNetworkAttempts = gate.attempts();
  142. expect(facts.rejectedNetworkAttempts).toBe(3);
  143. // 失败原因由详情顶部的失败区表达,原文只进剪贴板,不再有独立错误图标。
  144. expect(await row.$('[data-testid="project-connection-error"]').isExisting()).toBe(false);
  145. const failure = $(
  146. '[data-testid="remote-identity-details"] [data-testid="remote-connection-failure"]',
  147. );
  148. await failure.waitForDisplayed({ timeout: 10_000 });
  149. facts.failureText = await failure.getText();
  150. expect((await failure.getText()).trim().length).toBeGreaterThan(0);
  151. expect(await failure.getText()).not.toContain(config.password);
  152. expect(await failure.$('[data-testid="remote-connection-copy-error"]').isDisplayed()).toBe(
  153. true,
  154. );
  155. await browser.saveScreenshot(resolve(artifactDir, "budget-exhausted.png"));
  156. await leaveDetails();
  157. expect((await readRemoteTabSnapshot(tab.workspaceIdentity!)).remoteSessionId).toBeNull();
  158. gate.allow();
  159. const automaticallyRestored = await waitForRemoteTab({
  160. caseMarker: MARKER,
  161. expectedIdentity: tab.workspaceIdentity!,
  162. expectedPath: tab.workspacePath!,
  163. timeoutMs: 180_000,
  164. });
  165. expect(automaticallyRestored.remoteSessionId).not.toBe(tab.remoteSessionId);
  166. expect(await $('[data-testid="ssh-dialog"]').isExisting()).toBe(false);
  167. facts.silentRecovery = automaticallyRestored;
  168. gate.block();
  169. await browser.waitUntil(
  170. async () => (await row.getAttribute("data-connection-state")) === "connecting",
  171. { timeout: 30_000 },
  172. );
  173. // 先确认旧 attachment 已释放再恢复网络;反序会把自动恢复完成误判成等待断开超时。
  174. await browser.waitUntil(
  175. async () => (await readRemoteTabSnapshot(tab.workspaceIdentity!)).remoteSessionId === null,
  176. { timeout: 30_000 },
  177. );
  178. gate.allow();
  179. await requestRemoteProjectConnection(tab.workspaceIdentity!, MARKER, { retryFailure: true });
  180. const manuallyRestored = await waitForRemoteTab({
  181. caseMarker: MARKER,
  182. expectedIdentity: tab.workspaceIdentity!,
  183. expectedPath: tab.workspacePath!,
  184. timeoutMs: 120_000,
  185. });
  186. expect(manuallyRestored.remoteSessionId).not.toBe(automaticallyRestored.remoteSessionId);
  187. expect(await readHostProcesses()).toEqual(hosts);
  188. facts.manualTakeover = manuallyRestored;
  189. // 展示缺失不影响后续连接操作;保留最终断言,同时采集静默恢复和手动接管的独立证据。
  190. expect(seen).toEqual([1, 2, 3]);
  191. });
  192. });