zcode-protocol-transport.test.ts 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767
  1. import { PassThrough } from "node:stream";
  2. import { describe, expect, it, vi } from "vitest";
  3. import { zcodeProtocolMethods, type ZCodeProtocolMessage } from "@zcode/shared";
  4. import { ZCodeProtocolNdjsonConnection } from "../src/zcode-protocol/transport.js";
  5. describe("ZCodeProtocolNdjsonConnection", () => {
  6. it("stdout 背压时丢弃观测批次,业务响应仍可写入", () => {
  7. const output = new PassThrough({ highWaterMark: 1 });
  8. const connection = new ZCodeProtocolNdjsonConnection({
  9. input: new PassThrough(),
  10. output,
  11. handleMessage: async () => undefined,
  12. });
  13. output.write("x".repeat(256 * 1024));
  14. const before = output.writableLength;
  15. connection.send({
  16. method: "process/networkRequests",
  17. params: { captureId: "one", records: [], dropped: 0 },
  18. });
  19. expect(output.writableLength).toBe(before);
  20. connection.send({ id: 1, result: {} });
  21. expect(output.writableLength).toBeGreaterThan(before);
  22. output.destroy();
  23. });
  24. it("网络观测控制不等待挂起业务请求,并保留启停顺序", async () => {
  25. const input = new PassThrough();
  26. const output = new PassThrough();
  27. const controls: unknown[] = [];
  28. const connection = new ZCodeProtocolNdjsonConnection({
  29. input,
  30. output,
  31. handleMessage: async (message) => {
  32. if ("method" in message && message.method === "process/networkCapture") {
  33. controls.push(message.params);
  34. return undefined;
  35. }
  36. return new Promise(() => {});
  37. },
  38. });
  39. connection.start();
  40. input.write(frame({ id: "busy", method: "workspace/readState" }));
  41. input.write(frame({ method: "process/networkCapture", params: { captureId: "one" } }));
  42. input.write(frame({ method: "process/networkCapture", params: { captureId: null } }));
  43. await vi.waitFor(() => expect(controls).toEqual([{ captureId: "one" }, { captureId: null }]));
  44. input.end();
  45. await connection.waitForClose();
  46. });
  47. it("bounds EOF drain even while a handler never settles", async () => {
  48. const input = new PassThrough();
  49. const output = new PassThrough();
  50. const closed = vi.fn();
  51. const connection = new ZCodeProtocolNdjsonConnection({
  52. input,
  53. output,
  54. handleMessage: () => new Promise(() => {}),
  55. onTransportClosed: closed,
  56. });
  57. connection.start();
  58. input.end(frame({ id: "hung", method: "workspace/readState", params: {} }));
  59. await connection.waitForClose();
  60. expect(closed).toHaveBeenCalledTimes(1);
  61. expect(input.listenerCount("data")).toBe(0);
  62. }, 1_000);
  63. it("writes response, every physical notification, then commits the reservation", async () => {
  64. const input = new PassThrough();
  65. const output = new PassThrough();
  66. const order: string[] = [];
  67. output.on("data", (chunk: Buffer) => {
  68. const value = JSON.parse(chunk.toString("utf8")) as {
  69. id?: string;
  70. params?: { fragmentIndex?: number };
  71. };
  72. order.push(value.id ? "response" : `wire-${value.params?.fragmentIndex}`);
  73. });
  74. const connection = new ZCodeProtocolNdjsonConnection({
  75. handleMessage: async (message) =>
  76. "id" in message && "method" in message
  77. ? { id: message.id, result: { ack: {} } }
  78. : undefined,
  79. input,
  80. output,
  81. takePostResponseBatch: () => ({
  82. messages: [0, 1].map((fragmentIndex) => ({
  83. method: "v4/conversation/frame",
  84. params: { kind: "fragment", fragmentIndex },
  85. })),
  86. commit: () => {
  87. order.push("commit");
  88. return true;
  89. },
  90. }),
  91. });
  92. connection.start();
  93. input.end(frame({ id: "physical-order", method: "v4/conversation/subscribe", params: {} }));
  94. await connection.waitForClose();
  95. expect(order).toEqual(["response", "wire-0", "wire-1", "commit"]);
  96. });
  97. it("does not commit when a physical notification write throws", async () => {
  98. const input = new PassThrough();
  99. const output = new PassThrough();
  100. const originalWrite = output.write.bind(output);
  101. let writes = 0;
  102. output.write = ((chunk: string | Uint8Array) => {
  103. writes += 1;
  104. if (writes === 3) throw new Error("physical write failed");
  105. return originalWrite(chunk);
  106. }) as typeof output.write;
  107. const commit = vi.fn(() => true);
  108. const connection = new ZCodeProtocolNdjsonConnection({
  109. handleMessage: async (message) =>
  110. "id" in message && "method" in message
  111. ? { id: message.id, result: { ack: {} } }
  112. : undefined,
  113. input,
  114. output,
  115. takePostResponseBatch: () => ({
  116. messages: [
  117. { method: "v4/conversation/frame", params: { fragmentIndex: 0 } },
  118. { method: "v4/conversation/frame", params: { fragmentIndex: 1 } },
  119. ],
  120. commit,
  121. }),
  122. });
  123. connection.start();
  124. input.end(frame({ id: "physical-fail", method: "v4/conversation/subscribe", params: {} }));
  125. await expect(connection.waitForClose()).rejects.toThrow("physical write failed");
  126. expect(commit).not.toHaveBeenCalled();
  127. });
  128. it("commits after queue admission, then async EPIPE terminalizes the connection epoch", async () => {
  129. const input = new PassThrough();
  130. const output = new PassThrough();
  131. let written = "";
  132. output.on("data", (chunk: Buffer) => {
  133. written += chunk.toString("utf8");
  134. });
  135. const commit = vi.fn(() => true);
  136. const clearPostResponseMessages = vi.fn();
  137. const takePostResponseBatch = vi.fn(() => ({
  138. messages: [{ method: "v4/conversation/frame", params: { kind: "complete" } }],
  139. commit,
  140. }));
  141. const connection = new ZCodeProtocolNdjsonConnection({
  142. clearPostResponseMessages,
  143. handleMessage: async (message) =>
  144. "id" in message && "method" in message
  145. ? { id: message.id, result: { ack: { subscriptionId: "sub-epoch" } } }
  146. : undefined,
  147. input,
  148. output,
  149. takePostResponseBatch,
  150. });
  151. connection.start();
  152. input.write(frame({ id: "async-epipe", method: "v4/conversation/subscribe", params: {} }));
  153. await vi.waitFor(() => expect(commit).toHaveBeenCalledTimes(1));
  154. const acceptedBytes = written;
  155. output.emit("error", new Error("async write EPIPE"));
  156. await expect(connection.waitForClose()).rejects.toThrow("async write EPIPE");
  157. connection.send({ method: "v4/conversation/frame", params: { shouldNotWrite: true } });
  158. input.write(
  159. frame({ id: "new-epoch-required", method: "v4/conversation/subscribe", params: {} }),
  160. );
  161. await new Promise((resolve) => setImmediate(resolve));
  162. expect(written).toBe(acceptedBytes);
  163. expect(takePostResponseBatch).toHaveBeenCalledTimes(1);
  164. expect(clearPostResponseMessages).toHaveBeenCalledTimes(1);
  165. input.destroy();
  166. });
  167. it("writes the response before request-scoped initial notifications from one input chunk", async () => {
  168. const input = new PassThrough();
  169. const output = new PassThrough();
  170. let written = "";
  171. output.on("data", (chunk: Buffer) => {
  172. written += chunk.toString("utf8");
  173. });
  174. const connection = new ZCodeProtocolNdjsonConnection({
  175. handleMessage: async (message) => {
  176. if (!("id" in message) || !("method" in message)) return undefined;
  177. return {
  178. id: message.id,
  179. result: {
  180. ack: { subscriptionId: "sub-1", mode: "snapshot", logEpoch: "epoch-1" },
  181. },
  182. };
  183. },
  184. input,
  185. output,
  186. takePostResponseMessages: (requestId) =>
  187. requestId === "subscribe-1"
  188. ? [
  189. {
  190. method: "v4/conversation/frame",
  191. params: {
  192. topic: "conversation/session-1",
  193. subscriptionId: "sub-1",
  194. fromSeq: 0,
  195. toSeq: 0,
  196. sentAt: 1,
  197. payload: { kind: "deltas", deltas: [] },
  198. },
  199. },
  200. ]
  201. : [],
  202. });
  203. connection.start();
  204. input.end(
  205. frame({
  206. id: "subscribe-1",
  207. method: "v4/conversation/subscribe",
  208. params: { topic: "conversation/session-1" },
  209. }),
  210. );
  211. await connection.waitForClose();
  212. const lines = written
  213. .trim()
  214. .split("\n")
  215. .map((line) => JSON.parse(line) as Record<string, unknown>);
  216. expect(lines).toEqual([
  217. {
  218. id: "subscribe-1",
  219. result: {
  220. ack: { subscriptionId: "sub-1", mode: "snapshot", logEpoch: "epoch-1" },
  221. },
  222. },
  223. {
  224. method: "v4/conversation/frame",
  225. params: expect.objectContaining({
  226. topic: "conversation/session-1",
  227. subscriptionId: "sub-1",
  228. }),
  229. },
  230. ]);
  231. });
  232. it("writes only the response line when a subscribe has no initial frame", async () => {
  233. const input = new PassThrough();
  234. const output = new PassThrough();
  235. let written = "";
  236. output.on("data", (chunk: Buffer) => {
  237. written += chunk.toString("utf8");
  238. });
  239. const connection = new ZCodeProtocolNdjsonConnection({
  240. handleMessage: async (message) =>
  241. "id" in message && "method" in message
  242. ? {
  243. id: message.id,
  244. result: {
  245. ack: { subscriptionId: "sub-2", mode: "resume", logEpoch: "epoch-1" },
  246. },
  247. }
  248. : undefined,
  249. input,
  250. output,
  251. takePostResponseMessages: () => [],
  252. });
  253. connection.start();
  254. input.end(
  255. frame({
  256. id: "subscribe-2",
  257. method: "v4/conversation/subscribe",
  258. params: { topic: "conversation/session-1" },
  259. }),
  260. );
  261. await connection.waitForClose();
  262. expect(written.trim().split("\n")).toHaveLength(1);
  263. expect(JSON.parse(written.trim())).toEqual({
  264. id: "subscribe-2",
  265. result: {
  266. ack: { subscriptionId: "sub-2", mode: "resume", logEpoch: "epoch-1" },
  267. },
  268. });
  269. });
  270. it("clears post-response messages when queued request processing rejects", async () => {
  271. const input = new PassThrough();
  272. const output = new PassThrough();
  273. const clearPostResponseMessages = vi.fn();
  274. const connection = new ZCodeProtocolNdjsonConnection({
  275. clearPostResponseMessages,
  276. handleMessage: async () => {
  277. throw new Error("request failed");
  278. },
  279. input,
  280. output,
  281. });
  282. connection.start();
  283. input.end(
  284. frame({
  285. id: "request-failure",
  286. method: "v4/conversation/subscribe",
  287. params: { topic: "conversation/session-1" },
  288. }),
  289. );
  290. await expect(connection.waitForClose()).rejects.toThrow("request failed");
  291. expect(clearPostResponseMessages).toHaveBeenCalledTimes(1);
  292. });
  293. it("clears post-response messages when a bypassed handler rejects", async () => {
  294. const input = new PassThrough();
  295. const output = new PassThrough();
  296. const clearPostResponseMessages = vi.fn();
  297. const connection = new ZCodeProtocolNdjsonConnection({
  298. clearPostResponseMessages,
  299. handleMessage: async () => {
  300. throw new Error("bypass failed");
  301. },
  302. input,
  303. output,
  304. });
  305. connection.start();
  306. input.write(frame({ id: "server-1", result: {} }));
  307. await expect(connection.waitForClose()).rejects.toThrow("bypass failed");
  308. expect(clearPostResponseMessages).toHaveBeenCalledTimes(1);
  309. });
  310. it("clears on output EPIPE and discards an in-flight subscribe outbox that completes late", async () => {
  311. const input = new PassThrough();
  312. const output = new PassThrough();
  313. const clearPostResponseMessages = vi.fn();
  314. const takePostResponseMessages = vi.fn(() => [
  315. {
  316. method: "v4/conversation/frame",
  317. params: { subscriptionId: "sub-late" },
  318. },
  319. ]);
  320. let resolveStarted!: () => void;
  321. const started = new Promise<void>((resolve) => {
  322. resolveStarted = resolve;
  323. });
  324. let resolveResponse!: (value: {
  325. id: string;
  326. result: { ack: { subscriptionId: string; mode: "snapshot"; logEpoch: string } };
  327. }) => void;
  328. const response = new Promise<{
  329. id: string;
  330. result: { ack: { subscriptionId: string; mode: "snapshot"; logEpoch: string } };
  331. }>((resolve) => {
  332. resolveResponse = resolve;
  333. });
  334. let written = "";
  335. output.on("data", (chunk: Buffer) => {
  336. written += chunk.toString("utf8");
  337. });
  338. const connection = new ZCodeProtocolNdjsonConnection({
  339. clearPostResponseMessages,
  340. handleMessage: async () => {
  341. resolveStarted();
  342. return await response;
  343. },
  344. input,
  345. output,
  346. takePostResponseMessages,
  347. });
  348. connection.start();
  349. input.write(
  350. frame({
  351. id: "subscribe-late",
  352. method: "v4/conversation/subscribe",
  353. params: { topic: "conversation/session-1" },
  354. }),
  355. );
  356. await started;
  357. const closed = connection.waitForClose().then(
  358. () => null,
  359. (error: Error) => error,
  360. );
  361. output.emit("error", new Error("write EPIPE"));
  362. expect((await closed)?.message).toBe("write EPIPE");
  363. expect(clearPostResponseMessages).toHaveBeenCalledTimes(1);
  364. resolveResponse({
  365. id: "subscribe-late",
  366. result: {
  367. ack: { subscriptionId: "sub-late", mode: "snapshot", logEpoch: "epoch-1" },
  368. },
  369. });
  370. await vi.waitFor(() => expect(takePostResponseMessages).toHaveBeenCalledWith("subscribe-late"));
  371. expect(written).toBe("");
  372. input.destroy();
  373. });
  374. it("lets session/stop bypass a long-running request in the serial queue", async () => {
  375. const input = new PassThrough();
  376. const output = new PassThrough();
  377. const handledMethods: string[] = [];
  378. const responses: unknown[] = [];
  379. let resolveStopHandled!: () => void;
  380. const stopHandled = new Promise<void>((resolve) => {
  381. resolveStopHandled = resolve;
  382. });
  383. output.on("data", (chunk: Buffer) => {
  384. for (const line of chunk.toString("utf8").trim().split("\n")) {
  385. if (line) {
  386. responses.push(JSON.parse(line));
  387. }
  388. }
  389. });
  390. const connection = new ZCodeProtocolNdjsonConnection({
  391. handleMessage: async (message) => {
  392. if (!("method" in message)) {
  393. return undefined;
  394. }
  395. handledMethods.push(message.method);
  396. if (message.method === zcodeProtocolMethods.sessionCompact) {
  397. return await new Promise<never>(() => undefined);
  398. }
  399. if (message.method === zcodeProtocolMethods.sessionStop && "id" in message) {
  400. resolveStopHandled();
  401. return { id: message.id, result: {} };
  402. }
  403. return undefined;
  404. },
  405. input,
  406. output,
  407. });
  408. connection.start();
  409. input.write(
  410. [
  411. frame({
  412. id: 1,
  413. method: zcodeProtocolMethods.sessionCompact,
  414. params: { sessionId: "sess_1" },
  415. }),
  416. frame({
  417. id: 2,
  418. method: zcodeProtocolMethods.sessionStop,
  419. params: { sessionId: "sess_1" },
  420. }),
  421. ].join(""),
  422. );
  423. const stopResult = await Promise.race([
  424. stopHandled.then(() => "handled" as const),
  425. new Promise<"blocked">((resolve) => setTimeout(() => resolve("blocked"), 30)),
  426. ]);
  427. expect(stopResult).toBe("handled");
  428. expect(handledMethods).toEqual([
  429. zcodeProtocolMethods.sessionCompact,
  430. zcodeProtocolMethods.sessionStop,
  431. ]);
  432. await vi.waitFor(() => {
  433. expect(responses).toContainEqual({ id: 2, result: {} });
  434. });
  435. });
  436. it("lets workspace cancellation abort an active model request before the serial queue advances", async () => {
  437. const input = new PassThrough();
  438. const output = new PassThrough();
  439. const responses: unknown[] = [];
  440. let releaseGenerate!: () => void;
  441. const generateReleased = new Promise<void>((resolve) => {
  442. releaseGenerate = resolve;
  443. });
  444. let resolveCancelHandled!: () => void;
  445. const cancelHandled = new Promise<void>((resolve) => {
  446. resolveCancelHandled = resolve;
  447. });
  448. let generateActive = false;
  449. let generateCount = 0;
  450. let activeGenerateCount = 0;
  451. let maxActiveGenerateCount = 0;
  452. let cancelSawActiveGenerate = false;
  453. output.on("data", (chunk: Buffer) => {
  454. for (const line of chunk.toString("utf8").trim().split("\n")) {
  455. if (line) {
  456. responses.push(JSON.parse(line));
  457. }
  458. }
  459. });
  460. const connection = new ZCodeProtocolNdjsonConnection({
  461. handleMessage: async (message) => {
  462. if (!("method" in message) || !("id" in message)) {
  463. return undefined;
  464. }
  465. if (message.method === zcodeProtocolMethods.workspaceGenerateText) {
  466. generateCount += 1;
  467. generateActive = true;
  468. activeGenerateCount += 1;
  469. maxActiveGenerateCount = Math.max(maxActiveGenerateCount, activeGenerateCount);
  470. if (generateCount === 1) {
  471. await generateReleased;
  472. }
  473. activeGenerateCount -= 1;
  474. generateActive = false;
  475. return { id: message.id, result: { text: `generate-${generateCount}` } };
  476. }
  477. if (message.method === zcodeProtocolMethods.workspaceCancelGenerateText) {
  478. cancelSawActiveGenerate = generateActive;
  479. releaseGenerate();
  480. resolveCancelHandled();
  481. return {
  482. id: message.id,
  483. result: { operationId: "workspace-model-1", cancelled: true },
  484. };
  485. }
  486. return { id: message.id, result: {} };
  487. },
  488. input,
  489. output,
  490. });
  491. connection.start();
  492. input.write(
  493. [
  494. frame({
  495. id: 1,
  496. method: zcodeProtocolMethods.workspaceGenerateText,
  497. params: {
  498. operationId: "workspace-model-1",
  499. workspace: { workspaceKey: "/workspace/app", workspacePath: "/workspace/app" },
  500. },
  501. }),
  502. frame({
  503. id: 2,
  504. method: zcodeProtocolMethods.workspaceCancelGenerateText,
  505. params: { operationId: "workspace-model-1" },
  506. }),
  507. frame({
  508. id: 3,
  509. method: zcodeProtocolMethods.workspaceGenerateText,
  510. params: {
  511. operationId: "workspace-model-2",
  512. workspace: { workspaceKey: "/workspace/app", workspacePath: "/workspace/app" },
  513. },
  514. }),
  515. ].join(""),
  516. );
  517. const cancelResult = await Promise.race([
  518. cancelHandled.then(() => "handled" as const),
  519. new Promise<"blocked">((resolve) => setTimeout(() => resolve("blocked"), 100)),
  520. ]);
  521. expect(cancelResult).toBe("handled");
  522. expect(cancelSawActiveGenerate).toBe(true);
  523. input.end();
  524. await connection.waitForClose();
  525. expect(generateCount).toBe(2);
  526. expect(maxActiveGenerateCount).toBe(1);
  527. expect(responses).toContainEqual({
  528. id: 2,
  529. result: { operationId: "workspace-model-1", cancelled: true },
  530. });
  531. expect(responses).toContainEqual({ id: 3, result: { text: "generate-2" } });
  532. });
  533. it("lets protocol responses bypass a long-running request with later requests queued", async () => {
  534. const input = new PassThrough();
  535. const output = new PassThrough();
  536. const handled: unknown[] = [];
  537. let resolveResponseHandled!: () => void;
  538. const responseHandled = new Promise<void>((resolve) => {
  539. resolveResponseHandled = resolve;
  540. });
  541. const connection = new ZCodeProtocolNdjsonConnection({
  542. handleMessage: async (message) => {
  543. handled.push(message);
  544. if ("method" in message && message.method === zcodeProtocolMethods.sessionCompact) {
  545. return await new Promise<never>(() => undefined);
  546. }
  547. if ("result" in message && "id" in message) {
  548. resolveResponseHandled();
  549. }
  550. return undefined;
  551. },
  552. input,
  553. output,
  554. });
  555. connection.start();
  556. input.write(
  557. [
  558. frame({
  559. id: 1,
  560. method: zcodeProtocolMethods.sessionCompact,
  561. params: { sessionId: "sess_1" },
  562. }),
  563. frame({
  564. id: 2,
  565. method: zcodeProtocolMethods.sessionRead,
  566. params: { sessionId: "sess_1" },
  567. }),
  568. frame({
  569. id: "server-1",
  570. result: { headersApplied: true },
  571. }),
  572. ].join(""),
  573. );
  574. const responseResult = await Promise.race([
  575. responseHandled.then(() => "handled" as const),
  576. new Promise<"blocked">((resolve) => setTimeout(() => resolve("blocked"), 30)),
  577. ]);
  578. expect(responseResult).toBe("handled");
  579. expect(handled).toHaveLength(2);
  580. });
  581. it("waits for a queued session/send to start before handling session/stop", async () => {
  582. const input = new PassThrough();
  583. const output = new PassThrough();
  584. let releaseCompact!: () => void;
  585. const compactReleased = new Promise<void>((resolve) => {
  586. releaseCompact = resolve;
  587. });
  588. let releaseSend!: () => void;
  589. const sendReleased = new Promise<void>((resolve) => {
  590. releaseSend = resolve;
  591. });
  592. let resolveStopHandled!: () => void;
  593. const stopHandled = new Promise<void>((resolve) => {
  594. resolveStopHandled = resolve;
  595. });
  596. let sendActive = false;
  597. let stopSawActiveSend = false;
  598. const connection = new ZCodeProtocolNdjsonConnection({
  599. handleMessage: async (message) => {
  600. if (!("method" in message)) {
  601. return undefined;
  602. }
  603. if (message.method === zcodeProtocolMethods.sessionCompact) {
  604. await compactReleased;
  605. }
  606. if (message.method === zcodeProtocolMethods.sessionSend) {
  607. sendActive = true;
  608. await sendReleased;
  609. sendActive = false;
  610. }
  611. if (message.method === zcodeProtocolMethods.sessionStop) {
  612. stopSawActiveSend = sendActive;
  613. releaseSend();
  614. resolveStopHandled();
  615. }
  616. return "id" in message ? { id: message.id, result: {} } : undefined;
  617. },
  618. input,
  619. output,
  620. });
  621. connection.start();
  622. input.write(
  623. [
  624. frame({
  625. id: 1,
  626. method: zcodeProtocolMethods.sessionCompact,
  627. params: { sessionId: "sess_blocking" },
  628. }),
  629. frame({
  630. id: 2,
  631. method: zcodeProtocolMethods.sessionSend,
  632. params: { sessionId: "sess_target", inputId: "input_target", content: "run" },
  633. }),
  634. frame({
  635. id: 3,
  636. method: zcodeProtocolMethods.sessionStop,
  637. params: { sessionId: "sess_target" },
  638. }),
  639. ].join(""),
  640. );
  641. await new Promise<void>((resolve) => setImmediate(resolve));
  642. expect(stopSawActiveSend).toBe(false);
  643. releaseCompact();
  644. await stopHandled;
  645. expect(stopSawActiveSend).toBe(true);
  646. input.end();
  647. await connection.waitForClose();
  648. });
  649. // M5 收口:prompt/enhance 全簇删除后,请求方法级 bypass 名单只剩 session/stop;
  650. // 本用例保住「长请求占住串行队列时 stop 仍可进入 server」这一传输层语义。
  651. it("lets session/stop bypass a long-running request in the serial queue", async () => {
  652. const input = new PassThrough();
  653. const output = new PassThrough();
  654. const responses: unknown[] = [];
  655. let resolveStopHandled!: () => void;
  656. const stopHandled = new Promise<void>((resolve) => {
  657. resolveStopHandled = resolve;
  658. });
  659. output.on("data", (chunk: Buffer) => {
  660. for (const line of chunk.toString("utf8").trim().split("\n")) {
  661. if (line) {
  662. responses.push(JSON.parse(line));
  663. }
  664. }
  665. });
  666. const connection = new ZCodeProtocolNdjsonConnection({
  667. handleMessage: async (message) => {
  668. if (!("method" in message)) {
  669. return undefined;
  670. }
  671. if (message.method === zcodeProtocolMethods.sessionCompact) {
  672. return await new Promise<never>(() => undefined);
  673. }
  674. if (message.method === zcodeProtocolMethods.sessionStop && "id" in message) {
  675. resolveStopHandled();
  676. return {
  677. id: message.id,
  678. result: {},
  679. };
  680. }
  681. return undefined;
  682. },
  683. input,
  684. output,
  685. });
  686. connection.start();
  687. input.write(
  688. [
  689. frame({
  690. id: 1,
  691. method: zcodeProtocolMethods.sessionCompact,
  692. params: { sessionId: "sess_1" },
  693. }),
  694. frame({
  695. id: 2,
  696. method: zcodeProtocolMethods.sessionStop,
  697. params: { sessionId: "sess_1" },
  698. }),
  699. ].join(""),
  700. );
  701. const stopResult = await Promise.race([
  702. stopHandled.then(() => "handled" as const),
  703. new Promise<"blocked">((resolve) => setTimeout(() => resolve("blocked"), 30)),
  704. ]);
  705. expect(stopResult).toBe("handled");
  706. await vi.waitFor(() => {
  707. expect(responses).toContainEqual({
  708. id: 2,
  709. result: {},
  710. });
  711. });
  712. });
  713. });
  714. function frame(message: ZCodeProtocolMessage): string {
  715. return `${JSON.stringify(message)}\n`;
  716. }