runtime-command-queue.test.ts 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226
  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("dequeues all same-priority task notifications as one frozen batch", () => {
  63. const queue = createRuntimeCommandQueue();
  64. queue.enqueue(command("next-1", "next"));
  65. queue.enqueue(command("next-2", "next"));
  66. queue.enqueue(command("later-1", "later"));
  67. const batch = queue.dequeueNextBatch();
  68. expect(Object.isFrozen(batch)).toBe(true);
  69. expect(batch.map((item) => item.id)).toEqual(["next-1", "next-2"]);
  70. expect(queue.dequeueNextBatch().map((item) => item.id)).toEqual(["later-1"]);
  71. expect(queue.dequeueNextBatch()).toEqual([]);
  72. });
  73. it("collects task notifications across later same-priority modes", () => {
  74. const queue = createRuntimeCommandQueue();
  75. queue.enqueue(command("next-1", "next"));
  76. queue.enqueue(promptCommand("prompt-1", "next"));
  77. queue.enqueue(command("next-2", "next"));
  78. expect(queue.dequeueNextBatch().map((item) => item.id)).toEqual(["next-1", "next-2"]);
  79. expect(queue.dequeueNextBatch().map((item) => item.id)).toEqual(["prompt-1"]);
  80. });
  81. it("does not batch past a higher-priority or earlier same-priority command", () => {
  82. const queue = createRuntimeCommandQueue();
  83. queue.enqueue(promptCommand("prompt-next", "next"));
  84. queue.enqueue(command("notification-next-1", "next"));
  85. queue.enqueue(promptCommand("prompt-now", "now"));
  86. queue.enqueue(command("notification-next-2", "next"));
  87. queue.enqueue(command("notification-later", "later"));
  88. expect(queue.dequeueNextBatch().map((item) => item.id)).toEqual(["prompt-now"]);
  89. expect(queue.dequeueNextBatch().map((item) => item.id)).toEqual(["prompt-next"]);
  90. expect(queue.dequeueNextBatch().map((item) => item.id)).toEqual([
  91. "notification-next-1",
  92. "notification-next-2",
  93. ]);
  94. expect(queue.dequeueNextBatch().map((item) => item.id)).toEqual(["notification-later"]);
  95. });
  96. it("returns a frozen snapshot that cannot mutate the queue", () => {
  97. const queue = createRuntimeCommandQueue();
  98. queue.enqueue(command("next-1", "next"));
  99. const snapshot = queue.snapshot();
  100. expect(Object.isFrozen(snapshot)).toBe(true);
  101. expect(() => {
  102. (snapshot as RuntimeCommand[]).push(command("now-1", "now"));
  103. }).toThrow();
  104. expect(queue.size()).toBe(1);
  105. });
  106. it("removes queued commands by id without touching other priorities", () => {
  107. const queue = createRuntimeCommandQueue();
  108. queue.enqueue(command("later-1", "later"));
  109. queue.enqueue(command("next-1", "next"));
  110. queue.enqueue(command("now-1", "now"));
  111. const removed = queue.removeById("next-1" as RuntimeCommandId);
  112. expect(removed?.id).toBe("next-1");
  113. expect(queue.size()).toBe(2);
  114. expect(queue.dequeue()?.id).toBe("now-1");
  115. expect(queue.dequeue()?.id).toBe("later-1");
  116. });
  117. it("returns all commands at or above the requested priority rank in enqueue order", () => {
  118. const queue = createRuntimeCommandQueue();
  119. queue.enqueue(command("later-1", "later"));
  120. queue.enqueue(command("next-1", "next"));
  121. queue.enqueue(command("now-1", "now"));
  122. queue.enqueue(command("next-2", "next"));
  123. queue.enqueue(command("later-2", "later"));
  124. const selected = queue.getByMaxPriority("next");
  125. expect(selected.map((item) => item.id)).toEqual(["next-1", "now-1", "next-2"]);
  126. expect(queue.size()).toBe(5);
  127. for (const item of selected) {
  128. queue.removeById(item.id);
  129. }
  130. expect(queue.size()).toBe(2);
  131. expect(queue.dequeue()?.id).toBe("later-1");
  132. expect(queue.dequeue()?.id).toBe("later-2");
  133. expect(queue.dequeue()).toBeUndefined();
  134. });
  135. it("tracks cancel-pending ids when removal races with dequeue", () => {
  136. const queue = createRuntimeCommandQueue();
  137. const id = "next-1" as RuntimeCommandId;
  138. expect(queue.consumeCancelPending(id)).toBe(false);
  139. queue.markCancelPending(id);
  140. expect(queue.consumeCancelPending(id)).toBe(true);
  141. expect(queue.consumeCancelPending(id)).toBe(false);
  142. });
  143. it("holds earlier runtime work until the leased promoted command is runnable", async () => {
  144. const executionOrder: string[] = [];
  145. const runtime = {
  146. activeForegroundExecution: undefined,
  147. activeTurn: undefined,
  148. activeTurnStartReservation: undefined,
  149. executeTurnCommand: vi.fn().mockImplementation(async (input: string) => {
  150. executionOrder.push(input);
  151. return {};
  152. }),
  153. foregroundPromotionLease: undefined,
  154. runtimeCommandDrainActive: false,
  155. runtimeCommandQueue: createRuntimeCommandQueue(),
  156. } as unknown as AgentRuntimeInternal;
  157. expect(
  158. acquireForegroundPromotionLease.call(runtime, {
  159. leaseId: "lease-bg44",
  160. mode: "after-current",
  161. promotedInputId: "lease-bg44",
  162. }),
  163. ).toEqual({ kind: "acquired", leaseId: "lease-bg44" });
  164. runtime.runtimeCommandQueue.enqueue(promptCommand("notification-b", "next"));
  165. await drainRuntimeCommandQueue.call(runtime);
  166. expect(executionOrder).toEqual([]);
  167. expect(runtime.runtimeCommandQueue.size()).toBe(1);
  168. runtime.runtimeCommandQueue.enqueue(promptCommand("promoted-prompt", "next", "lease-bg44"));
  169. await drainRuntimeCommandQueue.call(runtime);
  170. expect(executionOrder).toEqual(["promoted-prompt", "notification-b"]);
  171. expect(runtime.foregroundPromotionLease).toBeUndefined();
  172. });
  173. it("rejects idle-only acquisition while runtime work is pending", () => {
  174. const runtime = {
  175. activeForegroundExecution: undefined,
  176. activeTurn: undefined,
  177. activeTurnStartReservation: undefined,
  178. foregroundPromotionLease: undefined,
  179. runtimeCommandDrainActive: false,
  180. runtimeCommandQueue: createRuntimeCommandQueue(),
  181. } as unknown as AgentRuntimeInternal;
  182. runtime.runtimeCommandQueue.enqueue(promptCommand("notification-b", "next"));
  183. expect(
  184. acquireForegroundPromotionLease.call(runtime, {
  185. leaseId: "auto-drain-bg43",
  186. mode: "idle-only",
  187. promotedInputId: "notification-b",
  188. }),
  189. ).toEqual({ kind: "busy" });
  190. });
  191. });