repositories / pi-ext

pi-ext

bugabingas pi extensions

owned by bugabinga

extensions/diff-review/scripts/smoke-browser.ts

Raw
File outline
import { type ChildProcess, execFile, spawn } from "node:child_process";
import { mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
import { tmpdir } from "node:os";
import { dirname, join } from "node:path";
import { fileURLToPath } from "node:url";
import { promisify } from "node:util";
import { parseArgs } from "../args.js";
import { collectDiff } from "../git.js";
import { startReviewServer } from "../server.js";
import type { BrowserResult } from "../types.js";

const execFileAsync = promisify(execFile);
const EXT_DIR = dirname(dirname(fileURLToPath(import.meta.url)));
const BUILD_BUFFER_BYTES = 10 * 1024 * 1024;
const REVIEW_TIMEOUT_MS = 30_000;
const DEBUG_PORT_BASE = 9400;
const DEBUG_PORT_SPAN = 1000;
const TAB_RETRIES = 80;
const TAB_POLL_MS = 250;
const BROWSER_BOOT_MS = 5_000;
const CHROME_COMMANDS = [
	"google-chrome-stable",
	"google-chrome",
	"chromium",
	"chromium-browser",
];

async function main() {
	await execFileAsync("bun", ["run", "build"], {
		cwd: EXT_DIR,
		maxBuffer: BUILD_BUFFER_BYTES,
	});
	await assertStaticBundle();
	await smokeRealBrowser();
}

async function assertStaticBundle() {
	const [index, app, manifest] = await Promise.all([
		readText(join(EXT_DIR, "static", "index.html")),
		readText(join(EXT_DIR, "static", "app.js")),
		readText(join(EXT_DIR, "static", "manifest.json")),
	]);
	if (!index || !app || !manifest)
		throw new Error("static browser bundle missing; run bun run build");
	if (!index.includes("/static/app.js"))
		throw new Error("static/index.html does not load /static/app.js");
	JSON.parse(manifest);
}

async function smokeRealBrowser() {
	const chrome = process.env.CHROME ?? (await findChrome());
	if (!chrome)
		return console.log(
			"smoke: static bundle ok; no Chrome/Chromium found, skipping real browser smoke",
		);

	const ctx = await createSmokeContext(chrome);
	try {
		await prepareRepo(ctx.repo);
		const running = await startSmokeServer(ctx.repo);
		ctx.server = running.server;
		ctx.submitted = running.submitted;
		ctx.chrome = launchChrome(
			chrome,
			ctx.profile,
			ctx.debugPort,
			ctx.server.url,
		);
		await exerciseBrowser(ctx.debugPort, ctx.server, ctx.submitted);
		console.log(
			"smoke: real browser loaded UI, switched theme, loaded font, added/removed finding, submitted review",
		);
	} finally {
		await cleanup(ctx);
	}
}

type SmokeContext = {
	repo: string;
	profile: string;
	debugPort: number;
	server?: Awaited<ReturnType<typeof startReviewServer>>;
	submitted?: Promise<Extract<BrowserResult, { type: "submit" }>>;
	chrome?: ChildProcess;
};

async function createSmokeContext(_chrome: string): Promise<SmokeContext> {
	return {
		repo: await mkdtemp(join(tmpdir(), "diff-review-smoke-repo-")),
		profile: await mkdtemp(join(tmpdir(), "diff-review-smoke-chrome-")),
		debugPort: DEBUG_PORT_BASE + Math.floor(Math.random() * DEBUG_PORT_SPAN),
	};
}

async function prepareRepo(repo: string) {
	await git(repo, ["init", "-q"]);
	await git(repo, ["config", "user.email", "smoke@example.invalid"]);
	await git(repo, ["config", "user.name", "smoke"]);
	await writeFile(join(repo, "a.ts"), "const a = 1;\n");
	await git(repo, ["add", "a.ts"]);
	await git(repo, ["commit", "-qm", "init"]);
	await writeFile(join(repo, "a.ts"), "const a = 2;\nconst b = 3;\n");
}

async function startSmokeServer(repo: string) {
	const diff = await collectDiff(repo, parseArgs(""));
	let resolveSubmit!: (
		result: Extract<BrowserResult, { type: "submit" }>,
	) => void;
	const submitted = new Promise<Extract<BrowserResult, { type: "submit" }>>(
		(resolve) => {
			resolveSubmit = resolve;
		},
	);
	const server = await startReviewServer({
		diff,
		state: { round: 0, findings: [], rounds: [] },
		round: 1,
		timeoutMs: REVIEW_TIMEOUT_MS,
		onSubmit: resolveSubmit,
	});
	return { server, submitted };
}

function launchChrome(
	chrome: string,
	profile: string,
	debugPort: number,
	url: string,
) {
	return spawn(
		chrome,
		[
			"--headless=new",
			"--disable-gpu",
			"--no-sandbox",
			"--disable-dev-shm-usage",
			`--remote-debugging-port=${debugPort}`,
			`--user-data-dir=${profile}`,
			"--window-size=1400,900",
			url,
		],
		{ stdio: "ignore" },
	);
}

async function exerciseBrowser(
	debugPort: number,
	server: Awaited<ReturnType<typeof startReviewServer>>,
	submitted: Promise<Extract<BrowserResult, { type: "submit" }>>,
) {
	const tab = await waitForTab(debugPort);
	const client = await connectCdp(tab.webSocketDebuggerUrl);
	try {
		await client.call("Runtime.enable");
		await sleep(BROWSER_BOOT_MS);
		assertBrowserSmokeResult(await client.eval(BROWSER_SCRIPT));
		const result = await submitted;
		if (
			result.findings.length !== 1 ||
			result.findings[0]?.comment !== "smoke finding"
		)
			throw new Error("server did not receive expected submitted finding");
		server.close("browser");
	} finally {
		client.close();
	}
}

const BROWSER_SCRIPT = String.raw`(async () => {
	const wait = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
	const must = (selector, root = document) => {
		const el = root.querySelector(selector);
		if (!el) throw new Error('missing ' + selector);
		return el;
	};
	const clickLine = async (line, y) => {
		line.dispatchEvent(new MouseEvent('click', { bubbles: true, composed: true, clientX: 900, clientY: y }));
		await wait(200);
	};
	const addFinding = async (selector, commentText, y) => {
		const shadowRoot = must('diffs-container').shadowRoot;
		await clickLine(must(selector, shadowRoot), y);
		const comment = must('#comment');
		comment.value = commentText;
		comment.dispatchEvent(new Event('input', { bubbles: true }));
		must('#add').click();
		await wait(400);
	};

	await document.fonts.ready;
	const themeMode = must('#theme-mode');
	themeMode.value = 'light';
	themeMode.dispatchEvent(new Event('change', { bubbles: true }));

	await addFinding('[data-additions] [data-line="1"]', 'remove me', 350);
	await addFinding('[data-additions] [data-line="2"]', 'smoke finding', 370);
	must('.remove-finding').click();
	await wait(200);

	const failedResources = performance.getEntriesByType('resource')
		.filter((entry) => 'responseStatus' in entry && entry.responseStatus >= 400)
		.map((entry) => [entry.name, entry.responseStatus]);
	const result = {
		findingsText: must('#findings').innerText,
		failedResources,
		fontLoaded: document.fonts.check('12px "JetBrains Mono Nerd"'),
		theme: document.documentElement.dataset.theme,
	};
	must('#submit').click();
	return result;
})()`;

type BrowserSmokeResult = {
	findingsText: string;
	failedResources: Array<[string, number]>;
	fontLoaded: boolean;
	theme: string;
};

function assertBrowserSmokeResult(
	value: unknown,
): asserts value is BrowserSmokeResult {
	if (!isRecord(value))
		throw new Error("browser smoke returned invalid result");
	if (typeof value.findingsText !== "string")
		throw new Error("browser smoke missing findings text");
	if (
		!value.findingsText.includes("smoke finding") ||
		value.findingsText.includes("remove me")
	)
		throw new Error("finding add/remove flow failed in browser UI");
	if (value.fontLoaded !== true)
		throw new Error("JetBrains Mono Nerd font did not load");
	if (value.theme !== "light")
		throw new Error("theme selector did not apply light mode");
	if (Array.isArray(value.failedResources) && value.failedResources.length > 0)
		throw new Error(
			`resource failures: ${JSON.stringify(value.failedResources)}`,
		);
}

async function cleanup(ctx: SmokeContext) {
	ctx.chrome?.kill();
	ctx.server?.close("timeout");
	await Promise.all([
		rm(ctx.repo, { recursive: true, force: true }),
		rm(ctx.profile, { recursive: true, force: true }),
	]);
}

async function waitForTab(
	port: number,
): Promise<{ webSocketDebuggerUrl: string }> {
	for (let i = 0; i < TAB_RETRIES; i++) {
		const tab = await localChromeTabs(port).catch(() => undefined);
		if (tab) return tab;
		await sleep(TAB_POLL_MS);
	}
	throw new Error("Chrome CDP tab not found");
}

async function localChromeTabs(port: number) {
	const tabs = (await fetch(`http://127.0.0.1:${port}/json/list`).then((res) =>
		res.json(),
	)) as Array<{ type: string; url: string; webSocketDebuggerUrl: string }>;
	return tabs.find(
		(candidate) =>
			candidate.type === "page" && candidate.url.startsWith("http://127.0.0.1"),
	);
}

type CdpClient = {
	call(method: string, params?: Record<string, unknown>): Promise<CdpResponse>;
	eval(expression: string): Promise<unknown>;
	close(): void;
};
type CdpResponse = {
	id?: number;
	result?: {
		result?: { value?: unknown };
		exceptionDetails?: { text?: string };
	};
	error?: { message?: string };
};

async function connectCdp(url: string): Promise<CdpClient> {
	let id = 0;
	const ws = new WebSocket(url);
	const pending = new Map<number, (value: CdpResponse) => void>();
	ws.onmessage = (event) => receiveCdpMessage(pending, event.data);
	await new Promise<void>((resolve, reject) => {
		ws.onopen = () => resolve();
		ws.onerror = reject;
	});
	return {
		call(method: string, params: Record<string, unknown> = {}) {
			return new Promise<CdpResponse>((resolve) => {
				const callId = ++id;
				pending.set(callId, resolve);
				ws.send(JSON.stringify({ id: callId, method, params }));
			});
		},
		async eval(expression: string) {
			const response = await this.call("Runtime.evaluate", {
				expression,
				returnByValue: true,
				awaitPromise: true,
			});
			if (response.error)
				throw new Error(
					response.error.message ?? "browser eval protocol error",
				);
			if (response.result?.exceptionDetails)
				throw new Error(
					response.result.exceptionDetails.text ?? "browser eval failed",
				);
			return response.result?.result?.value;
		},
		close() {
			ws.close();
		},
	};
}

function receiveCdpMessage(
	pending: Map<number, (value: CdpResponse) => void>,
	data: unknown,
) {
	const message = JSON.parse(String(data)) as CdpResponse;
	if (!message.id) return;
	pending.get(message.id)?.(message);
	pending.delete(message.id);
}

async function findChrome() {
	for (const command of CHROME_COMMANDS) {
		try {
			await execFileAsync(command, ["--version"]);
			return command;
		} catch {}
	}
	return undefined;
}

async function git(cwd: string, args: string[]) {
	await execFileAsync("git", args, { cwd });
}

async function readText(path: string) {
	return readFile(path, "utf8").catch(() => "");
}

function sleep(ms: number) {
	return new Promise((resolve) => setTimeout(resolve, ms));
}

function isRecord(value: unknown): value is Record<string, unknown> {
	return !!value && typeof value === "object" && !Array.isArray(value);
}

await main();