import { afterEach, beforeEach, describe, expect, test } from "bun:test"; import { chmodSync, existsSync, mkdtempSync, readFileSync, rmSync, unlinkSync, writeFileSync, } from "node:fs"; import { createHash } from "node:crypto"; import { tmpdir } from "node:os"; import { join } from "node:path"; import { DaemonServer } from "@cueloop/daemon"; import { DaemonClient } from "@cueloop/daemon/client"; import { runHarnessBridge } from "../harness-bridge"; import { createCodexDeliveryService } from "./delivery-service"; import { createCodexSessionRegistry } from "./session-registry"; let home: string; let server: DaemonServer; let client: DaemonClient; let codexBin: string; beforeEach(async () => { home = mkdtempSync(join(tmpdir(), "cueloop-codex-delivery-")); server = new DaemonServer({ home, idleExitMs: 0 }); server.start(); client = await DaemonClient.connect({ home }); codexBin = join(home, "codex"); writeFileSync( codexBin, '#!/bin/sh\n[ -f fail ] && exit 1\necho sent >> invocations.txt\nprintf "%s" "$5" > messages.txt\n', ); chmodSync(codexBin, 0o755); createCodexSessionRegistry(home).activate("codex-session-1"); }); afterEach(() => { client?.close(); server?.stop(); rmSync(home, { recursive: true, force: true }); }); describe("createCodexDeliveryService", () => { test("a running poller delivers a message after the tool call has returned", async () => { const opened = await runHarnessBridge( { operation: "open", harness: "codex", harnessSessionId: "codex-session-1", cwd: home, workflow: "plan", content: "# Wait for feedback", }, home, ); if (opened.operation !== "open") throw new Error("expected open Thread"); const service = createCodexDeliveryService({ home, codexBin, pollMs: 20 }); service.start(); try { await Bun.sleep(100); await client.sessionSendMessage(opened.threadId, "approved", "Delayed response."); const deadline = Date.now() + 3000; while (!existsSync(join(home, "messages.txt")) && Date.now() < deadline) await Bun.sleep(20); expect(readFileSync(join(home, "messages.txt"), "utf8")).toContain("Delayed response."); } finally { service.stop(); } }); test("a malformed session record does not stop healthy sessions", async () => { const hash = createHash("sha256").update("broken-session").digest("hex"); writeFileSync(join(home, "codex-active-sessions", `${hash}.json`), "{"); const opened = await runHarnessBridge( { operation: "open", harness: "codex", harnessSessionId: "codex-session-1", cwd: home, workflow: "plan", content: "# Plan", }, home, ); if (opened.operation !== "open") throw new Error("expected open Thread"); await client.sessionSendMessage(opened.threadId, "approved", "Continue."); await createCodexDeliveryService({ home, codexBin }).reconcile(); expect(readFileSync(join(home, "messages.txt"), "utf8")).toContain("Continue."); }); test("a stale Codex session does not block delivery to another session", async () => { const sessions = createCodexSessionRegistry(home); sessions.activate("codex-session-2"); const opened = await runHarnessBridge( { operation: "open", harness: "codex", harnessSessionId: "codex-session-2", cwd: home, workflow: "plan", content: "# Second plan", }, home, ); if (opened.operation !== "open") throw new Error("expected open Thread"); await client.sessionSendMessage(opened.threadId, "approved", "Continue second session."); writeFileSync( codexBin, '#!/bin/sh\n[ "$3" = codex-session-1 ] && exit 1\necho sent >> invocations.txt\nprintf "%s" "$5" > messages.txt\n', ); const first = await runHarnessBridge( { operation: "open", harness: "codex", harnessSessionId: "codex-session-1", cwd: home, workflow: "plan", content: "# First plan", }, home, ); if (first.operation !== "open") throw new Error("expected open Thread"); await client.sessionSendMessage(first.threadId, "approved", "Blocked first session."); await expect(createCodexDeliveryService({ home, codexBin }).reconcile()).rejects.toThrow( "Codex Message injection failed", ); expect(readFileSync(join(home, "messages.txt"), "utf8")).toContain("Continue second session."); const pending = await runHarnessBridge( { operation: "pending", harness: "codex", harnessSessionId: "codex-session-2" }, home, ); if (pending.operation !== "pending") throw new Error("expected pending response"); expect(pending.deliveries).toEqual([]); }); test("redelivers after a failed queue and does not duplicate an acknowledged Message", async () => { const opened = await runHarnessBridge( { operation: "open", harness: "codex", harnessSessionId: "codex-session-1", cwd: home, workflow: "plan", content: "# Plan\n\nShip it.", }, home, ); if (opened.operation !== "open") throw new Error("expected open Thread"); await client.sessionSendMessage(opened.threadId, "approved", "Proceed."); const service = createCodexDeliveryService({ home, codexBin }); writeFileSync(join(home, "fail"), ""); await expect(service.reconcile()).rejects.toThrow("Codex Message injection failed"); expect(existsSync(join(home, "messages.txt"))).toBeFalse(); unlinkSync(join(home, "fail")); const restarted = createCodexDeliveryService({ home, codexBin }); await restarted.reconcile(); await restarted.reconcile(); expect(readFileSync(join(home, "messages.txt"), "utf8")).toContain("Proceed."); expect(readFileSync(join(home, "invocations.txt"), "utf8").trim().split("\n")).toHaveLength(1); const pending = await runHarnessBridge( { operation: "pending", harness: "codex", harnessSessionId: "codex-session-1" }, home, ); expect(pending.operation).toBe("pending"); if (pending.operation !== "pending") throw new Error("expected pending response"); expect(pending.deliveries).toEqual([]); }); });