repositories / pi-ext

pi-ext

bugabingas pi extensions

owned by bugabinga

extensions/ui/__tests__/runtime.test.ts

Raw
File outline
import { EventEmitter } from "node:events";
import { mkdtemp, readFile, rm } from "node:fs/promises";
import { tmpdir } from "node:os";
import path from "node:path";
import { Writable } from "node:stream";
import { afterEach, describe, expect, it } from "vitest";
import WebSocket from "ws";
import { openBrowser, openerCandidates } from "../open";
import { createUiRuntime, normalizeRpcEvent, type UiRuntime } from "../runtime";

describe("ui browser opener", () => {
	it("uses platform openers", () => {
		expect(
			openerCandidates("http://x", { platform: "win32", env: {} })[0],
		).toEqual({
			command: "explorer.exe",
			args: ["http://x"],
			windowsHide: true,
		});
		expect(
			openerCandidates("http://x", { platform: "darwin", env: {} })[0],
		).toEqual({
			command: "open",
			args: ["http://x"],
		});
		expect(
			openerCandidates("http://x", { platform: "linux", env: {} })[0],
		).toEqual({
			command: "xdg-open",
			args: ["http://x"],
		});
	});

	it("uses termux opener when available", () => {
		expect(
			openerCandidates("http://x", {
				platform: "linux",
				env: { TERMUX_VERSION: "1" },
			})[0],
		).toEqual({
			command: "termux-open-url",
			args: ["http://x"],
		});
	});

	it("can suppress auto-open for smoke harnesses", async () => {
		const previous = process.env.PI_UI_NO_AUTO_OPEN;
		process.env.PI_UI_NO_AUTO_OPEN = "1";
		try {
			await expect(openBrowser("http://127.0.0.1:9")).resolves.toBeUndefined();
		} finally {
			if (previous === undefined) delete process.env.PI_UI_NO_AUTO_OPEN;
			else process.env.PI_UI_NO_AUTO_OPEN = previous;
		}
	});
});

const runtimes: UiRuntime[] = [];

afterEach(async () => {
	await Promise.all(
		runtimes.splice(0).map((runtime) => runtime.stop("test cleanup")),
	);
});

describe("ui rpc event normalization", () => {
	it("drops unknown rpc startup chatter", () => {
		expect(
			normalizeRpcEvent({ type: "startup_log", message: "builtin-tools" }),
		).toBeUndefined();
	});

	it("uses accumulated assistant text for streaming updates", () => {
		expect(
			normalizeRpcEvent({
				type: "message_update",
				message: {
					role: "assistant",
					content: [{ type: "text", text: "Ready. What" }],
				},
				assistantMessageEvent: {
					type: "text_delta",
					contentIndex: 0,
					delta: " What",
				},
			}),
		).toEqual({
			type: "message",
			role: "assistant",
			text: "Ready. What",
			streamId: "assistant-stream",
		});
	});
});

describe("ui runtime", () => {
	it("starts, reports status, redraws QR, and stops", async () => {
		const runtime = await createUiRuntime({
			sessionLabel: "ui: test",
			address: "127.0.0.1",
			openBrowser: false,
		});
		runtimes.push(runtime);

		expect(runtime.status().active).toBe(true);
		expect(runtime.status().url).toMatch(/^http:\/\/127\.0\.0\.1:\d+\/?$/);
		expect(runtime.widgetLines().join("\n")).toContain("ui: test");

		await runtime.redrawQr();
		expect(runtime.widgetLines().join("\n")).toContain("mobile QR: /ui qr");

		await runtime.stop("test");
		expect(runtime.status().active).toBe(false);
	});

	it("writes smoke URL handoff only when requested", async () => {
		const dir = await mkdtemp(path.join(tmpdir(), "pi-ui-smoke-"));
		const file = path.join(dir, "url.txt");
		const previous = process.env.PI_UI_SMOKE_URL_FILE;
		process.env.PI_UI_SMOKE_URL_FILE = file;
		try {
			const runtime = await createUiRuntime({
				sessionLabel: "ui: test",
				address: "127.0.0.1",
				openBrowser: false,
			});
			runtimes.push(runtime);
			const value = await readFile(file, "utf8");
			expect(new URL(value.trim()).searchParams.has("token")).toBe(true);
			expect(value.trim()).not.toBe(runtime.status().url);
		} finally {
			if (previous === undefined) delete process.env.PI_UI_SMOKE_URL_FILE;
			else process.env.PI_UI_SMOKE_URL_FILE = previous;
			await rm(dir, { recursive: true, force: true });
		}
	});

	it("is safe to stop twice", async () => {
		const runtime = await createUiRuntime({
			sessionLabel: "ui: test",
			address: "127.0.0.1",
			openBrowser: false,
		});
		await runtime.stop("first");
		await runtime.stop("second");
		expect(runtime.status().active).toBe(false);
	});

	it("seeds an active branch and starts rpc when a session manager is provided", async () => {
		const sent: unknown[] = [];
		const runtime = await createUiRuntime({
			sessionLabel: "ui: test",
			address: "127.0.0.1",
			cwd: "C:/repo",
			openBrowser: false,
			sessionManager: fakeSessionManager(),
			startRpcBridge: ({ sessionPath, onState }) => {
				onState?.("connected");
				return fakeRpc(sent, sessionPath);
			},
		});
		runtimes.push(runtime);

		expect(runtime.status()).toMatchObject({
			active: true,
			rpcState: "connected",
			sessionPath: "C:/sessions/ui-branch.jsonl",
		});
		expect(runtime.widgetLines().join("\n")).toContain("rpc: connected");
	});

	it("forwards browser prompts to rpc and publishes stream events", async () => {
		const sent: unknown[] = [];
		const runtime = await createUiRuntime({
			sessionLabel: "ui: test",
			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.send(JSON.stringify({ type: "prompt", text: "hello" }));
		await new Promise((resolve) => setTimeout(resolve, 20));
		socket.close();

		expect(sent).toContainEqual(
			expect.objectContaining({ type: "prompt", message: "hello" }),
		);
	});

	it("routes bash and browser control actions to rpc", async () => {
		const sent: unknown[] = [];
		const runtime = await createUiRuntime({
			sessionLabel: "ui: test",
			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.send(JSON.stringify({ type: "prompt", text: "!!git status" }));
		socket.send(JSON.stringify({ type: "cycle_model" }));
		socket.send(JSON.stringify({ type: "abort" }));
		await new Promise((resolve) => setTimeout(resolve, 20));
		socket.close();

		expect(sent).toContainEqual({
			type: "bash",
			command: "git status",
			excludeFromContext: true,
		});
		expect(sent).toContainEqual({ type: "cycle_model" });
		expect(sent).toContainEqual({ type: "abort" });
	});

	it("attaches telemetry digest once to browser prompt", async () => {
		const sent: unknown[] = [];
		const runtime = await createUiRuntime({
			sessionLabel: "ui: test",
			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.send(
			JSON.stringify({
				type: "telemetry_batch",
				events: [{ type: "click", target: "SEND" }],
			}),
		);
		socket.send(JSON.stringify({ type: "prompt", text: "hello" }));
		socket.send(JSON.stringify({ type: "prompt", text: "again" }));
		await new Promise((resolve) => setTimeout(resolve, 20));
		socket.close();

		expect(sent).toContainEqual({
			type: "prompt",
			message: "Browser digest:\n- click SEND\n\nUser prompt:\nhello",
		});
		expect(sent).toContainEqual({ type: "prompt", message: "again" });
	});

	it("routes extension UI responses to rpc", async () => {
		const sent: unknown[] = [];
		const runtime = await createUiRuntime({
			sessionLabel: "ui: test",
			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.send(
			JSON.stringify({ type: "ui_response", id: "u1", value: "Allow" }),
		);
		await new Promise((resolve) => setTimeout(resolve, 20));
		socket.close();

		expect(sent).toContainEqual({
			type: "extension_ui_response",
			id: "u1",
			value: "Allow",
		});
	});
});

async function connectRuntimeSocket(runtime: UiRuntime): Promise<WebSocket> {
	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-1",
		getSessionFile: () => "C:/sessions/source.jsonl",
		createBranchedSession: () => "C:/sessions/ui-branch.jsonl",
	};
}

function fakeRpc(sent: unknown[], sessionPath: string) {
	return {
		child: Object.assign(new EventEmitter(), {
			stdout: new EventEmitter(),
			stderr: new EventEmitter(),
			stdin: new Writable({
				write(_chunk, _encoding, callback) {
					callback();
				},
			}),
			kill() {},
		}),
		sessionPath,
		send(request: unknown) {
			sent.push(request);
			return Promise.resolve({ type: "response", success: true, data: {} });
		},
		stderr: () => "",
		close: () => Promise.resolve(),
	};
}