conversation-session-remote-workspace-folder-thread-exhaustion-ssh.test.ts 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299
  1. import { mkdir, writeFile } from "node:fs/promises";
  2. import { readFileSync } from "node:fs";
  3. import { resolve } from "node:path";
  4. import { parseRemoteWorkspaceIdentity } from "@zcode/shared";
  5. import { TID_SSH_DIALOG, TID_SSH_ERROR } from "@zcode/shared/test-ids";
  6. import {
  7. countRemoteWorkspaceUnresponsiveFailures,
  8. readConnectRemoteFailures,
  9. } from "#e2e/helpers/connect-remote-error-log";
  10. import { clearAppData } from "#e2e/helpers/desktop-app";
  11. import { startDraftFromProject } from "#e2e/helpers/project-sidebar";
  12. import {
  13. execInRemoteContainer,
  14. readRemoteDockerContainer,
  15. writeRemoteContainerFile,
  16. } from "#e2e/helpers/remote-docker-target";
  17. import {
  18. disconnectRemoteSource,
  19. requestRemoteProjectConnection,
  20. } from "#e2e/helpers/remote-project-actions";
  21. import { installAndStartRemoteDaemon } from "#e2e/helpers/remote-restart-stale-daemon";
  22. import {
  23. clickLastEnabledSSHDialogButton,
  24. connectSSHWorkspace,
  25. fillSSHPasswordSettings,
  26. openSSHRemoteDialog,
  27. openSSHSourceDirectory,
  28. readSSHRuntimeConfig,
  29. selectSSHRemoteDirectory,
  30. waitForRemoteTab,
  31. waitForSSHDirectoryStep,
  32. } from "#e2e/helpers/ssh-remote-p0";
  33. import { prepareV4ConversationE2E } from "#e2e/helpers/v4-conversation";
  34. // ZCT-2113660144497782784 的真实 SSH 验证(本机 Docker runner):远端读取项目目录卡住,且每个卡住的调用真实占住
  35. // Core 的一个 libuv 线程(Node 默认 4 个,文件调用不能取消)。修复前,卡住项目重试几次后线程池占满,同设备所有
  36. // 文件操作都不再返回:其他项目打不开,侧栏一直“连接中”,新建任务一直转圈。修复后同一路径未返回的调用被复用,
  37. // 主目录检查 30 秒后按“无法访问”返回;其他项目照常打开,远端恢复后卡住项目可以重新打开。
  38. const MARKER = "E2E_REMOTE_WORKSPACE_FOLDER_THREAD_EXHAUSTION_SSH";
  39. const HANG_DIR = "/home/dev/e2e-exhaust-hang";
  40. const OK_DIR = "/home/dev/e2e-exhaust-ok";
  41. const LATE_DIR = "/home/dev/e2e-exhaust-late";
  42. const HANG_FLAG = "/home/dev/.e2e-exhaust-hang-on";
  43. const HANG_FIFO = "/home/dev/.e2e-exhaust-hang.fifo";
  44. const SEAM_SCRIPT = "/home/dev/.e2e-exhaust-seam.cjs";
  45. const HUNG_ATTEMPTS = 4;
  46. const DEADLINE_MS = 30_000;
  47. const desktopRoot = process.cwd();
  48. const artifactDir = resolve(
  49. process.env.ZCODE_E2E_ARTIFACT_DIR ??
  50. ".e2e-artifacts/remote-workspace-folder-thread-exhaustion-ssh",
  51. );
  52. // 标记文件存在时,Core 对 HANG_DIR/.(admission 探测)的 readdir 和对 HANG_DIR(主目录检查)的 stat 先对没有
  53. // 写端的 FIFO 调用 open():这会在 libuv 线程池里真实阻塞一个线程,与远端等待授权、网络盘无响应时一致。
  54. // 恢复时测试打开 FIFO 写端放行挂起的调用,随后执行真实的文件调用。只作用于 server-core 进程。
  55. const SEAM = `if (/server-core\\.js$/.test(process.argv[1] || "")) {
  56. const fs = require("node:fs");
  57. const fsp = require("node:fs/promises");
  58. const flag = ${JSON.stringify(HANG_FLAG)};
  59. const fifo = ${JSON.stringify(HANG_FIFO)};
  60. const gate = (name, matches) => {
  61. const original = fsp[name];
  62. fsp[name] = function (path, ...rest) {
  63. if (matches(String(path)) && fs.existsSync(flag)) {
  64. return fsp.open(fifo, "r").then(async (handle) => {
  65. await handle.close();
  66. return original.call(this, path, ...rest);
  67. });
  68. }
  69. return original.call(this, path, ...rest);
  70. };
  71. };
  72. gate("readdir", (path) => path === ${JSON.stringify(`${HANG_DIR}/.`)});
  73. gate("stat", (path) => path === ${JSON.stringify(HANG_DIR)});
  74. require("node:module").syncBuiltinESMExports();
  75. }
  76. `;
  77. /** 等到这次连接以“目录无响应”结束:新建连接与已有连接上的重试走不同路径,统一按失败次数增加判断。 */
  78. async function waitForUnresponsiveFailure(before: number, label: string): Promise<void> {
  79. await browser.waitUntil(async () => (await countRemoteWorkspaceUnresponsiveFailures()) > before, {
  80. timeout: DEADLINE_MS + 45_000,
  81. interval: 500,
  82. timeoutMsg: `${MARKER}: ${label} 没有以目录无响应结束`,
  83. });
  84. }
  85. async function clickDialogRetry(): Promise<void> {
  86. await browser.waitUntil(
  87. () =>
  88. browser.execute((errorTestId) => {
  89. const button = Array.from(
  90. document.querySelectorAll<HTMLButtonElement>(`[data-testid="${errorTestId}"] button`),
  91. ).find((item) => /^(重试|Retry)$/u.test(item.innerText.trim()) && !item.disabled);
  92. button?.click();
  93. return Boolean(button);
  94. }, TID_SSH_ERROR),
  95. { timeout: 30_000, timeoutMsg: `${MARKER}: 错误块里没有可用的重试按钮` },
  96. );
  97. }
  98. async function closeDialog(): Promise<void> {
  99. const dialog = $(`[data-testid="${TID_SSH_DIALOG}"]`);
  100. if (!(await dialog.isDisplayed())) return;
  101. await browser.keys("Escape");
  102. await dialog.waitForDisplayed({ reverse: true, timeout: 15_000 });
  103. }
  104. /** 同一设备追加一个项目:向导收起时从已注册设备进入目录选择。 */
  105. async function addProjectOnSameDevice(
  106. config: ReturnType<typeof readSSHRuntimeConfig>,
  107. workspacePath: string,
  108. ) {
  109. await openSSHRemoteDialog(MARKER);
  110. await fillSSHPasswordSettings(config);
  111. await clickLastEnabledSSHDialogButton(MARKER);
  112. if ((await waitForSSHDirectoryStep(MARKER)) === "closed")
  113. await openSSHSourceDirectory(config, MARKER);
  114. await selectSSHRemoteDirectory(workspacePath, MARKER);
  115. return waitForRemoteTab({ caseMarker: MARKER, expectedPath: workspacePath });
  116. }
  117. function projectRowSelector(identity: string): string {
  118. return `[data-project-workspace-identity=${JSON.stringify(identity)}]`;
  119. }
  120. async function readProjectRow(identity: string) {
  121. return browser.execute((selector) => {
  122. const row = document.querySelector<HTMLElement>(selector);
  123. return {
  124. exists: Boolean(row),
  125. primaryRootStatus: row?.dataset.primaryRootStatus ?? null,
  126. connectionState: row?.dataset.connectionState ?? null,
  127. statusLabel:
  128. row?.querySelector<HTMLElement>('[data-testid="project-status-label"]')?.innerText.trim() ??
  129. null,
  130. createTaskDisabled:
  131. row?.querySelector<HTMLButtonElement>('[data-testid="virtual-project-create-task"]')
  132. ?.disabled ?? null,
  133. };
  134. }, projectRowSelector(identity));
  135. }
  136. async function releaseHungCalls(container: string): Promise<void> {
  137. await execInRemoteContainer(container, ["rm", "-f", HANG_FLAG]);
  138. // 打开写端放行所有阻塞在读端 open() 的调用;没有读端时 timeout 结束本次写端等待。
  139. await execInRemoteContainer(container, [
  140. "sh",
  141. "-c",
  142. `for i in $(seq 1 40); do timeout 0.2 sh -c ': > ${HANG_FIFO}' 2>/dev/null; done; true`,
  143. ]);
  144. }
  145. describe(`${MARKER}: 卡住的远端目录不能占满 Core 线程池`, () => {
  146. const facts: Record<string, unknown> = {};
  147. after(async () => {
  148. await mkdir(artifactDir, { recursive: true });
  149. await writeFile(
  150. resolve(artifactDir, "workspace-folder-thread-exhaustion.json"),
  151. JSON.stringify(facts, null, 2),
  152. );
  153. await browser.electron.restoreAllMocks();
  154. await clearAppData();
  155. });
  156. it("卡住项目反复重试后,同设备其他项目照常打开,侧栏标为无法访问,恢复后可重新打开", async function () {
  157. this.timeout(25 * 60_000);
  158. const config = readSSHRuntimeConfig(MARKER);
  159. const container = readRemoteDockerContainer(MARKER);
  160. const appVersion = (
  161. JSON.parse(readFileSync(resolve(desktopRoot, "../../package.json"), "utf8")) as {
  162. version: string;
  163. }
  164. ).version;
  165. await prepareV4ConversationE2E({ skipProvider: true });
  166. await execInRemoteContainer(container, ["mkdir", "-p", HANG_DIR, OK_DIR]);
  167. await execInRemoteContainer(container, [
  168. "sh",
  169. "-c",
  170. `rm -f ${HANG_FIFO} && mkfifo ${HANG_FIFO}`,
  171. ]);
  172. await writeRemoteContainerFile(container, SEAM_SCRIPT, SEAM);
  173. await installAndStartRemoteDaemon(
  174. container,
  175. { user: "dev", home: "/home/dev" },
  176. { desktopRoot, appVersion, nodeOptions: `--require=${SEAM_SCRIPT}` },
  177. );
  178. // 1. 接缝未启用:同一设备建好两个项目;卡住项目最后打开,保持为当前页签。
  179. const ok = await connectSSHWorkspace({ config, caseMarker: MARKER, workspacePath: OK_DIR });
  180. const hung = await addProjectOnSameDevice(config, HANG_DIR);
  181. const hungIdentity = hung.workspaceIdentity!;
  182. const okIdentity = ok.workspaceIdentity!;
  183. const sourceServerId = parseRemoteWorkspaceIdentity(hungIdentity)?.sourceServerId;
  184. if (!sourceServerId) throw new Error(`${MARKER}: 项目身份里没有 sourceServerId`);
  185. expect(parseRemoteWorkspaceIdentity(okIdentity)?.sourceServerId).toBe(sourceServerId);
  186. await disconnectRemoteSource(sourceServerId, MARKER, {
  187. workspaceIdentities: [hungIdentity, okIdentity],
  188. });
  189. // 2. 启用接缝后反复打开卡住项目:每次 30 秒后报无响应,设备保持在线。
  190. // 第 1 次从项目行连接;之后从该项目页签的横幅进入原向导重试,与用户反复点击一致。
  191. await execInRemoteContainer(container, ["touch", HANG_FLAG]);
  192. const attempts: number[] = [];
  193. for (let attempt = 1; attempt <= HUNG_ATTEMPTS; attempt++) {
  194. const before = await countRemoteWorkspaceUnresponsiveFailures();
  195. const startedAt = Date.now();
  196. if (attempt === 1) {
  197. await requestRemoteProjectConnection(hungIdentity, MARKER);
  198. } else {
  199. if (!(await $(`[data-testid="${TID_SSH_DIALOG}"]`).isDisplayed())) {
  200. // 横幅属于当前页签(卡住项目);“重新连接”把失败项目交给向导,向导里的重试读取该项目目录。
  201. const banner = $('[data-testid="remote-conversation-banner"]');
  202. await banner.waitForDisplayed({ timeout: 30_000, timeoutMsg: `${MARKER}: 没有断线横幅` });
  203. await banner
  204. .$('.//button[normalize-space(.)="重新连接" or normalize-space(.)="Reconnect"]')
  205. .click();
  206. await $(`[data-testid="${TID_SSH_DIALOG}"]`).waitForDisplayed({ timeout: 30_000 });
  207. }
  208. await clickDialogRetry();
  209. }
  210. await waitForUnresponsiveFailure(before, `卡住项目第 ${attempt} 次连接`);
  211. attempts.push(Date.now() - startedAt);
  212. }
  213. // 每次都按 R8 在截止时间结束,而不是立即失败或一直挂着。
  214. facts.hungAttemptElapsedMs = attempts;
  215. expect(attempts.every((elapsedMs) => elapsedMs >= DEADLINE_MS - 1_000)).toBe(true);
  216. await browser.saveScreenshot(resolve(artifactDir, "hung-attempts.png"));
  217. await closeDialog();
  218. // 3. 同设备新增项目:目录选择器读取目录、项目 admission 都照常完成。
  219. // 修复前:线程池已被卡住的调用占满,读目录同样不再返回,新项目打不开。
  220. await execInRemoteContainer(container, ["mkdir", "-p", LATE_DIR]);
  221. const lateFailuresBefore = (await readConnectRemoteFailures()).length;
  222. const lateUnresponsiveBefore = await countRemoteWorkspaceUnresponsiveFailures();
  223. try {
  224. const late = await addProjectOnSameDevice(config, LATE_DIR);
  225. facts.lateProject = {
  226. workspaceIdentity: late.workspaceIdentity,
  227. remoteSessionId: late.remoteSessionId,
  228. };
  229. } finally {
  230. facts.lateFailures = (await readConnectRemoteFailures()).slice(lateFailuresBefore);
  231. facts.lateUnresponsive =
  232. (await countRemoteWorkspaceUnresponsiveFailures()) - lateUnresponsiveBefore;
  233. await browser.saveScreenshot(resolve(artifactDir, "late-project.png"));
  234. }
  235. expect(facts.lateFailures).toEqual([]);
  236. expect(facts.lateUnresponsive).toBe(0);
  237. // 4. 侧栏不再一直“连接中”:卡住项目标为无法访问并禁用新建,其他项目正常可用。
  238. let rows:
  239. | {
  240. hung: Awaited<ReturnType<typeof readProjectRow>>;
  241. ok: Awaited<ReturnType<typeof readProjectRow>>;
  242. }
  243. | undefined;
  244. try {
  245. await browser.waitUntil(
  246. async () => {
  247. rows = { hung: await readProjectRow(hungIdentity), ok: await readProjectRow(okIdentity) };
  248. return (
  249. rows.hung.primaryRootStatus === "unavailable" &&
  250. rows.hung.createTaskDisabled === true &&
  251. rows.ok.primaryRootStatus === "available" &&
  252. rows.ok.statusLabel === null
  253. );
  254. },
  255. { timeout: DEADLINE_MS + 45_000, interval: 1000 },
  256. );
  257. } finally {
  258. facts.sidebarRows = rows ?? null;
  259. }
  260. await browser.saveScreenshot(resolve(artifactDir, "sidebar-unavailable.png"));
  261. // 5. 远端恢复:放行挂起的调用;用户切回窗口时侧栏重新读取(focus 刷新),卡住项目恢复可用,
  262. // 从侧栏新建任务可以进入该项目(prepareSession 复检主目录、项目 admission 都完成)。
  263. await releaseHungCalls(container);
  264. await browser.waitUntil(
  265. async () => {
  266. await browser.execute(() => window.dispatchEvent(new Event("focus")));
  267. return (await readProjectRow(hungIdentity)).primaryRootStatus === "available";
  268. },
  269. { timeout: 60_000, interval: 2000, timeoutMsg: `${MARKER}: 恢复后主目录仍不可用` },
  270. );
  271. await startDraftFromProject(HANG_DIR, { workspaceIdentity: hungIdentity });
  272. const restored = await waitForRemoteTab({
  273. caseMarker: MARKER,
  274. expectedIdentity: hungIdentity,
  275. expectedPath: HANG_DIR,
  276. timeoutMs: 120_000,
  277. });
  278. facts.hungRestored = { remoteSessionId: restored.remoteSessionId };
  279. expect(restored.remoteSessionId).toBeTruthy();
  280. await browser.saveScreenshot(resolve(artifactDir, "restored.png"));
  281. });
  282. });