import path from "node:path"; import { afterEach, describe, expect, it } from "vitest"; import WebSocket from "ws"; import { createTestSession, type TestSession } from "../../../test/harness"; import { createUiRuntime, type UiRuntime } from "../runtime"; const runtimes: Array<{ stop(reason: string): Promise }> = []; let t: TestSession | undefined; describe("ui cleanup", () => { afterEach(async () => { while (runtimes.length) await runtimes.pop()?.stop("test cleanup"); t?.dispose(); t = undefined; }); it("stops runtime idempotently after socket close", async () => { const sent: unknown[] = []; const runtime = await createUiRuntime({ sessionLabel: "ui: cleanup", address: "127.0.0.1", cwd: "C:/repo", openBrowser: false, sessionManager: fakeSessionManager(), startRpcBridge: ({ sessionPath }) => fakeRpc(sent, sessionPath), }); runtimes.push(runtime); const socket = await connectRuntimeSocket(runtime); socket.close(); await new Promise((resolve) => setTimeout(resolve, 20)); await runtime.stop("first"); await runtime.stop("second"); expect(runtime.status().active).toBe(false); expect(sent).toContainEqual({ type: "close", reason: "first" }); }); it("/ui off removes terminal widget even when inactive", async () => { const extensionPath = path.resolve(import.meta.dirname, "../index.ts"); t = await createTestSession({ extensions: [extensionPath] }); const command = t.session.extensionRunner.extensions[0].commands.get("ui"); expect(command).toBeDefined(); await command?.handler( "off", t.session.extensionRunner.createCommandContext(), ); expect(t.events.uiCallsFor("setWidget").at(-1)?.args).toEqual([ "ui", undefined, ]); }); }); async function connectRuntimeSocket(runtime: UiRuntime): Promise { const url = new URL(runtime.status().url ?? ""); const response = await fetch(url); const cookie = response.headers.get("set-cookie") ?? ""; const socketUrl = new URL("/ws", url); socketUrl.protocol = "ws:"; const socket = new WebSocket(socketUrl, { headers: { cookie } }); await new Promise((resolve) => socket.once("open", resolve)); return socket; } function fakeSessionManager() { return { getLeafId: () => "leaf", createBranchedSession: () => ({ path: "C:/repo/.pi/sessions/ui.json" }), }; } function fakeRpc(sent: unknown[], sessionPath: string) { return { state: () => "connected", sessionPath, send(request: unknown) { sent.push(request); return Promise.resolve({ type: "response", success: true }); }, close(reason: string) { sent.push({ type: "close", reason }); return Promise.resolve(); }, }; }