taskRealtimeBus.test.ts 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798
  1. import { EventEmitter } from "node:events";
  2. import type { UtilityProcess as ElectronUtilityProcess } from "electron";
  3. import { describe, expect, it, vi } from "vitest";
  4. import { HostMessageTypes, HostResponseTypes } from "@zcode/shared";
  5. import { TaskRealtimeBus } from "../src/main/taskRealtimeBus.js";
  6. class FakeHostProcess extends EventEmitter {
  7. readonly postedMessages: unknown[] = [];
  8. postMessage(message: unknown): void {
  9. this.postedMessages.push(message);
  10. }
  11. emitMessage(message: unknown): void {
  12. this.emit("message", message);
  13. }
  14. emitExit(): void {
  15. this.emit("exit", 0);
  16. }
  17. }
  18. function asUtilityProcess(process: FakeHostProcess): ElectronUtilityProcess {
  19. return process as unknown as ElectronUtilityProcess;
  20. }
  21. function makeLogger() {
  22. return {
  23. info: vi.fn(),
  24. warn: vi.fn(),
  25. };
  26. }
  27. function makePublish(overrides: Record<string, unknown> = {}) {
  28. return {
  29. type: HostResponseTypes.TaskRealtimePublish,
  30. event: {
  31. type: "task_snapshot_invalidated",
  32. eventId: "evt-1",
  33. workspacePath: "/repo/demo",
  34. workspaceKey: "/repo/demo",
  35. reason: "user_message_saved",
  36. traceId: "trace-1",
  37. createdAt: 1,
  38. taskId: "task-1",
  39. ...overrides,
  40. },
  41. };
  42. }
  43. function makeSessionRouteAnnounce(overrides: Record<string, unknown> = {}) {
  44. return {
  45. type: HostResponseTypes.SessionRouteAnnounce,
  46. route: {
  47. sessionId: "session-target",
  48. ...overrides,
  49. },
  50. };
  51. }
  52. function makeSessionMessageRequest(overrides: Record<string, unknown> = {}) {
  53. return {
  54. content: "继续成语接龙:一心一意",
  55. createdAt: "2026-05-21T00:00:00.000Z",
  56. fromSessionId: "session-source",
  57. messageId: "msg-1",
  58. requestId: "req-1",
  59. toSessionId: "session-target",
  60. ...overrides,
  61. };
  62. }
  63. function makeLeaseRequest(leaseRequestId = "lease-1", overrides: Record<string, unknown> = {}) {
  64. return {
  65. type: HostResponseTypes.TaskRunLeaseAcquire,
  66. request: {
  67. leaseRequestId,
  68. workspacePath: "/repo/demo",
  69. workspaceKey: "/repo/demo",
  70. taskId: "task-1",
  71. runId: "trace-1",
  72. traceId: "trace-1",
  73. ...overrides,
  74. },
  75. };
  76. }
  77. function makeStreamTarget(overrides: Record<string, unknown> = {}) {
  78. return {
  79. workspacePath: "/repo/demo",
  80. workspaceKey: "/repo/demo",
  81. taskId: "task-1",
  82. runId: "trace-1",
  83. traceId: "trace-1",
  84. ...overrides,
  85. };
  86. }
  87. function makeChunk(content: string) {
  88. return {
  89. type: HostResponseTypes.TaskStreamOpPublish,
  90. target: makeStreamTarget(),
  91. op: {
  92. kind: "stream_event",
  93. event: {
  94. type: "agent_message_chunk",
  95. taskId: "task-1",
  96. traceId: "trace-1",
  97. content,
  98. },
  99. },
  100. };
  101. }
  102. function makeUserMessage(content: string, timestamp = 1234) {
  103. return {
  104. type: HostResponseTypes.TaskStreamOpPublish,
  105. target: makeStreamTarget(),
  106. op: {
  107. kind: "user_message",
  108. messageId: "trace-1:user",
  109. content,
  110. timestamp,
  111. },
  112. };
  113. }
  114. describe("TaskRealtimeBus", () => {
  115. it("forwards a publish from host A to host B in the same workspace", () => {
  116. const hostA = new FakeHostProcess();
  117. const hostB = new FakeHostProcess();
  118. const bus = new TaskRealtimeBus({ logger: makeLogger() });
  119. bus.registerHost({
  120. hostId: "host-a",
  121. windowId: 1,
  122. child: asUtilityProcess(hostA),
  123. workspaceKeys: ["/repo/demo"],
  124. });
  125. bus.registerHost({
  126. hostId: "host-b",
  127. windowId: 2,
  128. child: asUtilityProcess(hostB),
  129. workspaceKeys: ["/repo/demo"],
  130. });
  131. hostA.emitMessage(makePublish());
  132. expect(hostB.postedMessages).toEqual([
  133. {
  134. type: "task-realtime-deliver",
  135. event: expect.objectContaining({
  136. eventId: "evt-1",
  137. originHostId: "host-a",
  138. workspaceKey: "/repo/demo",
  139. }),
  140. },
  141. ]);
  142. });
  143. it("delivers publishes back to the origin host for ordered self replay", () => {
  144. const hostA = new FakeHostProcess();
  145. const bus = new TaskRealtimeBus({ logger: makeLogger() });
  146. bus.registerHost({
  147. hostId: "host-a",
  148. windowId: 1,
  149. child: asUtilityProcess(hostA),
  150. workspaceKeys: ["/repo/demo"],
  151. });
  152. hostA.emitMessage(makePublish());
  153. expect(hostA.postedMessages).toEqual([
  154. {
  155. type: "task-realtime-deliver",
  156. event: expect.objectContaining({
  157. eventId: "evt-1",
  158. originHostId: "host-a",
  159. workspaceKey: "/repo/demo",
  160. }),
  161. },
  162. ]);
  163. });
  164. it("does not cross-forward different workspaceIdentity scopes with the same path", () => {
  165. const hostA = new FakeHostProcess();
  166. const hostB = new FakeHostProcess();
  167. const bus = new TaskRealtimeBus({ logger: makeLogger() });
  168. bus.registerHost({
  169. hostId: "host-a",
  170. windowId: 1,
  171. child: asUtilityProcess(hostA),
  172. workspaceKeys: ["identity-a"],
  173. });
  174. bus.registerHost({
  175. hostId: "host-b",
  176. windowId: 2,
  177. child: asUtilityProcess(hostB),
  178. workspaceKeys: ["identity-b"],
  179. });
  180. hostA.emitMessage(
  181. makePublish({
  182. workspacePath: "/repo/demo",
  183. workspaceIdentity: "identity-a",
  184. workspaceKey: "identity-a",
  185. }),
  186. );
  187. expect(hostB.postedMessages).toEqual([]);
  188. });
  189. it("ignores duplicate eventId values", () => {
  190. const hostA = new FakeHostProcess();
  191. const hostB = new FakeHostProcess();
  192. const bus = new TaskRealtimeBus({ logger: makeLogger() });
  193. bus.registerHost({
  194. hostId: "host-a",
  195. windowId: 1,
  196. child: asUtilityProcess(hostA),
  197. workspaceKeys: ["/repo/demo"],
  198. });
  199. bus.registerHost({
  200. hostId: "host-b",
  201. windowId: 2,
  202. child: asUtilityProcess(hostB),
  203. workspaceKeys: ["/repo/demo"],
  204. });
  205. hostA.emitMessage(makePublish());
  206. hostA.emitMessage(makePublish());
  207. expect(hostB.postedMessages).toHaveLength(1);
  208. });
  209. it("does not crash on invalid payloads", () => {
  210. const logger = makeLogger();
  211. const hostA = new FakeHostProcess();
  212. const hostB = new FakeHostProcess();
  213. const bus = new TaskRealtimeBus({ logger });
  214. bus.registerHost({
  215. hostId: "host-a",
  216. windowId: 1,
  217. child: asUtilityProcess(hostA),
  218. workspaceKeys: ["/repo/demo"],
  219. });
  220. bus.registerHost({
  221. hostId: "host-b",
  222. windowId: 2,
  223. child: asUtilityProcess(hostB),
  224. workspaceKeys: ["/repo/demo"],
  225. });
  226. hostA.emitMessage({
  227. type: HostResponseTypes.TaskRealtimePublish,
  228. event: {
  229. ...makePublish().event,
  230. workspaceKey: "wrong",
  231. },
  232. });
  233. expect(hostB.postedMessages).toEqual([]);
  234. expect(logger.warn).toHaveBeenCalled();
  235. });
  236. it("unregisters a host on exit", () => {
  237. const hostA = new FakeHostProcess();
  238. const hostB = new FakeHostProcess();
  239. const bus = new TaskRealtimeBus({ logger: makeLogger() });
  240. bus.registerHost({
  241. hostId: "host-a",
  242. windowId: 1,
  243. child: asUtilityProcess(hostA),
  244. workspaceKeys: ["/repo/demo"],
  245. });
  246. bus.registerHost({
  247. hostId: "host-b",
  248. windowId: 2,
  249. child: asUtilityProcess(hostB),
  250. workspaceKeys: ["/repo/demo"],
  251. });
  252. hostB.emitExit();
  253. hostA.emitMessage(makePublish());
  254. expect(hostB.postedMessages).toEqual([]);
  255. });
  256. it("acquires, rejects, releases, and reacquires task run leases", () => {
  257. const hostA = new FakeHostProcess();
  258. const hostB = new FakeHostProcess();
  259. const bus = new TaskRealtimeBus({ logger: makeLogger() });
  260. bus.registerHost({
  261. hostId: "host-a",
  262. windowId: 1,
  263. child: asUtilityProcess(hostA),
  264. workspaceKeys: ["/repo/demo"],
  265. });
  266. bus.registerHost({
  267. hostId: "host-b",
  268. windowId: 2,
  269. child: asUtilityProcess(hostB),
  270. workspaceKeys: ["/repo/demo"],
  271. });
  272. hostA.emitMessage(makeLeaseRequest("lease-a"));
  273. hostA.emitMessage(makeLeaseRequest("lease-a2"));
  274. hostB.emitMessage(makeLeaseRequest("lease-b"));
  275. hostA.emitMessage({
  276. type: HostResponseTypes.TaskRunLeaseRelease,
  277. target: makeStreamTarget(),
  278. });
  279. hostB.emitMessage(makeLeaseRequest("lease-b2"));
  280. expect(hostA.postedMessages).toEqual([
  281. {
  282. type: HostMessageTypes.TaskRunLeaseResult,
  283. result: { leaseRequestId: "lease-a", acquired: true, ownerHostId: "host-a" },
  284. },
  285. {
  286. type: HostMessageTypes.TaskRunLeaseResult,
  287. result: { leaseRequestId: "lease-a2", acquired: true, ownerHostId: "host-a" },
  288. },
  289. ]);
  290. expect(hostB.postedMessages).toEqual([
  291. {
  292. type: HostMessageTypes.TaskRunLeaseResult,
  293. result: {
  294. leaseRequestId: "lease-b",
  295. acquired: false,
  296. ownerHostId: "host-a",
  297. reason: "owned_by_other_host",
  298. },
  299. },
  300. {
  301. type: HostMessageTypes.TaskRunLeaseResult,
  302. result: { leaseRequestId: "lease-b2", acquired: true, ownerHostId: "host-b" },
  303. },
  304. ]);
  305. });
  306. it("batches stream ops, coalesces chunks, and delivers the same seq stream to owner and observer", () => {
  307. vi.useFakeTimers();
  308. const hostA = new FakeHostProcess();
  309. const hostB = new FakeHostProcess();
  310. const bus = new TaskRealtimeBus({ logger: makeLogger() });
  311. bus.registerHost({
  312. hostId: "host-a",
  313. windowId: 1,
  314. child: asUtilityProcess(hostA),
  315. workspaceKeys: ["/repo/demo"],
  316. });
  317. bus.registerHost({
  318. hostId: "host-b",
  319. windowId: 2,
  320. child: asUtilityProcess(hostB),
  321. workspaceKeys: ["/repo/demo"],
  322. });
  323. hostA.emitMessage(makeLeaseRequest());
  324. hostA.postedMessages.length = 0;
  325. hostA.emitMessage(makeChunk("hel"));
  326. hostA.emitMessage(makeChunk("lo"));
  327. vi.advanceTimersByTime(1000);
  328. expect(hostA.postedMessages).toHaveLength(1);
  329. expect(hostB.postedMessages).toHaveLength(1);
  330. expect(hostA.postedMessages[0]).toMatchObject({
  331. type: HostMessageTypes.TaskRealtimeDeliver,
  332. event: {
  333. type: "task_stream_mirror_batch",
  334. originHostId: "host-a",
  335. deliveryPurpose: "relay_owner",
  336. fromSeq: 1,
  337. toSeq: 1,
  338. ops: [
  339. {
  340. kind: "stream_event",
  341. seq: 1,
  342. event: { type: "agent_message_chunk", content: "hello" },
  343. },
  344. ],
  345. },
  346. });
  347. expect(hostB.postedMessages[0]).toMatchObject({
  348. type: HostMessageTypes.TaskRealtimeDeliver,
  349. event: {
  350. type: "task_stream_mirror_batch",
  351. originHostId: "host-a",
  352. deliveryPurpose: "observer",
  353. fromSeq: 1,
  354. toSeq: 1,
  355. ops: [
  356. {
  357. kind: "stream_event",
  358. seq: 1,
  359. event: { type: "agent_message_chunk", content: "hello" },
  360. },
  361. ],
  362. },
  363. });
  364. vi.useRealTimers();
  365. });
  366. it("flushes mirrored user messages before user_message_saved invalidation", () => {
  367. vi.useFakeTimers();
  368. const hostA = new FakeHostProcess();
  369. const hostB = new FakeHostProcess();
  370. const bus = new TaskRealtimeBus({ logger: makeLogger() });
  371. bus.registerHost({
  372. hostId: "host-a",
  373. windowId: 1,
  374. child: asUtilityProcess(hostA),
  375. workspaceKeys: ["/repo/demo"],
  376. });
  377. bus.registerHost({
  378. hostId: "host-b",
  379. windowId: 2,
  380. child: asUtilityProcess(hostB),
  381. workspaceKeys: ["/repo/demo"],
  382. });
  383. hostA.emitMessage(makeLeaseRequest());
  384. hostA.postedMessages.length = 0;
  385. hostB.postedMessages.length = 0;
  386. hostA.emitMessage(makeUserMessage("hello"));
  387. hostA.emitMessage(
  388. makePublish({
  389. eventId: "user-saved-1",
  390. reason: "user_message_saved",
  391. traceId: "trace-1",
  392. }),
  393. );
  394. expect(hostA.postedMessages).toHaveLength(2);
  395. expect(hostB.postedMessages).toHaveLength(2);
  396. expect(hostA.postedMessages[0]).toMatchObject({
  397. type: HostMessageTypes.TaskRealtimeDeliver,
  398. event: {
  399. type: "task_stream_mirror_batch",
  400. deliveryPurpose: "relay_owner",
  401. ops: [
  402. {
  403. kind: "user_message",
  404. messageId: "trace-1:user",
  405. content: "hello",
  406. timestamp: 1234,
  407. },
  408. ],
  409. },
  410. });
  411. expect(hostA.postedMessages[1]).toMatchObject({
  412. type: HostMessageTypes.TaskRealtimeDeliver,
  413. event: {
  414. type: "task_snapshot_invalidated",
  415. reason: "user_message_saved",
  416. },
  417. });
  418. expect(hostB.postedMessages[0]).toMatchObject({
  419. type: HostMessageTypes.TaskRealtimeDeliver,
  420. event: {
  421. type: "task_stream_mirror_batch",
  422. deliveryPurpose: "observer",
  423. ops: [
  424. {
  425. kind: "user_message",
  426. messageId: "trace-1:user",
  427. content: "hello",
  428. timestamp: 1234,
  429. },
  430. ],
  431. },
  432. });
  433. expect(hostB.postedMessages[1]).toMatchObject({
  434. type: HostMessageTypes.TaskRealtimeDeliver,
  435. event: {
  436. type: "task_snapshot_invalidated",
  437. reason: "user_message_saved",
  438. },
  439. });
  440. vi.useRealTimers();
  441. });
  442. it("falls back to snapshot invalidation when replay exceeds retention limits", () => {
  443. vi.useFakeTimers();
  444. const hostA = new FakeHostProcess();
  445. const hostC = new FakeHostProcess();
  446. const bus = new TaskRealtimeBus({ logger: makeLogger() });
  447. bus.registerHost({
  448. hostId: "host-a",
  449. windowId: 1,
  450. child: asUtilityProcess(hostA),
  451. workspaceKeys: ["/repo/demo"],
  452. });
  453. hostA.emitMessage(makeLeaseRequest());
  454. hostA.postedMessages.length = 0;
  455. for (let index = 0; index < 65; index += 1) {
  456. hostA.emitMessage(makeChunk(String(index)));
  457. vi.advanceTimersByTime(1000);
  458. }
  459. bus.registerHost({
  460. hostId: "host-c",
  461. windowId: 3,
  462. child: asUtilityProcess(hostC),
  463. workspaceKeys: ["/repo/demo"],
  464. });
  465. expect(hostC.postedMessages).toContainEqual(
  466. expect.objectContaining({
  467. type: HostMessageTypes.TaskRealtimeDeliver,
  468. event: expect.objectContaining({
  469. type: "task_snapshot_invalidated",
  470. reason: "stream_mirror_gap",
  471. streamWatermark: { runId: "trace-1", opSeq: 65 },
  472. }),
  473. }),
  474. );
  475. vi.useRealTimers();
  476. });
  477. it("splits oversized mirror batches for owner and invalidates observers", () => {
  478. vi.useFakeTimers();
  479. const hostA = new FakeHostProcess();
  480. const hostB = new FakeHostProcess();
  481. const bus = new TaskRealtimeBus({ logger: makeLogger() });
  482. bus.registerHost({
  483. hostId: "host-a",
  484. windowId: 1,
  485. child: asUtilityProcess(hostA),
  486. workspaceKeys: ["/repo/demo"],
  487. });
  488. bus.registerHost({
  489. hostId: "host-b",
  490. windowId: 2,
  491. child: asUtilityProcess(hostB),
  492. workspaceKeys: ["/repo/demo"],
  493. });
  494. hostA.emitMessage(makeLeaseRequest());
  495. hostA.postedMessages.length = 0;
  496. hostB.postedMessages.length = 0;
  497. hostA.emitMessage(makeChunk("x".repeat(560 * 1024)));
  498. vi.advanceTimersByTime(1000);
  499. const ownerBatches = hostA.postedMessages
  500. .map((message) => (message as { event?: unknown }).event)
  501. .filter(
  502. (
  503. event,
  504. ): event is { type: string; deliveryPurpose?: string; ops?: Array<{ seq: number }> } =>
  505. typeof event === "object" &&
  506. event !== null &&
  507. (event as { type?: unknown }).type === "task_stream_mirror_batch",
  508. );
  509. expect(ownerBatches.length).toBeGreaterThan(1);
  510. expect(ownerBatches.every((event) => event.deliveryPurpose === "relay_owner")).toBe(true);
  511. expect(ownerBatches.flatMap((event) => event.ops?.map((op) => op.seq) ?? [])).toEqual([
  512. 1, 2, 3, 4, 5,
  513. ]);
  514. expect(ownerBatches.every((event) => JSON.stringify(event).length <= 512 * 1024)).toBe(true);
  515. expect(hostB.postedMessages).toEqual([
  516. expect.objectContaining({
  517. type: HostMessageTypes.TaskRealtimeDeliver,
  518. event: expect.objectContaining({
  519. type: "task_snapshot_invalidated",
  520. reason: "stream_mirror_gap",
  521. streamWatermark: { runId: "trace-1", opSeq: 5 },
  522. }),
  523. }),
  524. ]);
  525. vi.useRealTimers();
  526. });
  527. it("delivers relay bridge owners the same mirror batches as observers", () => {
  528. vi.useFakeTimers();
  529. const hostA = new FakeHostProcess();
  530. const bus = new TaskRealtimeBus({ logger: makeLogger() });
  531. bus.registerHost({
  532. hostId: "host-a",
  533. windowId: 1,
  534. child: asUtilityProcess(hostA),
  535. workspaceKeys: ["/repo/demo"],
  536. deliveryKind: "relay_bridge",
  537. });
  538. expect(bus.getHostDeliveryKindForTest("host-a")).toBe("relay_bridge");
  539. hostA.emitMessage(makeLeaseRequest());
  540. hostA.postedMessages.length = 0;
  541. hostA.emitMessage(makeChunk("hello"));
  542. vi.advanceTimersByTime(1000);
  543. expect(hostA.postedMessages).toEqual([
  544. expect.objectContaining({
  545. type: HostMessageTypes.TaskRealtimeDeliver,
  546. event: expect.objectContaining({
  547. type: "task_stream_mirror_batch",
  548. deliveryPurpose: "relay_owner",
  549. }),
  550. }),
  551. ]);
  552. vi.useRealTimers();
  553. });
  554. it("routes owner commands and forwards results", () => {
  555. const hostA = new FakeHostProcess();
  556. const hostB = new FakeHostProcess();
  557. const bus = new TaskRealtimeBus({ logger: makeLogger() });
  558. bus.registerHost({
  559. hostId: "host-a",
  560. windowId: 1,
  561. child: asUtilityProcess(hostA),
  562. workspaceKeys: ["/repo/demo"],
  563. });
  564. bus.registerHost({
  565. hostId: "host-b",
  566. windowId: 2,
  567. child: asUtilityProcess(hostB),
  568. workspaceKeys: ["/repo/demo"],
  569. });
  570. hostA.emitMessage(makeLeaseRequest());
  571. hostA.postedMessages.length = 0;
  572. hostB.emitMessage({
  573. type: HostResponseTypes.TaskOwnerCommandRequest,
  574. command: {
  575. commandRequestId: "cmd-1",
  576. type: "stop_generation",
  577. workspacePath: "/repo/demo",
  578. workspaceKey: "/repo/demo",
  579. taskId: "task-1",
  580. runId: "trace-1",
  581. },
  582. });
  583. expect(hostA.postedMessages[0]).toMatchObject({
  584. type: HostMessageTypes.TaskOwnerCommandDeliver,
  585. command: {
  586. commandRequestId: "cmd-1",
  587. requesterHostId: "host-b",
  588. },
  589. });
  590. hostA.emitMessage({
  591. type: HostResponseTypes.TaskOwnerCommandResult,
  592. result: { commandRequestId: "cmd-1", success: true },
  593. });
  594. expect(hostB.postedMessages.at(-1)).toEqual({
  595. type: HostMessageTypes.TaskOwnerCommandResult,
  596. result: { commandRequestId: "cmd-1", success: true },
  597. });
  598. });
  599. it("routes session messages by the desktop main session registry", () => {
  600. const hostA = new FakeHostProcess();
  601. const hostB = new FakeHostProcess();
  602. const bus = new TaskRealtimeBus({ logger: makeLogger() });
  603. bus.registerHost({
  604. hostId: "host-a",
  605. windowId: 1,
  606. child: asUtilityProcess(hostA),
  607. workspaceKeys: ["/repo/demo"],
  608. });
  609. bus.registerHost({
  610. hostId: "host-b",
  611. windowId: 2,
  612. child: asUtilityProcess(hostB),
  613. workspaceKeys: ["/repo/demo"],
  614. });
  615. hostB.emitMessage(makeSessionRouteAnnounce());
  616. hostB.postedMessages.length = 0;
  617. const request = makeSessionMessageRequest();
  618. hostA.emitMessage({
  619. type: HostResponseTypes.SessionMessageSendRequested,
  620. request,
  621. });
  622. expect(hostB.postedMessages).toEqual([
  623. {
  624. type: HostMessageTypes.SessionMessageDeliver,
  625. request,
  626. },
  627. ]);
  628. hostB.emitMessage({
  629. type: HostResponseTypes.SessionMessageDeliverResult,
  630. result: {
  631. messageId: "msg-1",
  632. requestId: "req-1",
  633. sessionId: "session-source",
  634. status: "success",
  635. },
  636. });
  637. expect(hostA.postedMessages.at(-1)).toEqual({
  638. type: HostMessageTypes.SessionMessageDeliveryResult,
  639. result: {
  640. messageId: "msg-1",
  641. requestId: "req-1",
  642. sessionId: "session-source",
  643. status: "success",
  644. },
  645. });
  646. });
  647. it("returns failed session message delivery when target session is unknown", () => {
  648. const hostA = new FakeHostProcess();
  649. const bus = new TaskRealtimeBus({ logger: makeLogger() });
  650. bus.registerHost({
  651. hostId: "host-a",
  652. windowId: 1,
  653. child: asUtilityProcess(hostA),
  654. workspaceKeys: ["/repo/demo"],
  655. });
  656. hostA.emitMessage({
  657. type: HostResponseTypes.SessionMessageSendRequested,
  658. request: makeSessionMessageRequest({ toSessionId: "missing-session" }),
  659. });
  660. expect(hostA.postedMessages).toEqual([
  661. {
  662. type: HostMessageTypes.SessionMessageDeliveryResult,
  663. result: {
  664. error: "target session not found: missing-session",
  665. messageId: "msg-1",
  666. requestId: "req-1",
  667. sessionId: "session-source",
  668. status: "failed",
  669. },
  670. },
  671. ]);
  672. });
  673. it("fails pending session message delivery when the target host exits", () => {
  674. const hostA = new FakeHostProcess();
  675. const hostB = new FakeHostProcess();
  676. const bus = new TaskRealtimeBus({ logger: makeLogger() });
  677. bus.registerHost({
  678. hostId: "host-a",
  679. windowId: 1,
  680. child: asUtilityProcess(hostA),
  681. workspaceKeys: ["/repo/demo"],
  682. });
  683. bus.registerHost({
  684. hostId: "host-b",
  685. windowId: 2,
  686. child: asUtilityProcess(hostB),
  687. workspaceKeys: ["/repo/demo"],
  688. });
  689. hostB.emitMessage(makeSessionRouteAnnounce());
  690. hostB.postedMessages.length = 0;
  691. hostA.emitMessage({
  692. type: HostResponseTypes.SessionMessageSendRequested,
  693. request: makeSessionMessageRequest(),
  694. });
  695. hostB.emitExit();
  696. expect(hostA.postedMessages.at(-1)).toEqual({
  697. type: HostMessageTypes.SessionMessageDeliveryResult,
  698. result: {
  699. error: "Session message host exited.",
  700. messageId: "msg-1",
  701. requestId: "req-1",
  702. sessionId: "session-source",
  703. status: "failed",
  704. },
  705. });
  706. });
  707. });
  708. describe("TaskRealtimeBus.collectMemoryDiagnostics", () => {
  709. it("返回 streamBatches / leases / sessionRoutes 三张表的只读大小", () => {
  710. const bus = new TaskRealtimeBus({ logger: makeLogger() });
  711. expect(bus.collectMemoryDiagnostics()).toEqual({
  712. streamBatches: 0,
  713. leases: 0,
  714. sessionRoutes: 0,
  715. });
  716. });
  717. });