import { describe, expect, test, mock } from "bun:test"; import { startServer } from "../start-server.ts"; import type { Runtime, Action, TurnHandle } from "@gizmo-ai/runtime"; describe("startServer", () => { test("tracks run history from runtime action subscription", async () => { let state: Record = { execution: { id: null, state: "idle", turnIds: [] }, }; let actionListener: ((action: Action) => void) | null = null; const runtime: Runtime, Action> = { getState: () => state, dispatch: mock(() => {}), execute: (_input: string): TurnHandle => ({ included: Promise.resolve(), completed: Promise.resolve({ status: "completed" }), cancel: () => {}, }), subscribe: () => () => {}, subscribeToActions: (listener) => { actionListener = listener as (action: Action) => void; return () => { actionListener = null; }; }, dispatchToReducer: mock(() => {}), resetState: mock(() => {}), getPluginGraph: () => ({ nodes: [], edges: [] }), getPlugins: () => [], }; const originalServe = Bun.serve; const stop = mock(() => {}); (Bun as unknown as { serve: typeof Bun.serve }).serve = mock(() => ({ stop, })) as unknown as typeof Bun.serve; try { const server = startServer(runtime, { port: 0 }); state = { execution: { id: "exec-1", state: "pending", turnIds: ["turn-1"] }, }; if (!actionListener) { throw new Error("Expected runtime.subscribeToActions to register listener"); } (actionListener as (action: Action) => void)({ type: "RUNTIME_EXECUTION_STARTED", payload: { executionId: "exec-1", turnId: "turn-1", input: "hello", }, }); state = { execution: { id: "exec-1", state: "completed", turnIds: ["turn-1"] }, }; (actionListener as (action: Action) => void)({ type: "RUNTIME_EXECUTION_COMPLETED", payload: { executionId: "exec-1", }, }); const response = await server.app.request("/runs"); expect(response.status).toBe(200); const body = await response.json() as { runs: Array<{ executionId: string; status: string }> }; expect(body.runs).toHaveLength(1); expect(body.runs[0]).toEqual( expect.objectContaining({ executionId: "exec-1", status: "completed", }) ); server.close(); expect(stop).toHaveBeenCalled(); } finally { (Bun as unknown as { serve: typeof Bun.serve }).serve = originalServe; } }); });