zcodeStdioTransport.test.ts 18 KB

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