mcp-ui-connection-ready.test.ts 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. import { describe, expect, it, vi } from "vitest";
  2. import { mcpUiInstances } from "../src/zcode-protocol/mcp-ui/instances.js";
  3. import { openMcpUiInstance } from "../src/zcode-protocol/mcp-ui/protocol.js";
  4. const binding = {
  5. workspace: "w",
  6. sessionId: "s",
  7. pluginId: "p",
  8. serverName: "m",
  9. scopeId: "v",
  10. resourceUri: "ui://app",
  11. ownerWebContentsId: 1,
  12. };
  13. describe("MCP App connection readiness", () => {
  14. it.each(["ready", "session-closed", "session-replaced", "connection-replaced", "failed"])(
  15. "waits for startup and validates ownership before opening: %s",
  16. async (outcome) => {
  17. const source = { identity: "source", generation: 1 };
  18. let current: typeof source | null = null;
  19. const gate = Promise.withResolvers<typeof source | null>();
  20. const record = {
  21. app: {
  22. getMcpAppConnectionSnapshot: () => current,
  23. waitForMcpAppConnection: () => gate.promise,
  24. onMcpAppConnectionInvalidated: () => () => {},
  25. unsubscribeMcpResourcesForUi: async () => {},
  26. },
  27. };
  28. const sessions = new Map([[binding.sessionId, record]]);
  29. const context = { sessions } as unknown as Parameters<typeof openMcpUiInstance>[0];
  30. const params = {
  31. ...binding,
  32. workspace: { workspacePath: binding.workspace, workspaceKey: binding.workspace },
  33. };
  34. const settled = vi.fn();
  35. const opening = openMcpUiInstance(context, params);
  36. void opening.then(settled, settled);
  37. await Promise.resolve();
  38. expect(settled).not.toHaveBeenCalled();
  39. current = source;
  40. if (outcome === "session-closed") sessions.clear();
  41. if (outcome === "session-replaced") sessions.set(binding.sessionId, { ...record });
  42. if (outcome === "connection-replaced") current = { ...source, generation: 2 };
  43. if (outcome === "failed") current = null;
  44. gate.resolve(outcome === "failed" ? null : source);
  45. if (outcome === "ready") {
  46. const lease = await opening;
  47. expect(mcpUiInstances.validate(lease, params, source).lease).toEqual(lease);
  48. mcpUiInstances.close(lease);
  49. } else {
  50. await expect(opening).rejects.toThrow();
  51. }
  52. },
  53. );
  54. });