v4-auto-drain-race.test.ts 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254
  1. import { describe, expect, it, vi } from "vitest";
  2. import {
  3. SessionEventType,
  4. createTraceId,
  5. createTurnId,
  6. type SessionEvent,
  7. type SessionId,
  8. } from "@zcode/contracts";
  9. import { zcodeProtocolMethods, type ZCodeProtocolMessage } from "@zcode/shared";
  10. import {
  11. V4_METHODS,
  12. conversationTopic,
  13. conversationTopicFrameSchema,
  14. reassembleTopicWireFrames,
  15. routedTopicWireFrameSchema,
  16. } from "@zcode/shared/zcode-protocol-v4";
  17. import type { ZCodeApp, ZCodeAppOptions } from "../src/app/types.js";
  18. import { ZCodeProtocolAgentServer } from "../src/zcode-protocol/server.js";
  19. import { createFakeApp } from "./helpers/fake-zcode-app.js";
  20. const workspace = {
  21. workspacePath: "/workspace/v4-auto-drain-race",
  22. workspaceKey: "/workspace/v4-auto-drain-race",
  23. };
  24. async function requestResult(
  25. server: ZCodeProtocolAgentServer,
  26. message: ZCodeProtocolMessage,
  27. ): Promise<unknown> {
  28. const response = await server.handleMessage(message);
  29. if (!response || !("result" in response)) {
  30. throw new Error(`Expected protocol success response: ${JSON.stringify(response)}`);
  31. }
  32. return response.result;
  33. }
  34. describe("v4 queue auto-drain foreground races", () => {
  35. it("BG43:Core-only notification 活跃时 auto-drain 不得抢占 foreground", async () => {
  36. let sessionEventSink: ((event: SessionEvent) => void) | undefined;
  37. let sequenceNumber = 0;
  38. let activeForegroundExecutionId: string | undefined;
  39. let rejectNextIdlePromotion = true;
  40. let emitEvent!: (type: SessionEvent["type"], payload: unknown, turnId?: string) => SessionEvent;
  41. const stopActiveForegroundExecution = vi.fn().mockImplementation(() => {
  42. const stoppedId = activeForegroundExecutionId;
  43. activeForegroundExecutionId = undefined;
  44. return stoppedId
  45. ? { kind: "stopped" as const, foregroundExecutionId: stoppedId }
  46. : { kind: "idle" as const };
  47. });
  48. const acquireForegroundPromotionLease = vi.fn().mockImplementation(({ leaseId }) => {
  49. if (rejectNextIdlePromotion) {
  50. rejectNextIdlePromotion = false;
  51. return { kind: "busy" as const };
  52. }
  53. return { kind: "acquired" as const, leaseId };
  54. });
  55. const reserveQueueItem = vi.fn().mockImplementation(async (_queueItemId, reservationId) => {
  56. emitEvent(SessionEventType.TurnSteerDispatchChanged, {
  57. pendingInputId: "queue-bg43",
  58. reservationId,
  59. state: "reserved",
  60. targetTurnId: "turn-before-bg43",
  61. });
  62. return true;
  63. });
  64. const markQueueItemPromoting = vi
  65. .fn()
  66. .mockImplementation(async (_queueItemId, reservationId) => {
  67. emitEvent(SessionEventType.TurnSteerDispatchChanged, {
  68. pendingInputId: "queue-bg43",
  69. reservationId,
  70. state: "promoting",
  71. targetTurnId: "turn-before-bg43",
  72. });
  73. return true;
  74. });
  75. const removeQueueItem = vi.fn().mockImplementation(async () => {
  76. emitEvent(SessionEventType.TurnSteerDiscarded, {
  77. pendingInputIds: ["queue-bg43"],
  78. reason: "promoted",
  79. targetTurnId: "turn-before-bg43",
  80. });
  81. return true;
  82. });
  83. const setQueueAutoDrain = vi.fn().mockResolvedValue(undefined);
  84. const sendInput = vi
  85. .fn()
  86. .mockImplementation(
  87. async (
  88. _input: unknown,
  89. options?: { onTurnStartedObserved?: (event: SessionEvent) => void },
  90. ) => {
  91. const turnStarted = emitEvent(
  92. SessionEventType.TurnStarted,
  93. {
  94. input: "BG43 queued text",
  95. inputId: "source-bg43",
  96. messageId: "message-bg43",
  97. turnNumber: 2,
  98. },
  99. "turn-promoted-bg43",
  100. );
  101. options?.onTurnStartedObserved?.(turnStarted);
  102. return {};
  103. },
  104. );
  105. const server = new ZCodeProtocolAgentServer({
  106. createZCodeApp: (options: ZCodeAppOptions) => {
  107. const app = createFakeApp(options);
  108. return {
  109. ...app,
  110. markQueueItemPromoting,
  111. readTarget: vi.fn().mockResolvedValue(null),
  112. releaseQueueItemReservation: vi.fn().mockResolvedValue(true),
  113. removeQueueItem,
  114. reserveQueueItem,
  115. sendInput,
  116. setQueueAutoDrain,
  117. runtime: {
  118. ...app.runtime,
  119. acquireForegroundPromotionLease,
  120. getActiveForegroundExecutionId: () => activeForegroundExecutionId,
  121. stopActiveForegroundExecution,
  122. subscribeEvents: (sink) => {
  123. sessionEventSink = sink.onSessionEvent;
  124. return () => {};
  125. },
  126. },
  127. } as ZCodeApp;
  128. },
  129. cwd: workspace.workspacePath,
  130. version: "test-version",
  131. });
  132. const created = (await requestResult(server, {
  133. id: "create-bg43",
  134. method: zcodeProtocolMethods.sessionCreate,
  135. params: { workspace },
  136. })) as { session: { sessionId: string } };
  137. const sessionId = created.session.sessionId as SessionId;
  138. const traceId = createTraceId("trace-bg43");
  139. emitEvent = (type, payload, turnId) => {
  140. sequenceNumber += 1;
  141. const event = {
  142. id: `event-bg43-${sequenceNumber}`,
  143. payload,
  144. sequenceNumber,
  145. sessionId,
  146. timestamp: new Date(1_700_000_000_000 + sequenceNumber),
  147. traceId,
  148. type,
  149. ...(turnId ? { turnId: createTurnId(turnId) } : {}),
  150. } as SessionEvent;
  151. sessionEventSink?.(event);
  152. return event;
  153. };
  154. emitEvent(SessionEventType.SessionCreated, {
  155. contextWindow: 128_000,
  156. mode: "build",
  157. });
  158. emitEvent(
  159. SessionEventType.TurnSteerQueued,
  160. {
  161. pendingInputId: "queue-bg43",
  162. inputId: "source-bg43",
  163. input: "BG43 queued text",
  164. inputPreview: "BG43 queued text",
  165. inputSize: 16,
  166. delivery: "queue",
  167. targetTurnId: "turn-before-bg43",
  168. queueLength: 1,
  169. intent: {
  170. sourceCommandId: "source-bg43",
  171. queueItemId: "queue-bg43",
  172. clientId: "desktop-bg43",
  173. kind: "sendText",
  174. admissionSeq: 1,
  175. admittedAt: 1_700_000_000_002,
  176. requestedDelivery: "queue",
  177. admittedDelivery: "queue",
  178. },
  179. },
  180. "turn-before-bg43",
  181. );
  182. emitEvent(SessionEventType.QueueAutoDrainChanged, { autoDrain: true });
  183. activeForegroundExecutionId = "notification-bg43";
  184. const subscriptionRequestId = "subscribe-bg43";
  185. await requestResult(server, {
  186. id: subscriptionRequestId,
  187. method: V4_METHODS.conversationSubscribe,
  188. params: {
  189. clientMode: "desktop-continuous",
  190. connectionId: "connection-bg43",
  191. topic: conversationTopic(sessionId),
  192. },
  193. });
  194. const assembled = reassembleTopicWireFrames(
  195. server
  196. .takePostResponseMessages(subscriptionRequestId)
  197. .map((message) => routedTopicWireFrameSchema.parse(message.params)),
  198. conversationTopicFrameSchema,
  199. );
  200. if (assembled.kind !== "complete" || assembled.frame.payload.kind !== "snapshot") {
  201. throw new Error("Expected complete BG43 conversation snapshot");
  202. }
  203. expect(assembled.frame.payload.snapshot.queue).toMatchObject({
  204. autoDrain: true,
  205. items: [
  206. expect.objectContaining({
  207. queueItemId: "queue-bg43",
  208. dispatch: { state: "queued" },
  209. }),
  210. ],
  211. });
  212. const autoDrainAck = await requestResult(server, {
  213. id: "resume-auto-drain-bg43",
  214. method: V4_METHODS.command,
  215. params: {
  216. baseRevision: assembled.frame.payload.snapshot.revision,
  217. clientId: "desktop-bg43",
  218. commandId: "set-auto-drain-bg43",
  219. issuedAt: 1_700_000_000_003,
  220. payload: { autoDrain: true },
  221. sessionId,
  222. type: "setAutoDrain",
  223. },
  224. });
  225. if ((autoDrainAck as { status?: string }).status !== "accepted") {
  226. throw new Error(`Unexpected BG43 command ACK: ${JSON.stringify(autoDrainAck)}`);
  227. }
  228. expect(setQueueAutoDrain).toHaveBeenCalledWith(true);
  229. expect(activeForegroundExecutionId).toBe("notification-bg43");
  230. expect(stopActiveForegroundExecution).not.toHaveBeenCalled();
  231. expect(reserveQueueItem).not.toHaveBeenCalled();
  232. expect(markQueueItemPromoting).not.toHaveBeenCalled();
  233. expect(sendInput).not.toHaveBeenCalled();
  234. expect(removeQueueItem).not.toHaveBeenCalled();
  235. activeForegroundExecutionId = undefined;
  236. await vi.waitFor(() => {
  237. expect(acquireForegroundPromotionLease).toHaveBeenCalledTimes(2);
  238. expect(reserveQueueItem).toHaveBeenCalledOnce();
  239. expect(markQueueItemPromoting).toHaveBeenCalledOnce();
  240. expect(sendInput).toHaveBeenCalledOnce();
  241. expect(removeQueueItem).toHaveBeenCalledOnce();
  242. });
  243. expect(stopActiveForegroundExecution).not.toHaveBeenCalled();
  244. });
  245. });