zcodeStdioTransport.test.ts 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494
  1. import { spawn, spawnSync, type ChildProcessWithoutNullStreams } from "node:child_process";
  2. import { EventEmitter } from "node:events";
  3. import { PassThrough } from "node:stream";
  4. import { setTimeout as delay } from "node:timers/promises";
  5. import { afterEach, describe, expect, it, vi } from "vitest";
  6. import { terminateProcessTree } from "@zcode/services/process/processTreeTerminator";
  7. import { ZCodeStdioTransport } from "@zcode/services/node";
  8. const activeChildren = new Set<ChildProcessWithoutNullStreams>();
  9. function waitForExit(child: ChildProcessWithoutNullStreams): Promise<void> {
  10. if (child.exitCode !== null || child.signalCode !== null) {
  11. return Promise.resolve();
  12. }
  13. return new Promise((resolve) => {
  14. child.once("exit", () => resolve());
  15. });
  16. }
  17. function isPidRunning(pid: number): boolean {
  18. try {
  19. process.kill(pid, 0);
  20. } catch {
  21. return false;
  22. }
  23. if (process.platform === "win32") {
  24. // Windows 没有系统 ps;Git 附带的 ps 既不保证 stdout,也不能可靠查询原生 PID。
  25. // process.kill(pid, 0) 已完成当前平台的存活探测。
  26. return true;
  27. }
  28. const result = spawnSync("ps", ["-o", "stat=", "-p", String(pid)], {
  29. encoding: "utf8",
  30. });
  31. const status = result.stdout.trim();
  32. return status.length > 0 && !status.startsWith("Z");
  33. }
  34. afterEach(() => {
  35. for (const child of activeChildren) {
  36. terminateProcessTree(child);
  37. }
  38. activeChildren.clear();
  39. });
  40. describe("ZCodeStdioTransport", () => {
  41. it("stderr failure alone leaves a responsive protocol usable", async () => {
  42. const child = spawn(
  43. process.execPath,
  44. [
  45. "-e",
  46. `
  47. process.stdin.on("data", () => process.stdout.write(JSON.stringify({ id: "pong", result: {} }) + "\\n"));
  48. process.stdin.once("end", () => process.exit(0));
  49. process.stdout.write(JSON.stringify({ id: "ready", result: {} }) + "\\n");
  50. `,
  51. ],
  52. { stdio: ["pipe", "pipe", "pipe"] },
  53. );
  54. activeChildren.add(child);
  55. const transport = new ZCodeStdioTransport(child);
  56. await new Promise<void>((resolve) => transport.onMessage(() => resolve()));
  57. let closed = false;
  58. transport.onClose(() => {
  59. closed = true;
  60. });
  61. child.stderr.emit("error", new Error("diagnostic reader failed"));
  62. const response = new Promise<void>((resolve) => transport.onMessage(() => resolve()));
  63. await transport.send({ id: "ping", method: "workspace/readState", params: {} });
  64. await response;
  65. expect(closed).toBe(false);
  66. await transport.disposeAndWait();
  67. expect(child.exitCode).toBe(0);
  68. });
  69. it("keeps the final stderr line while EOF retires the protocol", async () => {
  70. const child = spawn(
  71. process.execPath,
  72. [
  73. "-e",
  74. `
  75. process.stdin.resume();
  76. process.stdin.once("end", () => process.stderr.write("FINAL_DIAGNOSTIC", () => process.exit(0)));
  77. process.stdout.write(JSON.stringify({ id: "ready", result: {} }) + "\\n");
  78. `,
  79. ],
  80. { stdio: ["pipe", "pipe", "pipe"] },
  81. );
  82. activeChildren.add(child);
  83. const lines: string[] = [];
  84. const transport = new ZCodeStdioTransport(child, { onStderrLine: (line) => lines.push(line) });
  85. await new Promise<void>((resolve) => transport.onMessage(() => resolve()));
  86. // 修复原因:退出后的进程身份复核可能阻塞事件循环,让 250ms drain timer
  87. // 先于 stderr EOF 投递。本用例只验证尾行收集,真实退出时限由后续用例验证。
  88. vi.useFakeTimers({ toFake: ["setTimeout", "clearTimeout"] });
  89. try {
  90. await transport.disposeAndWait();
  91. expect(child.exitCode).toBe(0);
  92. expect(lines).toEqual(["FINAL_DIAGNOSTIC"]);
  93. } finally {
  94. vi.useRealTimers();
  95. }
  96. });
  97. it("disposeAndWait 优先用 stdin EOF 关闭 stdio agent", async () => {
  98. const child = spawn(
  99. process.execPath,
  100. [
  101. "-e",
  102. `
  103. process.stdin.resume();
  104. process.stdin.once("end", () => process.exit(0));
  105. process.stdin.once("close", () => process.exit(0));
  106. setInterval(() => {}, 1000);
  107. `,
  108. ],
  109. {
  110. stdio: ["pipe", "pipe", "pipe"],
  111. windowsHide: true,
  112. },
  113. );
  114. activeChildren.add(child);
  115. const transport = new ZCodeStdioTransport(child);
  116. await delay(50);
  117. const startedAt = Date.now();
  118. // Bugfix: app-server --stdio 的自然关闭边界是 stdin EOF,不能每次关闭都直接
  119. // 进入进程树强杀等待,否则即使 agent 可正常收尾也会带来几秒关窗延迟。
  120. await transport.disposeAndWait();
  121. const durationMs = Date.now() - startedAt;
  122. expect(child.exitCode).toBe(0);
  123. // 阈值依据:产品约束是 Windows 清理落在 Host 3.5s service phase 预算内
  124. // (disposeAndWaitOnce 的绝对 deadline 即按它构造)。原 1s 紧断言在部分
  125. // Windows 机器上不稳定——stdin 管道拆除 + 进程树快照(WMI/CIM 查询)合计
  126. // 可合法耗时 ~2s 且优雅退出仍然成立(exitCode=0),属机器性能差异而非回归;
  127. // Linux/mac 保留 1s 紧阈值不变。
  128. const shutdownBudgetMs = process.platform === "win32" ? 3_500 : 1_000;
  129. expect(durationMs).toBeLessThan(shutdownBudgetMs);
  130. activeChildren.delete(child);
  131. });
  132. it.runIf(process.platform !== "win32")(
  133. "stdin EOF 让根进程先退出时仍回收已发现的 detached 后代",
  134. async () => {
  135. const child = spawn(
  136. process.execPath,
  137. [
  138. "-e",
  139. `
  140. const { spawn } = require("node:child_process");
  141. process.stderr.write("starting\\n");
  142. const descendant = spawn(
  143. process.execPath,
  144. ["-e", 'process.on("SIGTERM", () => {}); process.send?.("ready"); setInterval(() => {}, 1000);'],
  145. { detached: true, stdio: ["ignore", "ignore", "ignore", "ipc"] },
  146. );
  147. descendant.once("message", () => process.stderr.write(String(descendant.pid) + "\\n"));
  148. process.stdin.resume();
  149. process.stdin.once("end", () => process.exit(0));
  150. setInterval(() => {}, 1000);
  151. `,
  152. ],
  153. {
  154. stdio: ["pipe", "pipe", "pipe"],
  155. windowsHide: true,
  156. },
  157. );
  158. activeChildren.add(child);
  159. let reportPid: ((pid: number) => void) | undefined;
  160. const descendantPidPromise = new Promise<number>((resolve) => {
  161. reportPid = resolve;
  162. });
  163. const transport = new ZCodeStdioTransport(child, {
  164. onStderrLine: (line) => {
  165. const pid = Number(line);
  166. if (Number.isInteger(pid)) reportPid?.(pid);
  167. },
  168. });
  169. const descendantPid = await descendantPidPromise;
  170. expect(isPidRunning(descendantPid)).toBe(true);
  171. try {
  172. // 修复原因:EOF 正常关闭期间根进程可能先退出,但 detached MCP 不会随之退出。
  173. // disposeAndWait 必须使用 EOF 前保存的进程树快照完成后代回收。
  174. await transport.disposeAndWait();
  175. expect(isPidRunning(descendantPid)).toBe(false);
  176. } finally {
  177. if (isPidRunning(descendantPid)) {
  178. process.kill(-descendantPid, "SIGKILL");
  179. }
  180. }
  181. activeChildren.delete(child);
  182. },
  183. );
  184. it.runIf(process.platform !== "win32")(
  185. "根进程异常退出后仍按 Host 已拥有的进程组回收后代",
  186. async () => {
  187. const child = spawn(
  188. process.execPath,
  189. [
  190. "-e",
  191. `
  192. const { spawn } = require("node:child_process");
  193. process.stderr.write("starting\\n");
  194. const descendant = spawn(
  195. process.execPath,
  196. ["-e", 'process.send?.("ready"); setInterval(() => {}, 1000);'],
  197. { stdio: ["ignore", "ignore", "ignore", "ipc"] },
  198. );
  199. descendant.once("message", () => {
  200. const frame = JSON.stringify({ method: "state.updated", params: { pid: descendant.pid } }) + "\\n";
  201. process.stdout.write(frame, () => setTimeout(() => process.exit(1), 50));
  202. });
  203. `,
  204. ],
  205. {
  206. detached: true,
  207. stdio: ["pipe", "pipe", "pipe"],
  208. windowsHide: true,
  209. },
  210. );
  211. activeChildren.add(child);
  212. const transport = new ZCodeStdioTransport(child, {
  213. ownedProcessGroupId: child.pid,
  214. });
  215. const descendantPidPromise = new Promise<number>((resolve) => {
  216. transport.onMessage((message) => {
  217. if (!("method" in message) || message.method !== "state.updated") return;
  218. const pid = (message.params as { pid?: unknown } | undefined)?.pid;
  219. if (typeof pid === "number") resolve(pid);
  220. });
  221. });
  222. const descendantPid = await descendantPidPromise;
  223. await waitForExit(child);
  224. expect(isPidRunning(descendantPid)).toBe(true);
  225. try {
  226. // 修复原因:运行期协议热路径不能为了异常退出兜底扫描进程表。
  227. // POSIX Host 已把 Agent 放进独立进程组;root 退出后应在 cleanup 边界
  228. // 按已拥有的 PGID 找回同组后代,而不是依赖某条运行期 notification。
  229. await transport.disposeAndWait();
  230. expect(isPidRunning(descendantPid)).toBe(false);
  231. } finally {
  232. if (isPidRunning(descendantPid)) {
  233. process.kill(-descendantPid, "SIGKILL");
  234. }
  235. }
  236. activeChildren.delete(child);
  237. },
  238. );
  239. it.runIf(process.platform === "win32")(
  240. "Windows 根进程异常退出后仍按 ParentProcessId 回收 task tree",
  241. async () => {
  242. const spawnRequestedAt = Date.now();
  243. const child = spawn(
  244. process.execPath,
  245. [
  246. "-e",
  247. `
  248. const { spawn } = require("node:child_process");
  249. const descendant = spawn(
  250. process.execPath,
  251. ["-e", 'process.send?.("ready"); setInterval(() => {}, 1000);'],
  252. { stdio: ["ignore", "ignore", "ignore", "ipc"] },
  253. );
  254. descendant.once("message", () => {
  255. const frame = JSON.stringify({ method: "state.updated", params: { pid: descendant.pid } }) + "\\n";
  256. process.stdout.write(frame, () => process.exit(1));
  257. });
  258. `,
  259. ],
  260. { stdio: ["pipe", "pipe", "pipe"], windowsHide: true },
  261. );
  262. activeChildren.add(child);
  263. const transport = new ZCodeStdioTransport(child, {
  264. ownedProcessStartedAtMs: spawnRequestedAt,
  265. });
  266. const descendantPidPromise = new Promise<number>((resolve) => {
  267. transport.onMessage((message) => {
  268. if (!("method" in message) || message.method !== "state.updated") return;
  269. const pid = (message.params as { pid?: unknown } | undefined)?.pid;
  270. if (typeof pid === "number") resolve(pid);
  271. });
  272. });
  273. const descendantPid = await descendantPidPromise;
  274. await waitForExit(child);
  275. try {
  276. // 修复原因:Windows 没有 POSIX PGID;root 先退出时不能重新 taskkill 裸 root。
  277. // cleanup 只沿 Win32_Process 保留的 ParentProcessId 找回成员,并用 CreationDate
  278. // 固定 descendant 身份,确保 app quit 仍能回收原 task tree。
  279. await transport.disposeAndWait();
  280. expect(isPidRunning(descendantPid)).toBe(false);
  281. } finally {
  282. if (isPidRunning(descendantPid)) process.kill(descendantPid, "SIGKILL");
  283. }
  284. activeChildren.delete(child);
  285. },
  286. );
  287. it("高频 telemetry 保持实时有序分发且应用退出后仍回收 Agent", async () => {
  288. const frameCount = 300;
  289. const child = spawn(
  290. process.execPath,
  291. [
  292. "-e",
  293. `
  294. const frames = Array.from({ length: ${frameCount} }, (_, index) => ({
  295. method: "v4/telemetry/event",
  296. params: { index, pid: process.pid },
  297. }));
  298. process.stdout.write(frames.map((frame) => JSON.stringify(frame)).join("\\n") + "\\n");
  299. process.stdin.resume();
  300. process.stdin.once("end", () => process.exit(0));
  301. setInterval(() => {}, 1000);
  302. `,
  303. ],
  304. { stdio: ["pipe", "pipe", "pipe"], windowsHide: true },
  305. );
  306. activeChildren.add(child);
  307. const transport = new ZCodeStdioTransport(child);
  308. let firstFrameAt = 0;
  309. let receivedFrameCount = 0;
  310. let agentPid = 0;
  311. const receivedIndexes: number[] = [];
  312. const allFramesPromise = new Promise<void>((resolve) => {
  313. transport.onMessage((message) => {
  314. if (!("method" in message) || message.method !== "v4/telemetry/event") return;
  315. const params = message.params as { index?: unknown; pid?: unknown } | undefined;
  316. if (firstFrameAt === 0) firstFrameAt = Date.now();
  317. if (typeof params?.pid === "number") agentPid = params.pid;
  318. if (typeof params?.index === "number") receivedIndexes.push(params.index);
  319. receivedFrameCount += 1;
  320. if (receivedFrameCount === frameCount) resolve();
  321. });
  322. });
  323. await allFramesPromise;
  324. try {
  325. // 修复原因:进程清理曾在每条 telemetry 前同步 spawnSync("ps"),300 条消息
  326. // 会阻塞 Host 数秒并让 subagent 面板空白。运行期帧必须直接交付;完整树扫描
  327. // 只允许在 disposeAndWait 已进入退出阶段后执行。
  328. expect(Date.now() - firstFrameAt).toBeLessThan(750);
  329. expect(receivedIndexes).toEqual(Array.from({ length: frameCount }, (_, index) => index));
  330. expect(isPidRunning(agentPid)).toBe(true);
  331. await transport.disposeAndWait();
  332. expect(isPidRunning(agentPid)).toBe(false);
  333. } finally {
  334. if (isPidRunning(agentPid)) {
  335. process.kill(process.platform === "win32" ? agentPid : -agentPid, "SIGKILL");
  336. }
  337. }
  338. activeChildren.delete(child);
  339. }, 15_000);
  340. it("agent 退出后会把 transport 视为关闭", async () => {
  341. const child = spawn(process.execPath, ["-e", "setTimeout(() => process.exit(0), 10);"], {
  342. stdio: ["pipe", "pipe", "pipe"],
  343. windowsHide: true,
  344. });
  345. activeChildren.add(child);
  346. const transport = new ZCodeStdioTransport(child);
  347. await new Promise<void>((resolve) => child.once("exit", () => resolve()));
  348. await expect(
  349. transport.send({
  350. type: "zcode-hello-ack",
  351. version: 1,
  352. clientId: "test",
  353. } as never),
  354. ).rejects.toThrow("ZCode agent stdio transport is closed");
  355. activeChildren.delete(child);
  356. });
  357. it("按 LF 分帧时允许 JSON 字符串包含 Unicode 行分隔符", async () => {
  358. const frame = Buffer.from(
  359. `{"method":"session/event","params":{"text":"before\u2028middle\u2029after"}}\n`,
  360. "utf8",
  361. ).toString("base64");
  362. const child = spawn(
  363. process.execPath,
  364. [
  365. "-e",
  366. `
  367. const frame = Buffer.from("${frame}", "base64");
  368. process.stdout.write(frame, () => setTimeout(() => process.exit(0), 10));
  369. `,
  370. ],
  371. {
  372. stdio: ["pipe", "pipe", "pipe"],
  373. windowsHide: true,
  374. },
  375. );
  376. activeChildren.add(child);
  377. const transport = new ZCodeStdioTransport(child);
  378. let closeReason: string | undefined;
  379. transport.onClose((event) => {
  380. closeReason = event.reason;
  381. });
  382. const messagePromise = new Promise((resolve) => {
  383. transport.onMessage((message) => resolve(message));
  384. });
  385. await expect(messagePromise).resolves.toEqual({
  386. method: "session/event",
  387. params: {
  388. text: "before\u2028middle\u2029after",
  389. },
  390. });
  391. await waitForExit(child);
  392. expect(closeReason ?? "").not.toContain("protocol_parse_error");
  393. activeChildren.delete(child);
  394. });
  395. });
  396. // 用 PassThrough 模拟 child 的 stdio,便于精确控制 stdout 分块边界。
  397. function createFakeChild() {
  398. const child = Object.assign(new EventEmitter(), {
  399. stdin: new PassThrough(),
  400. stdout: new PassThrough(),
  401. stderr: new PassThrough(),
  402. killed: false,
  403. pid: undefined,
  404. exitCode: null,
  405. signalCode: null,
  406. });
  407. return child as unknown as ChildProcessWithoutNullStreams & {
  408. stdout: PassThrough;
  409. stderr: PassThrough;
  410. };
  411. }
  412. function writeInChunks(stream: PassThrough, bytes: Buffer, chunkBytes: number): void {
  413. for (let offset = 0; offset < bytes.length; offset += chunkBytes) {
  414. stream.write(bytes.subarray(offset, offset + chunkBytes));
  415. }
  416. }
  417. describe("ZCodeStdioTransport stdout 分帧", () => {
  418. it("跨 chunk 的超大多字节帧、同 chunk 多帧与 EOF 尾帧按序完整交付", async () => {
  419. const child = createFakeChild();
  420. const transport = new ZCodeStdioTransport(child);
  421. const messages: unknown[] = [];
  422. transport.onMessage((message) => messages.push(message));
  423. const closed = new Promise<string | undefined>((resolve) => {
  424. transport.onClose((event) => resolve(event.reason));
  425. });
  426. const big = { method: "session/event", params: { text: "中文🙂\u2028".repeat(40_000) } };
  427. const small = [1, 2, 3].map((n) => ({ id: `small-${n}`, result: { n } }));
  428. const tail = { id: "tail", result: {} };
  429. const bytes = Buffer.from(
  430. `${JSON.stringify(small[0])}\n${JSON.stringify(big)}\r\n${JSON.stringify(small[1])}\n\n${JSON.stringify(small[2])}\n${JSON.stringify(tail)}`,
  431. "utf8",
  432. );
  433. // 7 字节的奇数分块会切开 UTF-8 多字节序列与 CRLF。
  434. writeInChunks(child.stdout, bytes, 7);
  435. child.stdout.end();
  436. await expect(closed).resolves.toBe("stdout_closed");
  437. expect(messages).toEqual([small[0], big, small[1], small[2], tail]);
  438. });
  439. it("超大单行按小块到达时换行扫描量保持线性", async () => {
  440. const child = createFakeChild();
  441. const transport = new ZCodeStdioTransport(child);
  442. const received = new Promise((resolve) => transport.onMessage(resolve));
  443. const line = Buffer.from(
  444. `${JSON.stringify({ method: "session/event", params: { text: "x".repeat(4 << 20) } })}\n`,
  445. "utf8",
  446. );
  447. // Bug 原因:旧实现每个 chunk 都对累积 buffer 整体 indexOf("\n"),V8 需把 cons string
  448. // 整体拍平,15MB 的 session/read 响应按 64KB 到达时每轮分配数 GB(host CPU 100%)。
  449. // 这里统计对 "\n" 的扫描字符数,线性实现应与帧长同量级。
  450. let scannedChars = 0;
  451. const originalIndexOf = String.prototype.indexOf;
  452. String.prototype.indexOf = function (this: string, search: string, position?: number) {
  453. if (search === "\n") scannedChars += this.length - (position ?? 0);
  454. return originalIndexOf.call(this, search, position);
  455. };
  456. try {
  457. writeInChunks(child.stdout, line, 4096);
  458. await received;
  459. } finally {
  460. String.prototype.indexOf = originalIndexOf;
  461. }
  462. expect(scannedChars).toBeLessThan(line.length * 2);
  463. child.stdout.end();
  464. });
  465. });