import { describe, expect, test } from "bun:test"; import { type DequeuedBatch, type MessageQueueItem, type QueueItem, QueueRuntime, } from "@/queue/queue-runtime"; // ── Helpers ─────────────────────────────────────────────────────── function makeMsg(text = "hello"): Omit { return { kind: "message", source: "user", content: text }; } function makeScopedMsg(params: { text?: string; agentId?: string; conversationId?: string; }): Omit { return { kind: "message", source: "user", content: params.text ?? "hello", agentId: params.agentId, conversationId: params.conversationId, }; } function makeTask( text = "", ): Omit< Extract, "id" | "enqueuedAt" > { return { kind: "task_notification", source: "task_notification", text }; } function makeContinue( text = "keep going", ): Omit, "id" | "enqueuedAt"> { return { kind: "mod_continue", source: "system", text }; } // ── Enqueue ─────────────────────────────────────────────────────── describe("enqueue basics", () => { test("adds item, assigns ID, returns item, length increases", () => { const q = new QueueRuntime(); const item = q.enqueue(makeMsg()); expect(item).not.toBeNull(); expect(item?.id).toMatch(/^q-\d+$/); expect(item?.kind).toBe("message"); expect(q.length).toBe(1); }); test("onEnqueued fires with correct item and queue length", () => { const calls: [QueueItem, number][] = []; const q = new QueueRuntime({ callbacks: { onEnqueued: (item, len) => calls.push([item, len]) }, }); q.enqueue(makeMsg("a")); q.enqueue(makeMsg("b")); expect(calls).toHaveLength(2); expect(calls.at(0)?.[1]).toBe(1); expect(calls.at(1)?.[1]).toBe(2); }); test("multimodal content preserved through round-trip", () => { const q = new QueueRuntime(); // Use an array of text parts to verify multipart content is preserved const content: MessageQueueItem["content"] = [ { type: "text" as const, text: "part one" }, { type: "text" as const, text: "part two" }, ]; const input: Omit = { kind: "message", source: "user", content, }; const item = q.enqueue(input); expect(item).not.toBeNull(); const batch = q.tryDequeue(null); expect(batch).not.toBeNull(); const dequeued = batch?.items.at(0) as MessageQueueItem; expect(dequeued.content).toEqual(content); }); }); describe("bounded buffer — soft limit", () => { test("drops oldest item when at soft limit", () => { const dropped: QueueItem[] = []; const q = new QueueRuntime({ maxItems: 2, callbacks: { onDropped: (item) => dropped.push(item) }, }); const a = q.enqueue(makeMsg("a")); expect(a).not.toBeNull(); q.enqueue(makeMsg("b")); q.enqueue(makeMsg("c")); // triggers drop of "a" expect(dropped).toHaveLength(1); expect((dropped.at(0) as MessageQueueItem).content).toBe("a"); const droppedItem = dropped.at(0); expect(a?.id).toEqual(droppedItem?.id); expect(q.length).toBe(2); }); test("soft-limit drop repeats for each arrival at capacity", () => { const dropped: QueueItem[] = []; const q = new QueueRuntime({ maxItems: 2, callbacks: { onDropped: (item) => dropped.push(item) }, }); q.enqueue(makeMsg("a")); q.enqueue(makeMsg("b")); // full q.enqueue(makeMsg("c")); // drops "a" q.enqueue(makeMsg("d")); // drops "b" expect(dropped).toHaveLength(2); expect(q.length).toBe(2); }); }); describe("bounded buffer — hard ceiling", () => { test("hard ceiling rejects before the soft-limit drop", () => { // maxItems == hardMaxItems: the hard ceiling check runs first, so the new // item is rejected instead of evicting the oldest one. const dropped: string[] = []; const q = new QueueRuntime({ maxItems: 1, hardMaxItems: 1, callbacks: { onDropped: (_item, reason) => dropped.push(reason) }, }); q.enqueue(makeMsg("a")); // length 1 = at hard ceiling const rejected = q.enqueue(makeMsg("b")); // hard ceiling — rejected expect(rejected).toBeNull(); expect(dropped).toEqual(["buffer_limit"]); expect(q.length).toBe(1); // unchanged }); test("durability refusal never reports a phantom as durably dropped", () => { const dropped: QueueItem[] = []; const q = new QueueRuntime({ maxItems: 1, hardMaxItems: 1, callbacks: { beforeDropped: () => false, onDropped: (item) => dropped.push(item), }, }); q.enqueue(makeMsg("a")); expect(q.enqueue(makeMsg("b"))).toBeNull(); expect(dropped).toEqual([]); expect(q.length).toBe(1); }); }); // ── Dequeue — coalescable ───────────────────────────────────────── describe("dequeue coalescable items", () => { test("returns all contiguous coalescable items as one batch", () => { const q = new QueueRuntime(); q.enqueue(makeMsg("a")); q.enqueue(makeTask("")); q.enqueue(makeMsg("b")); const batch = q.tryDequeue(null); expect(batch).not.toBeNull(); expect(batch?.items).toHaveLength(3); expect(batch?.mergedCount).toBe(3); }); test("mod_continue items are coalescable and dequeue as a batch", () => { const q = new QueueRuntime(); q.enqueue(makeContinue("keep going")); const batch = q.tryDequeue(null); expect(batch).not.toBeNull(); expect(batch?.items).toHaveLength(1); expect(batch?.items[0]?.kind).toBe("mod_continue"); expect(q.length).toBe(0); }); test("onDequeued fires with correct batch metadata", () => { const batches: DequeuedBatch[] = []; const q = new QueueRuntime({ callbacks: { onDequeued: (b) => batches.push(b) }, }); q.enqueue(makeMsg("a")); q.enqueue(makeMsg("b")); q.tryDequeue(null); expect(batches).toHaveLength(1); const b = batches.at(0); expect(b?.mergedCount).toBe(2); expect(b?.queueLenAfter).toBe(0); expect(b?.batchId).toMatch(/^batch-\d+$/); }); test("does not coalesce adjacent items from different conversation scopes", () => { const q = new QueueRuntime(); q.enqueue( makeScopedMsg({ text: "a", agentId: "agent-1", conversationId: "default", }), ); q.enqueue( makeScopedMsg({ text: "b", agentId: "agent-2", conversationId: "default", }), ); const first = q.tryDequeue(null); expect((first?.items.at(0) as MessageQueueItem | undefined)?.content).toBe( "a", ); const second = q.tryDequeue(null); expect((second?.items.at(0) as MessageQueueItem | undefined)?.content).toBe( "b", ); }); test("coalesces task notifications for the same acting user", () => { const q = new QueueRuntime(); q.enqueue({ ...makeTask("a"), actingUserId: "cloud-user-a" }); q.enqueue({ ...makeTask("b"), actingUserId: "cloud-user-a" }); const batch = q.tryDequeue(null); expect(batch?.items.map((item) => item.actingUserId)).toEqual([ "cloud-user-a", "cloud-user-a", ]); expect(q.length).toBe(0); }); test("dequeues different acting users in arrival order without author gating", () => { const q = new QueueRuntime(); q.enqueue(makeTask("unattributed")); q.enqueue({ ...makeTask("a"), actingUserId: "cloud-user-a" }); q.enqueue({ ...makeTask("b"), actingUserId: "cloud-user-b" }); const first = q.tryDequeue(null); const second = q.tryDequeue(null); expect( first?.items.map((item) => ("text" in item ? item.text : undefined)), ).toEqual(["unattributed", "a", "b"]); expect(first?.items.map((item) => item.actingUserId)).toEqual([ undefined, "cloud-user-a", "cloud-user-b", ]); expect(second).toBeNull(); expect(q.length).toBe(0); }); test("length is 0 after full dequeue", () => { const q = new QueueRuntime(); q.enqueue(makeMsg()); q.enqueue(makeMsg()); q.tryDequeue(null); expect(q.length).toBe(0); expect(q.isEmpty).toBe(true); }); test("tryDequeue on empty queue returns null, no callback", () => { const batches: DequeuedBatch[] = []; const q = new QueueRuntime({ callbacks: { onDequeued: (b) => batches.push(b) }, }); const result = q.tryDequeue(null); expect(result).toBeNull(); expect(batches).toHaveLength(0); }); }); // ── Blocked ─────────────────────────────────────────────────────── describe("blocked state", () => { test("tryDequeue(streaming) returns null, fires onBlocked", () => { const blocked: string[] = []; const q = new QueueRuntime({ callbacks: { onBlocked: (r) => blocked.push(r) }, }); q.enqueue(makeMsg()); const result = q.tryDequeue("streaming"); expect(result).toBeNull(); expect(blocked).toEqual(["streaming"]); }); test("same reason twice fires onBlocked only once", () => { const blocked: string[] = []; const q = new QueueRuntime({ callbacks: { onBlocked: (r) => blocked.push(r) }, }); q.enqueue(makeMsg()); q.tryDequeue("streaming"); q.tryDequeue("streaming"); expect(blocked).toHaveLength(1); }); test("different reason fires onBlocked again", () => { const blocked: string[] = []; const q = new QueueRuntime({ callbacks: { onBlocked: (r) => blocked.push(r) }, }); q.enqueue(makeMsg()); q.tryDequeue("streaming"); q.tryDequeue("pending_approvals"); expect(blocked).toEqual(["streaming", "pending_approvals"]); }); test("tryDequeue(null) after blocked resets tracking", () => { const blocked: string[] = []; const q = new QueueRuntime({ callbacks: { onBlocked: (r) => blocked.push(r) }, }); q.enqueue(makeMsg()); q.tryDequeue("streaming"); q.tryDequeue(null); // unblocks, dequeues q.enqueue(makeMsg()); q.tryDequeue("streaming"); // should fire again expect(blocked).toHaveLength(2); }); test("blocked with empty queue does NOT fire onBlocked", () => { const blocked: string[] = []; const q = new QueueRuntime({ callbacks: { onBlocked: (r) => blocked.push(r) }, }); q.tryDequeue("streaming"); expect(blocked).toHaveLength(0); }); test("queue empties while blocked, then refills under same reason: emits again", () => { const blocked: string[] = []; const q = new QueueRuntime({ callbacks: { onBlocked: (r) => blocked.push(r) }, }); q.enqueue(makeMsg()); q.tryDequeue("streaming"); // emits "streaming" q.tryDequeue(null); // dequeues, queue empty, resets epoch q.enqueue(makeMsg()); // refills under same block q.tryDequeue("streaming"); // should emit "streaming" again expect(blocked).toHaveLength(2); expect(blocked).toEqual(["streaming", "streaming"]); }); }); // ── Clear ───────────────────────────────────────────────────────── describe("clear", () => { test("removes all items and fires onCleared with count", () => { const cleared: [string, number][] = []; const q = new QueueRuntime({ callbacks: { onCleared: (r, n) => cleared.push([r, n]) }, }); q.enqueue(makeMsg()); q.enqueue(makeMsg()); q.clear("error"); expect(q.length).toBe(0); expect(cleared).toEqual([["error", 2]]); }); test("clear on empty queue fires onCleared with 0", () => { const cleared: number[] = []; const q = new QueueRuntime({ callbacks: { onCleared: (_r, n) => cleared.push(n) }, }); q.clear("shutdown"); expect(cleared).toEqual([0]); }); }); // ── Callback safety ─────────────────────────────────────────────── describe("callback safety", () => { test("callback that throws does not corrupt queue state", () => { const q = new QueueRuntime({ callbacks: { onEnqueued: () => { throw new Error("boom"); }, }, }); const item = q.enqueue(makeMsg()); expect(item).not.toBeNull(); expect(q.length).toBe(1); // state intact despite callback throw }); test("subsequent operations work after callback throw", () => { let throwCount = 0; const q = new QueueRuntime({ callbacks: { onDequeued: () => { throwCount++; throw new Error("oops"); }, }, }); q.enqueue(makeMsg("a")); q.tryDequeue(null); // throws in callback q.enqueue(makeMsg("b")); const batch = q.tryDequeue(null); // should work fine expect(batch).not.toBeNull(); expect(batch?.items).toHaveLength(1); expect(throwCount).toBe(2); }); }); // ── IDs ─────────────────────────────────────────────────────────── describe("IDs and accessors", () => { test("IDs are monotonically increasing within a runtime instance", () => { const q = new QueueRuntime(); const a = q.enqueue(makeMsg()); const b = q.enqueue(makeMsg()); const c = q.enqueue(makeMsg()); expect(a).not.toBeNull(); expect(b).not.toBeNull(); expect(c).not.toBeNull(); const ids = [a?.id ?? "", b?.id ?? "", c?.id ?? ""].map((id) => Number.parseInt(id.replace("q-", ""), 10), ); const [id0, id1, id2] = ids; expect(id0).toBeLessThan(id1 ?? 0); expect(id1).toBeLessThan(id2 ?? 0); }); test("peek returns items without removing them", () => { const q = new QueueRuntime(); q.enqueue(makeMsg("a")); q.enqueue(makeMsg("b")); const peeked = q.peek(); expect(peeked).toHaveLength(2); expect(q.length).toBe(2); // unchanged }); }); // ── consumeItems ────────────────────────────────────────────────── describe("consumeItems", () => { test("removes exactly n items and fires onDequeued with correct batch", () => { const batches: DequeuedBatch[] = []; const q = new QueueRuntime({ callbacks: { onDequeued: (b) => batches.push(b) }, }); q.enqueue(makeMsg("a")); q.enqueue(makeMsg("b")); q.enqueue(makeMsg("c")); const result = q.consumeItems(2); expect(result).not.toBeNull(); expect(result?.mergedCount).toBe(2); expect(result?.queueLenAfter).toBe(1); expect(q.length).toBe(1); expect(batches).toHaveLength(1); expect(batches.at(0)?.mergedCount).toBe(2); }); test("consumes all when n exceeds queue length", () => { const q = new QueueRuntime(); q.enqueue(makeMsg("a")); const result = q.consumeItems(100); expect(result?.mergedCount).toBe(1); expect(q.length).toBe(0); }); test("returns null on empty queue", () => { const q = new QueueRuntime(); expect(q.consumeItems(1)).toBeNull(); }); test("returns null for n <= 0", () => { const q = new QueueRuntime(); q.enqueue(makeMsg()); expect(q.consumeItems(0)).toBeNull(); expect(q.length).toBe(1); // unchanged }); test("resets blockedEmittedForNonEmpty when queue drains", () => { const blocked: string[] = []; const q = new QueueRuntime({ callbacks: { onBlocked: (r) => blocked.push(r) }, }); q.enqueue(makeMsg("a")); q.tryDequeue("runtime_busy"); // emits blocked q.consumeItems(1); // drains queue q.enqueue(makeMsg("b")); q.tryDequeue("runtime_busy"); // should emit blocked again (epoch reset on drain) expect(blocked).toHaveLength(2); }); }); // ── resetBlockedState ───────────────────────────────────────────── describe("resetBlockedState", () => { test("allows same reason to re-emit onBlocked after reset", () => { const blocked: string[] = []; const q = new QueueRuntime({ callbacks: { onBlocked: (r) => blocked.push(r) }, }); q.enqueue(makeMsg()); q.tryDequeue("runtime_busy"); // first blocked emit q.tryDequeue("runtime_busy"); // same reason — no second emit q.resetBlockedState(); q.tryDequeue("runtime_busy"); // after reset — emits again expect(blocked).toHaveLength(2); expect(blocked).toEqual(["runtime_busy", "runtime_busy"]); }); test("does not fire onBlocked on empty queue after reset", () => { const blocked: string[] = []; const q = new QueueRuntime({ callbacks: { onBlocked: (r) => blocked.push(r) }, }); q.resetBlockedState(); // no-op on empty q.tryDequeue("runtime_busy"); expect(blocked).toHaveLength(0); }); }); // ── removeItem ───────────────────────────────────────────────────── describe("removeItem", () => { test("removes item by ID and returns it", () => { const q = new QueueRuntime(); const item = q.enqueue(makeMsg("first")); q.enqueue(makeMsg("second")); expect(q.length).toBe(2); expect(item).not.toBeNull(); const removed = q.removeItem(item?.id ?? ""); expect(removed).not.toBeNull(); expect(removed?.id).toBe(item?.id); expect((removed as MessageQueueItem).content).toBe("first"); expect(q.length).toBe(1); }); test("returns null for nonexistent ID", () => { const q = new QueueRuntime(); q.enqueue(makeMsg()); const removed = q.removeItem("q-999"); expect(removed).toBeNull(); expect(q.length).toBe(1); }); test("fires onRemoved callback with item and new queue length", () => { const removedItems: QueueItem[] = []; const queueLengths: number[] = []; const q = new QueueRuntime({ callbacks: { onRemoved: (item, queueLen) => { removedItems.push(item); queueLengths.push(queueLen); }, }, }); const item = q.enqueue(makeMsg()); q.enqueue(makeMsg()); q.removeItem(item?.id ?? ""); expect(removedItems).toHaveLength(1); expect(removedItems[0]?.id).toBe(item?.id); expect(queueLengths).toEqual([1]); }); test("removes from middle of queue", () => { const q = new QueueRuntime(); q.enqueue(makeMsg("first")); const second = q.enqueue(makeMsg("second")); q.enqueue(makeMsg("third")); q.removeItem(second?.id ?? ""); expect(q.length).toBe(2); // Verify order is preserved const batch = q.consumeItems(2); expect((batch?.items.at(0) as MessageQueueItem | undefined)?.content).toBe( "first", ); expect((batch?.items.at(1) as MessageQueueItem | undefined)?.content).toBe( "third", ); }); test("rehydration rejection preserves accepted items without drop callbacks", () => { const dropped: string[] = []; const q = new QueueRuntime({ maxItems: 2, hardMaxItems: 3, callbacks: { onDropped: (item) => dropped.push(item.id) }, }); q.enqueue(makeMsg("first")); q.enqueue(makeMsg("second")); expect( q.enqueue(makeMsg("rehydrated"), { preserveExisting: true }), ).toBeNull(); expect(q.length).toBe(2); expect(dropped).toEqual([]); expect( q .consumeItems(2) ?.items.map((item) => ("content" in item ? item.content : undefined)), ).toEqual(["first", "second"]); }); test("resets blockedEmittedForNonEmpty when queue becomes empty", () => { const blocked: string[] = []; const q = new QueueRuntime({ callbacks: { onBlocked: (r) => blocked.push(r) }, }); const item = q.enqueue(makeMsg()); // Fire blocked once q.tryDequeue("streaming"); expect(blocked).toHaveLength(1); // Remove the item, making queue empty q.removeItem(item?.id ?? ""); expect(q.length).toBe(0); // Add new item and block again — should emit blocked q.enqueue(makeMsg()); q.tryDequeue("streaming"); expect(blocked).toHaveLength(2); }); });