conversation-session-mcp-oauth-status-isolation.test.ts 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570
  1. import { readFile, writeFile, mkdir, rm } from "node:fs/promises";
  2. import { join, resolve } from "node:path";
  3. import {
  4. TID_MCP_OPEN_AUTHORIZATION_BUTTON,
  5. TID_MCP_SERVER_ROW,
  6. TID_PLUGIN_MCP_SERVER_ROW,
  7. TID_SETTINGS_BACK_BUTTON,
  8. TID_SETTINGS_PAGE,
  9. TID_SETTINGS_SECTION_NAV,
  10. TID_TASK_SETTINGS_BUTTON,
  11. testId,
  12. } from "@zcode/shared/test-ids";
  13. import {
  14. clearAppData,
  15. clickTestIdByDom,
  16. getE2EAppDataPaths,
  17. waitForTestIdByDom,
  18. } from "#e2e/helpers/desktop-app";
  19. import {
  20. E2E_REPLY_TOKEN,
  21. prepareV4ConversationE2E,
  22. sendV4Prompt,
  23. startNewV4Draft,
  24. waitForV4AssistantMessageContaining,
  25. waitForV4ConversationState,
  26. waitForV4ComposerText,
  27. waitForV4Pane,
  28. waitForV4UserMessageContaining,
  29. } from "#e2e/helpers/v4-conversation";
  30. import { waitForUpstreamRequest } from "#e2e/helpers/conversation-session-network";
  31. import { waitForToolCallBlockByToolName } from "#e2e/helpers/conversation-session-tool";
  32. import { ensureToolCrossProductFullAccessMode } from "#e2e/helpers/conversation-session-tool-cross-product";
  33. import {
  34. startMcpOAuthStatusIsolationServer,
  35. type McpOAuthStatusIsolationServer,
  36. } from "#e2e/helpers/mcp-oauth-status-isolation";
  37. const CASE_TIMEOUT_MS = 180_000;
  38. // 至少两个 OAuth status poll 周期,用来确认轮询不会断开或重建连接。
  39. const STATUS_POLL_SETTLE_MS = 2_500;
  40. const DIRECT_MCP_NAME = "everything";
  41. const DIRECT_MCP_TOOL_NAME = "mcp__everything__ping";
  42. const PLAIN_HTTP_MCP_NAME = "plain_http";
  43. const PLAIN_HTTP_MCP_TOOL_NAME = "mcp__plain_http__ping";
  44. const PLUGIN_ID = "e2e-plugin-mcp-oauth@e2e-fixture";
  45. const PLUGIN_NAME = "e2e-plugin-mcp-oauth";
  46. const PLUGIN_RUNTIME_MCP_NAME = `plugin:${PLUGIN_NAME}:canva`;
  47. const PROMPT_MARKER = "E2E_MCP_OAUTH_STATUS_ISOLATION";
  48. const DIRECT_RESULT = `E2E_MCP_DIRECT_PONG:${PROMPT_MARKER}`;
  49. const PLAIN_HTTP_RESULT = `E2E_MCP_HTTP_PONG:${PROMPT_MARKER}`;
  50. const E2E_PATHS = getE2EAppDataPaths();
  51. const CLI_CONFIG_FILE = join(E2E_PATHS.homeDir, ".zcode", "cli", "config.json");
  52. const INSTALLED_PLUGINS_FILE = join(
  53. E2E_PATHS.homeDir,
  54. ".zcode",
  55. "cli",
  56. "plugins",
  57. "installed_plugins.json",
  58. );
  59. const PLUGIN_ROOT = join(E2E_PATHS.homeDir, ".zcode", "cli", "e2e-fixtures", PLUGIN_NAME);
  60. const PLUGIN_MANIFEST_FILE = join(PLUGIN_ROOT, ".zcode-plugin", "plugin.json");
  61. const CASE_ROOT = join(E2E_PATHS.workspace, "mcp-oauth-status-isolation-e2e");
  62. const DIRECT_MCP_CALL_LOG = join(CASE_ROOT, "direct-mcp-calls.ndjson");
  63. const DIRECT_MCP_SERVER_SCRIPT = resolve(
  64. process.cwd(),
  65. "test/e2e/fixtures/mcp/oauth-status-isolation-direct-server.mjs",
  66. );
  67. describe("会话区 MCP OAuth 状态刷新隔离 E2E", () => {
  68. let oauthServer: McpOAuthStatusIsolationServer | null = null;
  69. after(async () => {
  70. await browser.electron.restoreAllMocks();
  71. await clearAppData();
  72. await oauthServer?.close();
  73. });
  74. it("MO01/MO03: 插件 OAuth 状态刷新不会断开 stdio 与普通 HTTP MCP", async function () {
  75. this.timeout(CASE_TIMEOUT_MS);
  76. await prepareV4ConversationE2E();
  77. oauthServer = await startMcpOAuthStatusIsolationServer();
  78. await writeMcpFixtures(oauthServer.mcpUrl, oauthServer.plainHttpMcpUrl);
  79. const openExternalMock = await browser.electron.mock("shell", "openExternal");
  80. await openExternalMock.mockResolvedValue(undefined);
  81. await openMcpSettings();
  82. await waitForMcpRow({
  83. status: "connected",
  84. testIdValue: testId(TID_MCP_SERVER_ROW, DIRECT_MCP_NAME),
  85. toolCount: 1,
  86. });
  87. await waitForMcpRow({
  88. status: "connected",
  89. testIdValue: testId(TID_MCP_SERVER_ROW, PLAIN_HTTP_MCP_NAME),
  90. toolCount: 1,
  91. });
  92. await waitForMcpRow({
  93. status: "connecting",
  94. testIdValue: testId(TID_PLUGIN_MCP_SERVER_ROW, PLUGIN_RUNTIME_MCP_NAME),
  95. toolCount: 0,
  96. });
  97. const directMcpPid = await waitForDirectMcpProcessStarted(30_000);
  98. await waitForTestIdByDom(testId(TID_MCP_OPEN_AUTHORIZATION_BUTTON, PLUGIN_RUNTIME_MCP_NAME), {
  99. timeout: 30_000,
  100. timeoutMsg: "插件 MCP 没有展示 OAuth 授权入口",
  101. });
  102. const pendingSnapshot = oauthServer.snapshot();
  103. expect(pendingSnapshot.unauthorizedMcpRequestCount).toBeGreaterThan(0);
  104. // 修复原因:旧实现的 1s OAuth poll 会把空的用户 MCP 子集送进 replace 路径。
  105. // 等至少两个周期,同时检查用户 stdio 进程和普通 HTTP 连接没有被断开重建。
  106. await browser.pause(STATUS_POLL_SETTLE_MS);
  107. expect(oauthServer.snapshot()).toMatchObject({
  108. plainHttpInitializeCount: pendingSnapshot.plainHttpInitializeCount,
  109. unauthorizedMcpRequestCount: pendingSnapshot.unauthorizedMcpRequestCount,
  110. });
  111. await expectMcpRow({
  112. status: "connected",
  113. testIdValue: testId(TID_MCP_SERVER_ROW, DIRECT_MCP_NAME),
  114. toolCount: 1,
  115. });
  116. expectProcessAlive(directMcpPid, "status-only poll 期间用户级 MCP 被断开");
  117. await expectMcpRow({
  118. status: "connected",
  119. testIdValue: testId(TID_MCP_SERVER_ROW, PLAIN_HTTP_MCP_NAME),
  120. toolCount: 1,
  121. });
  122. await clickTestIdByDom(testId(TID_MCP_OPEN_AUTHORIZATION_BUTTON, PLUGIN_RUNTIME_MCP_NAME), {
  123. timeout: 15_000,
  124. timeoutMsg: "插件 MCP OAuth 授权按钮不可点击",
  125. });
  126. const authorizationUrl = await waitForOpenedAuthorizationUrl(openExternalMock);
  127. await oauthServer.completeAuthorization(authorizationUrl);
  128. await waitForMcpRow({
  129. status: "connected",
  130. testIdValue: testId(TID_PLUGIN_MCP_SERVER_ROW, PLUGIN_RUNTIME_MCP_NAME),
  131. toolCount: 1,
  132. });
  133. await expectMcpRow({
  134. status: "connected",
  135. testIdValue: testId(TID_MCP_SERVER_ROW, DIRECT_MCP_NAME),
  136. toolCount: 1,
  137. });
  138. await expectMcpRow({
  139. status: "connected",
  140. testIdValue: testId(TID_MCP_SERVER_ROW, PLAIN_HTTP_MCP_NAME),
  141. toolCount: 1,
  142. });
  143. // 修复原因:预热的草稿会话在 session/create 时就连接插件 OAuth server,参与同一轮授权,
  144. // 授权完成后自己也 initialize 一次,所以不能断言全进程只有 1 次
  145. // (docs/issues/mcp-settings-legacy/08)。授权仍只走一次;之后的轮询不能再触发 initialize。
  146. await browser.pause(STATUS_POLL_SETTLE_MS);
  147. const authorizedSnapshot = oauthServer.snapshot();
  148. expect(authorizedSnapshot).toMatchObject({
  149. authorizationRequestCount: 1,
  150. // 运行日志确认 workspace 管理连接和预热 Session 各持有一个 MCP client;
  151. // OAuth 流程仍只有一次,凭据发布后两个既有 client 各完成一次 initialize。
  152. authorizedInitializeCount: pendingSnapshot.plainHttpInitializeCount,
  153. plainHttpInitializeCount: pendingSnapshot.plainHttpInitializeCount,
  154. registrationRequestCount: 1,
  155. tokenRequestCount: 1,
  156. });
  157. await browser.pause(STATUS_POLL_SETTLE_MS);
  158. expect(oauthServer.snapshot().authorizedInitializeCount).toBe(
  159. authorizedSnapshot.authorizedInitializeCount,
  160. );
  161. await verifyConfigLoadFailureKeepsMcpRuntime(directMcpPid, oauthServer);
  162. await clickTestIdByDom(TID_SETTINGS_BACK_BUTTON, {
  163. timeout: 15_000,
  164. timeoutMsg: "MCP 设置页返回按钮没有出现",
  165. });
  166. await waitForV4Pane(() => true, "完成 MCP OAuth 后没有回到工作区", 15_000);
  167. await startNewV4Draft();
  168. // 权限模式属于当前草稿;先设模式再新建会恢复默认模式,真实 MCP 调用会停在审批。
  169. await ensureToolCrossProductFullAccessMode();
  170. const prompt = `${PROMPT_MARKER}: Call ${DIRECT_MCP_TOOL_NAME} exactly once with marker "${PROMPT_MARKER}", then call ${PLAIN_HTTP_MCP_TOOL_NAME} exactly once with the same marker, then reply with exactly "${E2E_REPLY_TOKEN}" and no other text.`;
  171. await sendV4Prompt(prompt);
  172. await waitForV4ComposerText("", "MCP OAuth 隔离 case 首发后输入框没有清空");
  173. await waitForV4UserMessageContaining(PROMPT_MARKER);
  174. await waitForUpstreamRequest(
  175. {
  176. excludes: ["Generate a concise title", "CRITICAL: Respond with TEXT ONLY"],
  177. includes: [PROMPT_MARKER, DIRECT_MCP_TOOL_NAME, PLAIN_HTTP_MCP_TOOL_NAME],
  178. },
  179. "首轮 provider 请求没有同时暴露 stdio 与普通 HTTP MCP 工具",
  180. 60_000,
  181. );
  182. await waitForToolCallBlockByToolName(DIRECT_MCP_TOOL_NAME, 60_000);
  183. await waitForDirectMcpCall(PROMPT_MARKER, 60_000);
  184. await waitForUpstreamRequest(
  185. {
  186. excludes: ["Generate a concise title", "CRITICAL: Respond with TEXT ONLY"],
  187. includes: [PROMPT_MARKER, DIRECT_MCP_TOOL_NAME, DIRECT_RESULT],
  188. },
  189. "用户级 MCP tool_result 没有进入 provider continuation",
  190. 60_000,
  191. );
  192. await waitForToolCallBlockByToolName(PLAIN_HTTP_MCP_TOOL_NAME, 60_000);
  193. await waitForPlainHttpMcpCall(oauthServer, PROMPT_MARKER, 60_000);
  194. await waitForUpstreamRequest(
  195. {
  196. excludes: ["Generate a concise title", "CRITICAL: Respond with TEXT ONLY"],
  197. includes: [PROMPT_MARKER, DIRECT_RESULT, PLAIN_HTTP_MCP_TOOL_NAME, PLAIN_HTTP_RESULT],
  198. },
  199. "普通 HTTP MCP tool_result 没有进入 provider continuation",
  200. 60_000,
  201. );
  202. await waitForV4AssistantMessageContaining(E2E_REPLY_TOKEN);
  203. await waitForV4ConversationState(
  204. (snapshot) => snapshot.state === "idle" && snapshot.queueCount === 0,
  205. "MCP OAuth 隔离 case 完成后会话没有回到 idle",
  206. 60_000,
  207. );
  208. });
  209. });
  210. async function openMcpSettings(): Promise<void> {
  211. await clickTestIdByDom(TID_TASK_SETTINGS_BUTTON, {
  212. timeout: 15_000,
  213. timeoutMsg: "没有找到设置入口按钮",
  214. });
  215. await waitForTestIdByDom(TID_SETTINGS_PAGE, {
  216. timeout: 15_000,
  217. timeoutMsg: "设置页没有渲染",
  218. });
  219. await clickTestIdByDom(testId(TID_SETTINGS_SECTION_NAV, "mcp"), {
  220. timeout: 15_000,
  221. timeoutMsg: "设置页没有出现 MCP 分区入口",
  222. });
  223. }
  224. interface McpRowExpectation {
  225. status: string;
  226. testIdValue: string;
  227. toolCount: number;
  228. }
  229. interface McpRowSnapshot {
  230. exists: boolean;
  231. status: string | null;
  232. text: string;
  233. toolCount: number | null;
  234. }
  235. async function waitForMcpRow(expectation: McpRowExpectation): Promise<void> {
  236. let latest: McpRowSnapshot = {
  237. exists: false,
  238. status: null,
  239. text: "",
  240. toolCount: null,
  241. };
  242. await browser.waitUntil(
  243. async () => {
  244. latest = await readMcpRow(expectation.testIdValue);
  245. return matchesMcpRow(latest, expectation);
  246. },
  247. {
  248. timeout: 45_000,
  249. timeoutMsg: `MCP 行状态未收敛: expected=${JSON.stringify(expectation)} latest=${JSON.stringify(latest)}`,
  250. },
  251. );
  252. }
  253. async function expectMcpRow(expectation: McpRowExpectation): Promise<void> {
  254. expect(await readMcpRow(expectation.testIdValue)).toMatchObject({
  255. exists: true,
  256. status: expectation.status,
  257. toolCount: expectation.toolCount,
  258. });
  259. }
  260. function matchesMcpRow(snapshot: McpRowSnapshot, expectation: McpRowExpectation): boolean {
  261. return (
  262. snapshot.exists &&
  263. snapshot.status === expectation.status &&
  264. snapshot.toolCount === expectation.toolCount
  265. );
  266. }
  267. async function readMcpRow(testIdValue: string): Promise<McpRowSnapshot> {
  268. return (await browser.execute((targetTestId) => {
  269. const element = Array.from(document.querySelectorAll<HTMLElement>("[data-testid]")).find(
  270. (item) => item.dataset.testid === targetTestId,
  271. );
  272. if (!element) {
  273. return { exists: false, status: null, text: "", toolCount: null };
  274. }
  275. const rawToolCount = element.dataset.mcpToolCount;
  276. return {
  277. exists: true,
  278. status: element.dataset.mcpStatus ?? null,
  279. text: element.innerText,
  280. toolCount: rawToolCount === undefined || rawToolCount === "" ? null : Number(rawToolCount),
  281. };
  282. }, testIdValue)) as McpRowSnapshot;
  283. }
  284. async function waitForOpenedAuthorizationUrl(
  285. openExternalMock: Awaited<ReturnType<typeof browser.electron.mock>>,
  286. ): Promise<string> {
  287. let authorizationUrl = "";
  288. await browser.waitUntil(
  289. async () => {
  290. await openExternalMock.update();
  291. authorizationUrl =
  292. openExternalMock.mock.calls
  293. .map((call) => call[0])
  294. .find(
  295. (value): value is string => typeof value === "string" && value.includes("/authorize?"),
  296. ) ?? "";
  297. return Boolean(authorizationUrl);
  298. },
  299. {
  300. timeout: 15_000,
  301. timeoutMsg: "没有捕获到平台 openExternal 的 MCP OAuth URL",
  302. },
  303. );
  304. return authorizationUrl;
  305. }
  306. async function writeMcpFixtures(mcpUrl: string, plainHttpMcpUrl: string): Promise<void> {
  307. await mkdir(CASE_ROOT, { recursive: true });
  308. await rm(DIRECT_MCP_CALL_LOG, { force: true });
  309. await mkdir(join(PLUGIN_ROOT, ".zcode-plugin"), { recursive: true });
  310. await mkdir(join(E2E_PATHS.homeDir, ".zcode", "cli", "plugins"), {
  311. recursive: true,
  312. });
  313. await writeFile(
  314. PLUGIN_MANIFEST_FILE,
  315. `${JSON.stringify(
  316. {
  317. author: { name: "ZCode E2E" },
  318. description: "E2E fixture plugin with an OAuth-protected MCP server.",
  319. license: "MIT",
  320. mcpServers: {
  321. canva: {
  322. // 此夹具只实现 legacy;显式声明以排除 dual-era 探测握手对 OAuth 连接计数的干扰。
  323. protocolVersion: "legacy",
  324. oauth: {
  325. clientName: "ZCode MCP OAuth E2E",
  326. scope: "mcp:tools",
  327. type: "authorization_code",
  328. },
  329. timeoutMs: 30_000,
  330. type: "http",
  331. url: mcpUrl,
  332. },
  333. },
  334. name: PLUGIN_NAME,
  335. version: "0.0.0",
  336. },
  337. null,
  338. 2,
  339. )}\n`,
  340. "utf8",
  341. );
  342. await writeFile(
  343. INSTALLED_PLUGINS_FILE,
  344. `${JSON.stringify(
  345. {
  346. plugins: [
  347. {
  348. id: PLUGIN_ID,
  349. installPath: PLUGIN_ROOT,
  350. installedAt: "2026-07-10T00:00:00.000Z",
  351. marketplace: "e2e-fixture",
  352. name: PLUGIN_NAME,
  353. scope: "user",
  354. updatedAt: "2026-07-10T00:00:00.000Z",
  355. version: "0.0.0",
  356. },
  357. ],
  358. version: 1,
  359. },
  360. null,
  361. 2,
  362. )}\n`,
  363. "utf8",
  364. );
  365. const config = await readJsonRecord(CLI_CONFIG_FILE);
  366. const mcp = asRecord(config.mcp);
  367. const servers = asRecord(mcp.servers);
  368. const plugins = asRecord(config.plugins);
  369. const enabledPlugins = asRecord(plugins.enabledPlugins);
  370. enabledPlugins[PLUGIN_ID] = true;
  371. plugins.enabledPlugins = enabledPlugins;
  372. servers[DIRECT_MCP_NAME] = {
  373. args: [DIRECT_MCP_SERVER_SCRIPT],
  374. command: process.execPath,
  375. env: {
  376. E2E_MCP_DIRECT_CALL_LOG: DIRECT_MCP_CALL_LOG,
  377. },
  378. timeoutMs: 30_000,
  379. type: "stdio",
  380. };
  381. servers[PLAIN_HTTP_MCP_NAME] = {
  382. timeoutMs: 30_000,
  383. type: "http",
  384. url: plainHttpMcpUrl,
  385. };
  386. mcp.servers = servers;
  387. config.mcp = mcp;
  388. config.plugins = plugins;
  389. await writeFile(CLI_CONFIG_FILE, `${JSON.stringify(config, null, 2)}\n`, "utf8");
  390. }
  391. async function waitForDirectMcpCall(marker: string, timeoutMs: number): Promise<void> {
  392. let latest: DirectMcpLogEntry[] = [];
  393. await browser.waitUntil(
  394. async () => {
  395. latest = await readDirectMcpCalls();
  396. return latest.some((call) => call.tool === "ping" && call.marker === marker);
  397. },
  398. {
  399. timeout: timeoutMs,
  400. timeoutMsg: `用户级 MCP ping 没有真实执行: ${JSON.stringify(latest)}`,
  401. },
  402. );
  403. }
  404. async function waitForPlainHttpMcpCall(
  405. server: McpOAuthStatusIsolationServer,
  406. marker: string,
  407. timeoutMs: number,
  408. ): Promise<void> {
  409. let latest: string[] = [];
  410. await browser.waitUntil(
  411. async () => {
  412. latest = server.snapshot().plainHttpToolCallMarkers;
  413. return latest.includes(marker);
  414. },
  415. {
  416. timeout: timeoutMs,
  417. timeoutMsg: `普通 HTTP MCP ping 没有真实执行: ${JSON.stringify(latest)}`,
  418. },
  419. );
  420. }
  421. interface DirectMcpLogEntry {
  422. event?: "started";
  423. marker?: string;
  424. pid?: number;
  425. tool?: string;
  426. }
  427. async function waitForDirectMcpProcessStarted(timeoutMs: number): Promise<number> {
  428. let latest: DirectMcpLogEntry[] = [];
  429. let pid = 0;
  430. await browser.waitUntil(
  431. async () => {
  432. latest = await readDirectMcpCalls();
  433. pid = [...latest].reverse().find((entry) => entry.event === "started")?.pid ?? 0;
  434. return pid > 0;
  435. },
  436. {
  437. timeout: timeoutMs,
  438. timeoutMsg: `用户级 MCP 没有记录启动 PID: ${JSON.stringify(latest)}`,
  439. },
  440. );
  441. return pid;
  442. }
  443. function expectProcessAlive(pid: number, message: string): void {
  444. try {
  445. process.kill(pid, 0);
  446. } catch (error) {
  447. throw new Error(`${message}: pid=${pid}`, { cause: error });
  448. }
  449. }
  450. async function verifyConfigLoadFailureKeepsMcpRuntime(
  451. directMcpPid: number,
  452. server: McpOAuthStatusIsolationServer,
  453. ): Promise<void> {
  454. const validConfig = await readFile(CLI_CONFIG_FILE, "utf8");
  455. await clickTestIdByDom(TID_SETTINGS_BACK_BUTTON, {
  456. timeout: 15_000,
  457. timeoutMsg: "制造 MCP 配置读取失败前无法返回工作区",
  458. });
  459. await waitForV4Pane(() => true, "制造 MCP 配置读取失败前工作区没有恢复", 15_000);
  460. await writeFile(CLI_CONFIG_FILE, "{ invalid e2e mcp config", "utf8");
  461. const plainHttpInitializeCount = server.snapshot().plainHttpInitializeCount;
  462. try {
  463. await openMcpSettings();
  464. // 修复原因:错误实现会把解析失败当空列表并异步执行 replace;等待其越过加载与 connect 窗口,
  465. // 再检查同一 PID,避免只在旧 UI snapshot 尚未更新时产生假阳性。
  466. await browser.pause(2_500);
  467. await expectMcpRow({
  468. status: "connected",
  469. testIdValue: testId(TID_MCP_SERVER_ROW, DIRECT_MCP_NAME),
  470. toolCount: 1,
  471. });
  472. expectProcessAlive(directMcpPid, "配置读取失败后用户级 MCP 被空列表 replace 断开");
  473. await expectMcpRow({
  474. status: "connected",
  475. testIdValue: testId(TID_MCP_SERVER_ROW, PLAIN_HTTP_MCP_NAME),
  476. toolCount: 1,
  477. });
  478. expect(server.snapshot().plainHttpInitializeCount).toBe(plainHttpInitializeCount);
  479. } finally {
  480. await writeFile(CLI_CONFIG_FILE, validConfig, "utf8");
  481. }
  482. await clickTestIdByDom(TID_SETTINGS_BACK_BUTTON, {
  483. timeout: 15_000,
  484. timeoutMsg: "恢复 MCP 配置前无法返回工作区",
  485. });
  486. await waitForV4Pane(() => true, "恢复 MCP 配置前工作区没有出现", 15_000);
  487. await openMcpSettings();
  488. await waitForMcpRow({
  489. status: "connected",
  490. testIdValue: testId(TID_MCP_SERVER_ROW, DIRECT_MCP_NAME),
  491. toolCount: 1,
  492. });
  493. await waitForMcpRow({
  494. status: "connected",
  495. testIdValue: testId(TID_PLUGIN_MCP_SERVER_ROW, PLUGIN_RUNTIME_MCP_NAME),
  496. toolCount: 1,
  497. });
  498. await waitForMcpRow({
  499. status: "connected",
  500. testIdValue: testId(TID_MCP_SERVER_ROW, PLAIN_HTTP_MCP_NAME),
  501. toolCount: 1,
  502. });
  503. // 恢复有效配置后会回到既有 connect replace 收敛路径;本 case 只证明读取失败窗口
  504. // 不会误发空配置并断开原进程,不额外约束恢复阶段必须复用 PID。
  505. }
  506. async function readDirectMcpCalls(): Promise<DirectMcpLogEntry[]> {
  507. try {
  508. const raw = await readFile(DIRECT_MCP_CALL_LOG, "utf8");
  509. return raw
  510. .split("\n")
  511. .map((line) => line.trim())
  512. .filter(Boolean)
  513. .map((line) => JSON.parse(line) as DirectMcpLogEntry);
  514. } catch (error) {
  515. if (error instanceof Error && "code" in error && error.code === "ENOENT") {
  516. return [];
  517. }
  518. throw error;
  519. }
  520. }
  521. async function readJsonRecord(path: string): Promise<Record<string, unknown>> {
  522. try {
  523. return JSON.parse(await readFile(path, "utf8")) as Record<string, unknown>;
  524. } catch (error) {
  525. if (error instanceof Error && "code" in error && error.code === "ENOENT") {
  526. return {};
  527. }
  528. throw error;
  529. }
  530. }
  531. function asRecord(value: unknown): Record<string, unknown> {
  532. return value && typeof value === "object" && !Array.isArray(value)
  533. ? { ...(value as Record<string, unknown>) }
  534. : {};
  535. }