conversation-session-node-repl-frontend-restart.test.ts 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406
  1. import { readFile, readdir } from "node:fs/promises";
  2. import { createServer, type Server } from "node:http";
  3. import type { AddressInfo } from "node:net";
  4. import { join } from "node:path";
  5. import { TID_BROWSER_WEBVIEW } from "@zcode/shared/test-ids";
  6. import { clearAppData, getE2EAppDataPaths } from "#e2e/helpers/desktop-app";
  7. import {
  8. getUpstreamRequestRecordCount,
  9. getUpstreamRequestToolNames,
  10. waitForUpstreamRequest,
  11. } from "#e2e/helpers/conversation-session-network";
  12. import {
  13. waitForSuccessfulToolCallByToolCallId,
  14. waitForToolCallBlockByToolName,
  15. } from "#e2e/helpers/conversation-session-tool";
  16. import {
  17. collectProcessTreeByRootPids,
  18. listSystemProcesses,
  19. } from "#e2e/helpers/e2e-process-cleanup";
  20. import {
  21. prepareV4ConversationE2E,
  22. sendV4Prompt,
  23. waitForV4AssistantMessageContaining,
  24. waitForV4ConversationState,
  25. waitForV4UserMessageContaining,
  26. } from "#e2e/helpers/v4-conversation";
  27. const TOOL_NAME = "mcp__node_repl__js";
  28. const NODE_REPL_SERVER = "node_repl";
  29. const WARMUP_MARKER = "E2E_NODE_REPL_FRONTEND_RESTART_WARMUP";
  30. const WARMUP_FINAL_MARKER = "E2E_NODE_REPL_FRONTEND_RESTART_WARMUP_DONE";
  31. const TURN_ONE_MARKER = "E2E_NODE_REPL_FRONTEND_RESTART_TURN_1";
  32. const TURN_TWO_MARKER = "E2E_NODE_REPL_FRONTEND_RESTART_TURN_2";
  33. const SETUP_TOOL_CALL_ID = "toolu_e2e_node_repl_frontend_restart_setup";
  34. const VERIFY_TOOL_CALL_ID = "toolu_e2e_node_repl_frontend_restart_verify";
  35. const SETUP_RESULT_MARKER = "E2E_NODE_REPL_FRONTEND_RESTART_SETUP_OK";
  36. const VERIFY_RESULT_MARKER = "E2E_NODE_REPL_FRONTEND_RESTART_VERIFY_OK";
  37. const SETUP_FINAL_MARKER = "E2E_NODE_REPL_FRONTEND_RESTART_SETUP_DONE";
  38. const FINAL_MARKER = "E2E_NODE_REPL_FRONTEND_RESTART_DONE";
  39. const PROVIDER_NOISE = ["Generate a concise title", "CRITICAL: Respond with TEXT ONLY"];
  40. // 第一次自动重启没有退避;留出进程启动与 initialize 的时间。
  41. const RESTART_TIMEOUT_MS = 60_000;
  42. const E2E_PATHS = getE2EAppDataPaths();
  43. interface FixtureTabSnapshot {
  44. exists: boolean;
  45. id: number;
  46. state: string;
  47. url: string;
  48. }
  49. interface McpLogContext extends Record<string, unknown> {
  50. event?: string;
  51. mcpServerName?: string;
  52. mcpTransportPid?: number;
  53. }
  54. let fixtureServer: Server | null = null;
  55. let fixtureRootUrl = "";
  56. describe("Node REPL frontend 意外退出后自动重启 E2E", () => {
  57. before(async () => {
  58. fixtureServer = createRestartFixtureServer();
  59. fixtureRootUrl = await listen(fixtureServer);
  60. });
  61. after(async () => {
  62. await closeFixtureGuests();
  63. await closeServer(fixtureServer);
  64. fixtureServer = null;
  65. await browser.electron.restoreAllMocks();
  66. await clearAppData();
  67. });
  68. it("BSM03: frontend 被终止后不等调用就重启,下一轮 js 仍可用且 tab/page 连续", async function () {
  69. this.timeout(240_000);
  70. await prepareV4ConversationE2E();
  71. // MCP 异步启动时首个请求可能早于 node_repl 连上(ToolSearch 关闭时没有 pending 提示)。
  72. // 预热轮先启动会话并等 node_repl 连上,本 case 只验证之后的重启。
  73. await sendV4Prompt(`${WARMUP_MARKER}: reply with the warm-up marker only.`);
  74. await waitForV4AssistantMessageContaining(WARMUP_FINAL_MARKER);
  75. await waitForIdle("预热轮完成后没有回到 idle");
  76. const electronPid = await readElectronPid();
  77. const oldPid = await waitForNodeReplTransportPid(electronPid);
  78. await sendV4Prompt(
  79. [
  80. `${TURN_ONE_MARKER}: open the fixture page in an in-app Browser tab and write its state.`,
  81. `E2E_BROWSER_FIXTURE_URL:${fixtureRootUrl}`,
  82. ].join(" "),
  83. );
  84. await waitForV4UserMessageContaining(TURN_ONE_MARKER);
  85. await waitForToolCallBlockByToolName(TOOL_NAME, 90_000);
  86. await waitForPermissionAndApproveOnce("创建重启前的 Browser tab");
  87. await waitForSuccessfulToolCallByToolCallId(SETUP_TOOL_CALL_ID, [SETUP_RESULT_MARKER], 90_000);
  88. await waitForV4AssistantMessageContaining(SETUP_FINAL_MARKER);
  89. await waitForIdle("首轮完成后没有回到 idle");
  90. const [tabBefore] = await waitForFixtureTabs(1);
  91. expect(tabBefore?.state).toBe("before-restart");
  92. // 首轮调用用的仍是预热时连上的同一个 frontend。
  93. expect(await waitForNodeReplTransportPid(electronPid)).toBe(oldPid);
  94. const requestCount = await getUpstreamRequestRecordCount();
  95. // 只终止日志里属于本 E2E Electron 进程树的 frontend,不影响机器上的其他 node_repl。
  96. process.kill(oldPid, "SIGTERM");
  97. // 不发任何 prompt:重启必须由 adapter 自己完成,不能依赖下一次模型调用。
  98. const newPid = await waitForNodeReplTransportPid(electronPid, oldPid);
  99. expect(newPid).not.toBe(oldPid);
  100. expect(await isInProcessTree(electronPid, oldPid)).toBe(false);
  101. expect(await getUpstreamRequestRecordCount()).toBe(requestCount);
  102. await sendV4Prompt(`${TURN_TWO_MARKER}: get the same Browser tab again and read its state.`);
  103. await waitForV4UserMessageContaining(TURN_TWO_MARKER);
  104. const secondTurnQuery = {
  105. lastUserMessageIncludes: [TURN_TWO_MARKER],
  106. excludes: [VERIFY_TOOL_CALL_ID, ...PROVIDER_NOISE],
  107. };
  108. await waitForUpstreamRequest(secondTurnQuery, "第二轮 provider 请求没有发出", 60_000);
  109. // 修复前 frontend 退出后 server 进入 failed,js 在下一步离开 provider 请求。
  110. expect(await getUpstreamRequestToolNames(secondTurnQuery)).toContain(TOOL_NAME);
  111. await waitForToolCallBlockByToolName(TOOL_NAME, 90_000);
  112. await waitForPermissionAndApproveOnce("重启后取回原 Browser tab");
  113. await waitForSuccessfulToolCallByToolCallId(
  114. VERIFY_TOOL_CALL_ID,
  115. [VERIFY_RESULT_MARKER],
  116. 90_000,
  117. );
  118. await waitForUpstreamRequest(
  119. {
  120. includes: [TURN_TWO_MARKER, VERIFY_TOOL_CALL_ID],
  121. lastUserMessageIncludes: [VERIFY_RESULT_MARKER],
  122. excludes: PROVIDER_NOISE,
  123. },
  124. "重启后 js 结果没有进入 provider continuation",
  125. 90_000,
  126. );
  127. await waitForV4AssistantMessageContaining(FINAL_MARKER);
  128. await waitForIdle("第二轮完成后没有回到 idle");
  129. const [tabAfter] = await waitForFixtureTabs(1);
  130. expect(tabAfter?.id).toBe(tabBefore?.id);
  131. expect(tabAfter?.state).toBe("after-restart");
  132. });
  133. });
  134. function createRestartFixtureServer(): Server {
  135. return createServer((_request, response) => {
  136. response.setHeader("content-type", "text/html; charset=utf-8");
  137. response.end(`<!doctype html>
  138. <html>
  139. <head><meta name="viewport" content="width=device-width, initial-scale=1" /><title>E2E Node REPL Restart</title></head>
  140. <body>
  141. <main>
  142. <h1>Restart</h1>
  143. <label>State <input id="state" /></label>
  144. <p role="status">empty</p>
  145. </main>
  146. <script>
  147. document.querySelector("#state").addEventListener("input", (event) => {
  148. document.querySelector("[role=status]").textContent = event.currentTarget.value;
  149. });
  150. </script>
  151. </body>
  152. </html>`);
  153. });
  154. }
  155. async function listen(server: Server): Promise<string> {
  156. await new Promise<void>((resolve, reject) => {
  157. server.once("error", reject);
  158. server.listen(0, "127.0.0.1", () => {
  159. server.off("error", reject);
  160. resolve();
  161. });
  162. });
  163. const address = server.address() as AddressInfo | null;
  164. if (!address) throw new Error("Node REPL restart fixture server 没有绑定端口");
  165. return `http://127.0.0.1:${address.port}/root`;
  166. }
  167. async function closeServer(server: Server | null) {
  168. if (!server?.listening) return;
  169. await new Promise<void>((resolve, reject) => {
  170. server.close((error) => (error ? reject(error) : resolve()));
  171. });
  172. }
  173. async function waitForIdle(timeoutMessage: string) {
  174. await waitForV4ConversationState(
  175. (snapshot) => snapshot.state === "idle" && snapshot.queueCount === 0,
  176. timeoutMessage,
  177. 90_000,
  178. );
  179. }
  180. async function readElectronPid(): Promise<number> {
  181. const electron = await browser.electron.execute(() => ({ pid: process.pid }));
  182. return electron.pid;
  183. }
  184. async function isInProcessTree(rootPid: number, pid: number): Promise<boolean> {
  185. const tree = collectProcessTreeByRootPids(await listSystemProcesses(), [rootPid]);
  186. return tree.some((entry) => entry.pid === pid);
  187. }
  188. /** 读取最新一次 node_repl 连接的 transport PID,并确认它是本 Electron 进程树里仍存活的进程。 */
  189. async function waitForNodeReplTransportPid(electronPid: number, previousPid?: number) {
  190. let pid: number | undefined;
  191. let latest: McpLogContext[] = [];
  192. const waiting = browser.waitUntil(
  193. async () => {
  194. latest = (await readMcpLogContexts()).filter(
  195. (context) =>
  196. context.event === "mcp.server.connected" && context.mcpServerName === NODE_REPL_SERVER,
  197. );
  198. const candidate = latest.at(-1)?.mcpTransportPid;
  199. if (typeof candidate !== "number" || candidate === previousPid) return false;
  200. if (!(await isInProcessTree(electronPid, candidate))) return false;
  201. // 新连接出现前旧进程必须已经退出,否则说明看到的不是重启后的连接。
  202. if (previousPid !== undefined && (await isInProcessTree(electronPid, previousPid)))
  203. return false;
  204. pid = candidate;
  205. return true;
  206. },
  207. { interval: 250, timeout: RESTART_TIMEOUT_MS },
  208. );
  209. // timeoutMsg 在等待开始时就会求值;超时后再读最终证据。
  210. await waiting.catch((error: unknown) => {
  211. throw new Error(
  212. `node_repl frontend 没有${previousPid ? "在退出后自动重启" : "连接"}: previousPid=${previousPid ?? "none"} connectedPids=${JSON.stringify(latest.map((context) => context.mcpTransportPid))}`,
  213. { cause: error },
  214. );
  215. });
  216. if (pid === undefined) throw new Error("node_repl transport PID 缺失");
  217. return pid;
  218. }
  219. async function waitForFixtureTabs(expectedCount: number, timeout = 60_000) {
  220. let latest: FixtureTabSnapshot[] = [];
  221. await browser.waitUntil(
  222. async () => {
  223. latest = await readFixtureTabs();
  224. return latest.length === expectedCount && latest.every((tab) => tab.exists);
  225. },
  226. {
  227. timeout,
  228. timeoutMsg: `fixture tab 数量没有收敛到 ${expectedCount}: ${JSON.stringify(latest)}`,
  229. },
  230. );
  231. return latest;
  232. }
  233. async function readFixtureTabs(): Promise<FixtureTabSnapshot[]> {
  234. const ids = await browser.execute(
  235. (webviewTestId) =>
  236. Array.from(document.querySelectorAll<HTMLElement>(`[data-testid="${webviewTestId}"]`))
  237. .map(
  238. (element) =>
  239. (element as HTMLElement & { getWebContentsId?: () => number }).getWebContentsId?.() ??
  240. 0,
  241. )
  242. .filter((id) => id > 0),
  243. TID_BROWSER_WEBVIEW,
  244. );
  245. return browser.electron.execute(
  246. async (electron, targetIds, fixtureRoot) => {
  247. const fixtureOrigin = new URL(fixtureRoot).origin;
  248. const snapshots = await Promise.all(
  249. targetIds.map(async (id) => {
  250. const guest = electron.webContents.fromId(id);
  251. if (!guest || guest.isDestroyed()) return { exists: false, id, state: "", url: "" };
  252. const url = guest.getURL();
  253. if (!url.startsWith(fixtureOrigin)) return null;
  254. const state = (await guest.executeJavaScript(
  255. "document.querySelector('#state')?.value ?? ''",
  256. )) as string;
  257. return { exists: true, id, state, url };
  258. }),
  259. );
  260. return snapshots.filter((item): item is FixtureTabSnapshot => item !== null);
  261. },
  262. ids,
  263. fixtureRootUrl,
  264. ) as unknown as Promise<FixtureTabSnapshot[]>;
  265. }
  266. async function closeFixtureGuests() {
  267. if (!fixtureRootUrl) return;
  268. await browser.electron.execute((electron, fixtureRoot) => {
  269. const fixtureOrigin = new URL(fixtureRoot).origin;
  270. for (const contents of electron.webContents.getAllWebContents()) {
  271. if (!contents.isDestroyed() && contents.getURL().startsWith(fixtureOrigin)) {
  272. contents.close({ waitForBeforeUnload: false });
  273. }
  274. }
  275. }, fixtureRootUrl);
  276. }
  277. async function waitForPermissionAndApproveOnce(expectedTitle: string) {
  278. let latest = "";
  279. await browser.waitUntil(
  280. async () => {
  281. const state = await browser.execute(() => {
  282. const listboxes = Array.from(
  283. document.querySelectorAll<HTMLElement>('[role="listbox"]'),
  284. ).filter((element) => {
  285. const label = element.getAttribute("aria-label")?.trim();
  286. return label === "Permission required" || label === "需要权限";
  287. });
  288. return {
  289. allowOnceCount: listboxes.reduce(
  290. (count, element) =>
  291. count +
  292. element.querySelectorAll(
  293. 'button[role="option"][data-permission-option-kind="allowOnce"]',
  294. ).length,
  295. 0,
  296. ),
  297. count: listboxes.length,
  298. };
  299. });
  300. latest = JSON.stringify(state);
  301. return state.count === 1 && state.allowOnceCount === 1;
  302. },
  303. {
  304. timeout: 30_000,
  305. timeoutMsg: `node_repl 权限请求没有出现(${expectedTitle}): ${latest}`,
  306. },
  307. );
  308. const clicked = await browser.execute(() => {
  309. const listboxes = Array.from(document.querySelectorAll<HTMLElement>('[role="listbox"]')).filter(
  310. (element) => {
  311. const label = element.getAttribute("aria-label")?.trim();
  312. return label === "Permission required" || label === "需要权限";
  313. },
  314. );
  315. const options = listboxes.flatMap((listbox) =>
  316. Array.from(
  317. listbox.querySelectorAll<HTMLButtonElement>(
  318. 'button[role="option"][data-permission-option-kind="allowOnce"]',
  319. ),
  320. ),
  321. );
  322. if (listboxes.length !== 1 || options.length !== 1) return false;
  323. options[0]?.click();
  324. return true;
  325. });
  326. // 一次只批准一个请求,避免顺手批准下一张权限卡。
  327. expect(clicked).toBe(true);
  328. }
  329. async function readMcpLogContexts(): Promise<McpLogContext[]> {
  330. const contexts: McpLogContext[] = [];
  331. for (const logDir of await resolveMcpLogDirs()) {
  332. const files = await readdir(logDir).catch(() => []);
  333. for (const file of files) {
  334. const content = await readFile(join(logDir, file), "utf8").catch(() => "");
  335. for (const line of content.split("\n")) {
  336. const entry = parseRecord(line);
  337. const context = asRecord(entry?.context) as McpLogContext;
  338. const event =
  339. typeof entry?.event === "string"
  340. ? entry.event
  341. : typeof context.event === "string"
  342. ? context.event
  343. : undefined;
  344. if (event?.startsWith("mcp.")) contexts.push({ ...context, event });
  345. }
  346. }
  347. }
  348. return contexts;
  349. }
  350. async function resolveMcpLogDirs(): Promise<string[]> {
  351. const explicit = process.env.ZCODE_LOG_DIR?.trim();
  352. if (explicit) return [explicit];
  353. const artifactDir = process.env.ZCODE_E2E_ARTIFACT_DIR?.trim();
  354. if (artifactDir) {
  355. const runtimeLogDir = join(artifactDir, "runtime-logs");
  356. const workers = await readdir(runtimeLogDir, { withFileTypes: true }).catch(() => []);
  357. const workerLogDirs = workers
  358. .filter((entry) => entry.isDirectory())
  359. .map((entry) => join(runtimeLogDir, entry.name, "agent"));
  360. if (workerLogDirs.length > 0) return workerLogDirs;
  361. }
  362. return [join(E2E_PATHS.storageRoot, "cli", "log")];
  363. }
  364. function parseRecord(value: string): Record<string, unknown> | null {
  365. try {
  366. const parsed = JSON.parse(value) as unknown;
  367. return parsed && typeof parsed === "object" && !Array.isArray(parsed)
  368. ? (parsed as Record<string, unknown>)
  369. : null;
  370. } catch {
  371. return null;
  372. }
  373. }
  374. function asRecord(value: unknown): Record<string, unknown> {
  375. return value && typeof value === "object" && !Array.isArray(value)
  376. ? (value as Record<string, unknown>)
  377. : {};
  378. }