Skip to content
Source
Sign inSign up
samwillis/neonbricks
Open History to see the last commit

ai-lifecycle.test.ts

61 lines2.2 KB

1import { beforeEach, describe, expect, it, vi } from "vitest";
2const mock = vi.hoisted(() => ({
3 receive: (_snapshot: any) => {},
4 off: vi.fn(),
5 unsubscribe: vi.fn(),
6 close: vi.fn(),
7 subscribe: vi.fn(),
8}));
9vi.mock("../src/server/live", () => ({
10 trustedRealtime: () => ({ subscribe: mock.subscribe, close: mock.close }),
11}));
12import { watchCancellation } from "../src/server/ai-lifecycle";
13beforeEach(() => {
14 vi.clearAllMocks();
15 mock.subscribe.mockResolvedValue({
16 onChange: (receive: any) => {
17 mock.receive = receive;
18 return mock.off;
19 },
20 unsubscribe: mock.unsubscribe,
21 getSnapshot: () => ({ status: "connecting", data: [] }),
22 });
23});
24describe("Trusted AI cancellation subscription", () => {
25 it("ignores transport failure and aborts only on an authoritative terminal state", async () => {
26 const controller = new AbortController();
27 const stop = await watchCancellation("fixture", controller);
28 for (const status of ["connecting", "stale", "error", "closed"]) {
29 mock.receive({ status, data: [{ id: "fixture", status: "cancelled" }] });
30 expect(controller.signal.aborted).toBe(false);
31 }
32 mock.receive({
33 status: "live",
34 data: [{ id: "fixture", status: "repairing" }],
35 });
36 expect(controller.signal.aborted).toBe(false);
37 mock.receive({
38 status: "live",
39 data: [{ id: "fixture", status: "cancelled" }],
40 });
41 expect(controller.signal.aborted).toBe(true);
42 stop();
43 expect(mock.off).toHaveBeenCalledOnce();
44 expect(mock.unsubscribe).toHaveBeenCalledOnce();
45 expect(mock.close).toHaveBeenCalledOnce();
46 });
47 it("ignores callbacks after disposal", async () => {
48 const controller = new AbortController();
49 const stop = await watchCancellation("fixture", controller);
50 stop();
51 mock.receive({ status: "live", data: [] });
52 expect(controller.signal.aborted).toBe(false);
53 });
54 it("closes the socket when subscription setup fails", async () => {
55 mock.subscribe.mockRejectedValueOnce(new Error("Unavailable"));
56 await expect(
57 watchCancellation("fixture", new AbortController()),
58 ).rejects.toThrow("Unavailable");
59 expect(mock.close).toHaveBeenCalledOnce();
60 });
61});