repositories / pi-ext

pi-ext

bugabingas pi extensions

owned by bugabinga

Harden ui cleanup

f7267a88407c2938ad097d1c272837e84a529188

Oliver Krylow <o.krylow@isp-insoft.de> ·

unsigned

Browse filesCompare with HEAD

Changed files (1)

+82 / −0 text lines

Diff layout

extensions/ui/__tests__/cleanup.test.ts

Added
new file mode 100644

+82 / −0 text lines

1import path from "node:path";
2import { afterEach, describe, expect, it } from "vitest";
3import { createTestSession, type TestSession } from "../../../test/harness";
4import { createUiRuntime } from "../runtime";
5
6const runtimes: Array<{ stop(reason: string): Promise<void> }> = [];
7let t: TestSession | undefined;
8
9describe("ui cleanup", () => {
10 afterEach(async () => {
11 while (runtimes.length) await runtimes.pop()?.stop("test cleanup");
12 t?.dispose();
13 t = undefined;
14 });
16 it("stops runtime idempotently after socket close", async () => {
17 const sent: unknown[] = [];
18 const runtime = await createUiRuntime({
19 sessionLabel: "ui: cleanup",
20 address: "127.0.0.1",
21 cwd: "C:/repo",
22 openBrowser: false,
23 sessionManager: fakeSessionManager(),
24 startRpcBridge: ({ sessionPath }) => fakeRpc(sent, sessionPath),
25 });
26 runtimes.push(runtime);
27 const url = new URL(runtime.status().url ?? "");
28 const socketUrl = new URL("/ws", url);
29 socketUrl.protocol = "ws:";
30 socketUrl.searchParams.set("token", url.searchParams.get("token") ?? "");
31 const socket = new WebSocket(socketUrl);
32 await new Promise((resolve) =>
33 socket.addEventListener("open", resolve, { once: true }),
34 );
35 socket.close();
36 await new Promise((resolve) => setTimeout(resolve, 20));
38 await runtime.stop("first");
39 await runtime.stop("second");
40 expect(runtime.status().active).toBe(false);
41 expect(sent).toContainEqual({ type: "close", reason: "first" });
42 });
44 it("/ui off removes terminal widget even when inactive", async () => {
45 const extensionPath = path.resolve(import.meta.dirname, "../index.ts");
46 t = await createTestSession({ extensions: [extensionPath] });
47 const command = t.session.extensionRunner.extensions[0].commands.get("ui");
48 expect(command).toBeDefined();
50 await command?.handler(
51 "off",
52 t.session.extensionRunner.createCommandContext(),
53 );
55 expect(t.events.uiCallsFor("setWidget").at(-1)?.args).toEqual([
56 "ui",
57 undefined,
58 ]);
59 });
60});
62function fakeSessionManager() {
63 return {
64 getLeafId: () => "leaf",
65 createBranchedSession: () => ({ path: "C:/repo/.pi/sessions/ui.json" }),
66 };
67}
69function fakeRpc(sent: unknown[], sessionPath: string) {
70 return {
71 state: () => "connected",
72 sessionPath,
73 send(request: unknown) {
74 sent.push(request);
75 return Promise.resolve({ type: "response", success: true });
76 },
77 close(reason: string) {
78 sent.push({ type: "close", reason });
79 return Promise.resolve();
80 },
81 };
82}