mcp-ui-open-reconnect.test.ts 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. import { expect, it, vi } from "vitest";
  2. import type { ZCodeProtocolAgentServerContext } from "../src/zcode-protocol/server-types.js";
  3. import { mcpUiInstances } from "../src/zcode-protocol/mcp-ui/instances.js";
  4. import { openMcpUiInstance } from "../src/zcode-protocol/mcp-ui/protocol.js";
  5. const params = {
  6. workspace: { workspacePath: "/Users/dev/w", workspaceKey: "/Users/dev/w" },
  7. sessionId: "s",
  8. pluginId: "p",
  9. serverName: "m",
  10. scopeId: "v",
  11. resourceUri: "ui://app",
  12. ownerWebContentsId: 1,
  13. };
  14. function createContext(reconnected: { identity: string; generation: number } | null) {
  15. let source: { identity: string; generation: number } | null = null;
  16. const reconnectMcpAppConnection = vi.fn(async () => {
  17. source = reconnected;
  18. });
  19. const record = {
  20. app: {
  21. getMcpAppConnectionSnapshot: () => source,
  22. // 已有连接任务先等待;本例的连接已经停在 failed,等待立即返回空快照。
  23. waitForMcpAppConnection: async () => source,
  24. reconnectMcpAppConnection,
  25. onMcpAppConnectionInvalidated: () => () => {},
  26. unsubscribeMcpResourcesForUi: async () => {},
  27. },
  28. traceContext: { traceId: "trace" },
  29. };
  30. // 打开前先经过 session 生命周期的就绪检查;没有持久化存储时按常驻 session 判定已就绪。
  31. const context = {
  32. deps: {},
  33. sessions: new Map([[params.sessionId, record]]),
  34. } as unknown as ZCodeProtocolAgentServerContext;
  35. return { context, reconnectMcpAppConnection };
  36. }
  37. // 修复前连接不可用时直接报错;stdio 崩溃后连接停在 failed,用户点重试也无法恢复。
  38. it("reconnects once before opening an App whose connection is unavailable", async () => {
  39. const { context, reconnectMcpAppConnection } = createContext({ identity: "c", generation: 2 });
  40. const lease = await openMcpUiInstance(context, params);
  41. expect(reconnectMcpAppConnection).toHaveBeenCalledExactlyOnceWith("m");
  42. mcpUiInstances.close(lease);
  43. });
  44. it("reports the unavailable connection when reconnecting does not restore it", async () => {
  45. const { context, reconnectMcpAppConnection } = createContext(null);
  46. await expect(openMcpUiInstance(context, params)).rejects.toMatchObject({
  47. code: -32001,
  48. message: "MCP App connection is unavailable",
  49. });
  50. expect(reconnectMcpAppConnection).toHaveBeenCalledOnce();
  51. });