runtime-command-queue.test.ts 8.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238
  1. import { describe, expect, it, vi } from "vitest";
  2. import { createRuntimeCommandQueue } from "../src/runtime/command-queue.js";
  3. import type {
  4. RuntimeCommand,
  5. RuntimeCommandId,
  6. RuntimeCommandPriority,
  7. } from "../src/runtime/command-queue.js";
  8. import type { AgentRuntimeInternal } from "../src/runtime/internal.js";
  9. import {
  10. acquireForegroundPromotionLease,
  11. drainRuntimeCommandQueue,
  12. } from "../src/runtime/methods/runtime-command-queue.js";
  13. function command(id: string, priority: RuntimeCommandPriority): RuntimeCommand {
  14. return {
  15. createdAt: new Date(`2026-06-29T00:00:0${id.at(-1) ?? "0"}.000Z`),
  16. id: id as RuntimeCommandId,
  17. mode: "task-notification",
  18. priority,
  19. source: "background_task",
  20. text: `<task-notification><task-id>${id}</task-id></task-notification>`,
  21. traceContext: {
  22. sessionId: "sess_runtime_command_queue",
  23. spanId: `span_${id}`,
  24. traceId: "trace_runtime_command_queue",
  25. },
  26. } as RuntimeCommand;
  27. }
  28. function promptCommand(
  29. id: string,
  30. priority: RuntimeCommandPriority,
  31. inputId?: string,
  32. ): RuntimeCommand {
  33. return {
  34. createdAt: new Date("2026-06-29T00:01:00.000Z"),
  35. id: id as RuntimeCommandId,
  36. input: id,
  37. mode: "prompt",
  38. ...(inputId ? { options: { inputId } } : {}),
  39. priority,
  40. reject: () => {},
  41. resolve: () => {},
  42. traceContext: {
  43. sessionId: "sess_runtime_command_queue",
  44. spanId: `span_${id}`,
  45. traceId: "trace_runtime_command_queue",
  46. },
  47. } as RuntimeCommand;
  48. }
  49. describe("RuntimeCommandQueue", () => {
  50. it("dequeues commands by priority before FIFO order", () => {
  51. const queue = createRuntimeCommandQueue();
  52. queue.enqueue(command("later-1", "later"));
  53. queue.enqueue(command("next-1", "next"));
  54. queue.enqueue(command("now-1", "now"));
  55. queue.enqueue(command("next-2", "next"));
  56. expect(queue.dequeue()?.id).toBe("now-1");
  57. expect(queue.dequeue()?.id).toBe("next-1");
  58. expect(queue.dequeue()?.id).toBe("next-2");
  59. expect(queue.dequeue()?.id).toBe("later-1");
  60. expect(queue.dequeue()).toBeUndefined();
  61. });
  62. it("preserves FIFO order for commands with the same priority", () => {
  63. const queue = createRuntimeCommandQueue();
  64. queue.enqueue(command("next-1", "next"));
  65. queue.enqueue(command("next-2", "next"));
  66. queue.enqueue(command("next-3", "next"));
  67. expect(queue.dequeue()?.id).toBe("next-1");
  68. expect(queue.dequeue()?.id).toBe("next-2");
  69. expect(queue.dequeue()?.id).toBe("next-3");
  70. });
  71. it("dequeues all same-priority task notifications as one frozen batch", () => {
  72. const queue = createRuntimeCommandQueue();
  73. queue.enqueue(command("next-1", "next"));
  74. queue.enqueue(command("next-2", "next"));
  75. queue.enqueue(command("later-1", "later"));
  76. const batch = queue.dequeueNextBatch();
  77. expect(Object.isFrozen(batch)).toBe(true);
  78. expect(batch.map((item) => item.id)).toEqual(["next-1", "next-2"]);
  79. expect(queue.dequeueNextBatch().map((item) => item.id)).toEqual(["later-1"]);
  80. expect(queue.dequeueNextBatch()).toEqual([]);
  81. });
  82. it("collects task notifications across later same-priority modes", () => {
  83. const queue = createRuntimeCommandQueue();
  84. queue.enqueue(command("next-1", "next"));
  85. queue.enqueue(promptCommand("prompt-1", "next"));
  86. queue.enqueue(command("next-2", "next"));
  87. expect(queue.dequeueNextBatch().map((item) => item.id)).toEqual(["next-1", "next-2"]);
  88. expect(queue.dequeueNextBatch().map((item) => item.id)).toEqual(["prompt-1"]);
  89. });
  90. it("does not batch past a higher-priority or earlier same-priority command", () => {
  91. const queue = createRuntimeCommandQueue();
  92. queue.enqueue(promptCommand("prompt-next", "next"));
  93. queue.enqueue(command("notification-next-1", "next"));
  94. queue.enqueue(promptCommand("prompt-now", "now"));
  95. queue.enqueue(command("notification-next-2", "next"));
  96. queue.enqueue(command("notification-later", "later"));
  97. expect(queue.dequeueNextBatch().map((item) => item.id)).toEqual(["prompt-now"]);
  98. expect(queue.dequeueNextBatch().map((item) => item.id)).toEqual(["prompt-next"]);
  99. expect(queue.dequeueNextBatch().map((item) => item.id)).toEqual([
  100. "notification-next-1",
  101. "notification-next-2",
  102. ]);
  103. expect(queue.dequeueNextBatch().map((item) => item.id)).toEqual(["notification-later"]);
  104. });
  105. it("returns a frozen snapshot that cannot mutate the queue", () => {
  106. const queue = createRuntimeCommandQueue();
  107. queue.enqueue(command("next-1", "next"));
  108. const snapshot = queue.snapshot();
  109. expect(Object.isFrozen(snapshot)).toBe(true);
  110. expect(() => {
  111. (snapshot as RuntimeCommand[]).push(command("now-1", "now"));
  112. }).toThrow();
  113. expect(queue.size()).toBe(1);
  114. });
  115. it("removes queued commands by id without touching other priorities", () => {
  116. const queue = createRuntimeCommandQueue();
  117. queue.enqueue(command("later-1", "later"));
  118. queue.enqueue(command("next-1", "next"));
  119. queue.enqueue(command("now-1", "now"));
  120. const removed = queue.removeById("next-1" as RuntimeCommandId);
  121. expect(removed?.id).toBe("next-1");
  122. expect(queue.size()).toBe(2);
  123. expect(queue.dequeue()?.id).toBe("now-1");
  124. expect(queue.dequeue()?.id).toBe("later-1");
  125. });
  126. it("returns all commands at or above the requested priority rank in enqueue order", () => {
  127. const queue = createRuntimeCommandQueue();
  128. queue.enqueue(command("later-1", "later"));
  129. queue.enqueue(command("next-1", "next"));
  130. queue.enqueue(command("now-1", "now"));
  131. queue.enqueue(command("next-2", "next"));
  132. queue.enqueue(command("later-2", "later"));
  133. const selected = queue.getByMaxPriority("next");
  134. expect(selected.map((item) => item.id)).toEqual(["next-1", "now-1", "next-2"]);
  135. expect(queue.size()).toBe(5);
  136. for (const item of selected) {
  137. queue.removeById(item.id);
  138. }
  139. expect(queue.size()).toBe(2);
  140. expect(queue.dequeue()?.id).toBe("later-1");
  141. expect(queue.dequeue()?.id).toBe("later-2");
  142. expect(queue.dequeue()).toBeUndefined();
  143. });
  144. it("tracks cancel-pending ids when removal races with dequeue", () => {
  145. const queue = createRuntimeCommandQueue();
  146. const id = "next-1" as RuntimeCommandId;
  147. expect(queue.consumeCancelPending(id)).toBe(false);
  148. queue.markCancelPending(id);
  149. expect(queue.consumeCancelPending(id)).toBe(true);
  150. expect(queue.consumeCancelPending(id)).toBe(false);
  151. });
  152. it("holds earlier runtime work until the leased promoted command is runnable", async () => {
  153. const executionOrder: string[] = [];
  154. const runtime = {
  155. activeForegroundExecution: undefined,
  156. activeTurn: undefined,
  157. activeTurnStartReservation: undefined,
  158. executeTurnCommand: vi.fn().mockImplementation(async (input: string) => {
  159. executionOrder.push(input);
  160. return {};
  161. }),
  162. foregroundPromotionLease: undefined,
  163. runtimeCommandDrainActive: false,
  164. runtimeCommandQueue: createRuntimeCommandQueue(),
  165. } as unknown as AgentRuntimeInternal;
  166. expect(
  167. acquireForegroundPromotionLease.call(runtime, {
  168. leaseId: "lease-bg44",
  169. mode: "after-current",
  170. promotedInputId: "lease-bg44",
  171. }),
  172. ).toEqual({ kind: "acquired", leaseId: "lease-bg44" });
  173. runtime.runtimeCommandQueue.enqueue(promptCommand("notification-b", "next"));
  174. await drainRuntimeCommandQueue.call(runtime);
  175. expect(executionOrder).toEqual([]);
  176. expect(runtime.runtimeCommandQueue.size()).toBe(1);
  177. runtime.runtimeCommandQueue.enqueue(promptCommand("promoted-prompt", "next", "lease-bg44"));
  178. await drainRuntimeCommandQueue.call(runtime);
  179. expect(executionOrder).toEqual(["promoted-prompt", "notification-b"]);
  180. expect(runtime.foregroundPromotionLease).toBeUndefined();
  181. });
  182. it("rejects idle-only acquisition while runtime work is pending", () => {
  183. const runtime = {
  184. activeForegroundExecution: undefined,
  185. activeTurn: undefined,
  186. activeTurnStartReservation: undefined,
  187. foregroundPromotionLease: undefined,
  188. runtimeCommandDrainActive: false,
  189. runtimeCommandQueue: createRuntimeCommandQueue(),
  190. } as unknown as AgentRuntimeInternal;
  191. runtime.runtimeCommandQueue.enqueue(promptCommand("notification-b", "next"));
  192. expect(
  193. acquireForegroundPromotionLease.call(runtime, {
  194. leaseId: "auto-drain-bg43",
  195. mode: "idle-only",
  196. promotedInputId: "notification-b",
  197. }),
  198. ).toEqual({ kind: "busy" });
  199. });
  200. });