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

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