zcodeAgentService.mcpTelemetry.test.ts 4.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116
  1. import { mkdtempSync, rmSync, writeFileSync } from "node:fs";
  2. import { tmpdir } from "node:os";
  3. import { join } from "node:path";
  4. import type { ZCodeMcpTelemetryEvent, ZCodeMcpResourceSample } from "@zcode/shared";
  5. import { afterEach, describe, expect, it } from "vitest";
  6. import { createZCodeAgentService } from "../src/zcode-agent/zcodeAgentService.js";
  7. const MCP_TELEMETRY_FAKE_AGENT = `
  8. let buffer = "";
  9. function send(value) { process.stdout.write(JSON.stringify(value) + "\\n"); }
  10. process.stdin.on("data", (chunk) => {
  11. buffer += chunk.toString("utf8");
  12. let newline;
  13. while ((newline = buffer.indexOf("\\n")) >= 0) {
  14. const line = buffer.slice(0, newline);
  15. buffer = buffer.slice(newline + 1);
  16. if (!line.trim()) continue;
  17. const message = JSON.parse(line);
  18. if (message.method !== "session/list" || message.id === undefined) continue;
  19. send({ id: message.id, result: { sessions: [] } });
  20. const event = {
  21. kind: "memory",
  22. arch: "x64",
  23. platform: "linux",
  24. occurredAt: 1000,
  25. mcpId: "custom:123456789abc",
  26. mcpInstanceId: "mcp-instance-1",
  27. mcpIsolation: "session",
  28. mcpSource: "custom",
  29. memoryKb: 65536,
  30. memoryScope: "process_tree",
  31. ownerSessionCount: 0,
  32. unownedSeconds: 61,
  33. orphanSuspected: true,
  34. };
  35. send({ method: "process/mcpTelemetry", params: { ...event, mcpServerName: "private" } });
  36. send({ method: "process/mcpTelemetry", params: event });
  37. const samples = [{ mcpId: "builtin:node_repl", instanceToken: "cli-instance-01", sampledAt: 300000,
  38. intervalMs: 300000, processCount: 2, rssKbTotal: 120000, rssKbMaxProcess: 80000,
  39. cpuTimeMsDelta: 30000, uptimeMinutes: 5, platform: "linux", arch: "x64", logicalCpuCount: 8, totalMemoryGb: 32 }];
  40. send({ method: "process/mcpResourceSamples", params: [{ ...samples[0], pid: 123 }] });
  41. send({ method: "process/mcpResourceSamples", params: samples });
  42. }
  43. });
  44. `;
  45. describe("ZCodeAgentService MCP telemetry", () => {
  46. const tempDirs: string[] = [];
  47. afterEach(() => {
  48. for (const dir of tempDirs.splice(0)) rmSync(dir, { recursive: true, force: true });
  49. });
  50. it("strictly validates MCP telemetry before publishing the process-level event", async () => {
  51. const workspacePath = mkdtempSync(join(tmpdir(), "zcode-mcp-telemetry-"));
  52. tempDirs.push(workspacePath);
  53. const scriptPath = join(workspacePath, "mcp-telemetry-agent.cjs");
  54. writeFileSync(scriptPath, MCP_TELEMETRY_FAKE_AGENT);
  55. const service = createZCodeAgentService({
  56. commandResolver: () => ({ command: process.execPath, args: [scriptPath] }),
  57. });
  58. const events: ZCodeMcpTelemetryEvent[] = [];
  59. const subscription = service.onDynamicMcpTelemetry()((event) => events.push(event));
  60. try {
  61. await service.listSessions({ workspacePath });
  62. await new Promise((resolve) => setTimeout(resolve, 20));
  63. expect(events).toEqual([
  64. {
  65. arch: "x64",
  66. kind: "memory",
  67. mcpId: "custom:123456789abc",
  68. mcpInstanceId: "mcp-instance-1",
  69. mcpIsolation: "session",
  70. mcpSource: "custom",
  71. memoryKb: 65_536,
  72. memoryScope: "process_tree",
  73. occurredAt: 1_000,
  74. orphanSuspected: true,
  75. ownerSessionCount: 0,
  76. platform: "linux",
  77. unownedSeconds: 61,
  78. },
  79. ]);
  80. } finally {
  81. subscription.dispose();
  82. await service.disposeAllAndWait();
  83. }
  84. });
  85. it("通过真实 stdio 解析资源数组,丢弃含 PID 的通知", async () => {
  86. const workspacePath = mkdtempSync(join(tmpdir(), "zcode-mcp-resources-"));
  87. tempDirs.push(workspacePath);
  88. const scriptPath = join(workspacePath, "agent.cjs");
  89. writeFileSync(scriptPath, MCP_TELEMETRY_FAKE_AGENT);
  90. const service = createZCodeAgentService({
  91. commandResolver: () => ({ command: process.execPath, args: [scriptPath] }),
  92. });
  93. const batches: ZCodeMcpResourceSample[][] = [];
  94. const subscription = service.onDynamicMcpResourceSamples()((samples) => batches.push(samples));
  95. try {
  96. await service.listSessions({ workspacePath });
  97. await expect.poll(() => batches.length).toBe(1);
  98. expect(batches[0]).toEqual([
  99. expect.objectContaining({
  100. mcpId: "builtin:node_repl",
  101. rssKbTotal: 120000,
  102. cpuTimeMsDelta: 30000,
  103. }),
  104. ]);
  105. } finally {
  106. subscription.dispose();
  107. await service.disposeAllAndWait();
  108. }
  109. });
  110. });