import { execFile, spawn, type ChildProcess } 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 { promisify } from "node:util"; import { fileURLToPath } from "node:url"; import { collectDiff } from "../git.js"; import { parseArgs } from "../args.js"; import { startReviewServer } from "../server.js"; const execFileAsync = promisify(execFile); const EXT_DIR = dirname(dirname(fileURLToPath(import.meta.url))); await execFileAsync("bun", ["run", "build"], { cwd: EXT_DIR, maxBuffer: 1024 * 1024 * 10 }); await assertStaticBundle(); await smokeRealBrowser(); async function assertStaticBundle() { const index = await readFile(join(EXT_DIR, "static", "index.html"), "utf8").catch(() => ""); const app = await readFile(join(EXT_DIR, "static", "app.js"), "utf8").catch(() => ""); const manifest = await readFile(join(EXT_DIR, "static", "manifest.json"), "utf8").catch(() => ""); 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) { console.log("smoke: static bundle ok; no Chrome/Chromium found, skipping real browser smoke"); return; } const repo = await mkdtemp(join(tmpdir(), "diff-review-smoke-repo-")); const profile = await mkdtemp(join(tmpdir(), "diff-review-smoke-chrome-")); const debugPort = 9400 + Math.floor(Math.random() * 1000); let server: Awaited> | undefined; let chromeProcess: ChildProcess | undefined; try { 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"); const diff = await collectDiff(repo, parseArgs("")); server = await startReviewServer({ diff, state: { round: 0, findings: [], rounds: [] }, round: 1, timeoutMs: 30_000 }); chromeProcess = spawn(chrome, [ "--headless=new", "--disable-gpu", "--no-sandbox", "--disable-dev-shm-usage", `--remote-debugging-port=${debugPort}`, `--user-data-dir=${profile}`, "--window-size=1400,900", server.url, ], { stdio: "ignore" }); const tab = await waitForTab(debugPort); const client = await connectCdp(tab.webSocketDebuggerUrl); try { await client.call("Runtime.enable"); await sleep(5000); const browser = await client.eval(`(async () => { await document.fonts.ready; const dc = document.querySelector('diffs-container'); const sr = dc?.shadowRoot; const addLine1 = sr?.querySelector('[data-additions] [data-line="1"]'); const addLine2 = sr?.querySelector('[data-additions] [data-line="2"]'); if (!addLine1 || !addLine2) throw new Error('addition lines not rendered'); document.querySelector('#theme-mode').value = 'light'; document.querySelector('#theme-mode').dispatchEvent(new Event('change', { bubbles: true })); addLine1.dispatchEvent(new MouseEvent('click', { bubbles: true, composed: true, clientX: 900, clientY: 350 })); await new Promise((r) => setTimeout(r, 200)); let comment = document.querySelector('#comment'); comment.value = 'remove me'; comment.dispatchEvent(new Event('input', { bubbles: true })); document.querySelector('#add').click(); await new Promise((r) => setTimeout(r, 350)); addLine2.dispatchEvent(new MouseEvent('click', { bubbles: true, composed: true, clientX: 900, clientY: 370 })); await new Promise((r) => setTimeout(r, 200)); comment = document.querySelector('#comment'); comment.value = 'smoke finding'; comment.dispatchEvent(new Event('input', { bubbles: true })); document.querySelector('#add').click(); await new Promise((r) => setTimeout(r, 500)); document.querySelector('.remove-finding').click(); await new Promise((r) => setTimeout(r, 200)); const added = document.querySelector('#findings').innerText; const failedResources = performance.getEntriesByType('resource') .filter((entry) => 'responseStatus' in entry && entry.responseStatus >= 400) .map((entry) => [entry.name, entry.responseStatus]); const fontLoaded = document.fonts.check('12px "Nugu Code Nerd"'); document.querySelector('#submit').click(); return { added, failedResources, fontLoaded, theme: document.documentElement.dataset.theme, body: document.body.innerText }; })()`); if (!browser.added.includes("smoke finding") || browser.added.includes("remove me")) throw new Error("finding add/remove flow failed in browser UI"); if (!browser.fontLoaded) throw new Error("Nugu Code Nerd font did not load"); if (browser.theme !== "light") throw new Error("theme selector did not apply light mode"); if (browser.failedResources.length > 0) throw new Error(`resource failures: ${JSON.stringify(browser.failedResources)}`); const result = await server.result; if (result.type !== "submit" || result.findings.length !== 1 || result.findings[0]?.comment !== "smoke finding") throw new Error("server did not receive expected submitted finding"); console.log("smoke: real browser loaded UI, switched theme, loaded font, added/removed finding, submitted review"); } finally { client.close(); } } finally { chromeProcess?.kill(); server?.close("timeout"); await rm(repo, { recursive: true, force: true }); await rm(profile, { recursive: true, force: true }); } } async function waitForTab(port: number): Promise<{ webSocketDebuggerUrl: string }> { for (let i = 0; i < 80; i++) { try { const tabs = await fetch(`http://127.0.0.1:${port}/json/list`).then((res) => res.json()) as Array<{ type: string; url: string; webSocketDebuggerUrl: string }>; const tab = tabs.find((candidate) => candidate.type === "page" && candidate.url.startsWith("http://127.0.0.1")); if (tab) return tab; } catch {} await sleep(250); } throw new Error("Chrome CDP tab not found"); } async function connectCdp(url: string) { let id = 0; const ws = new WebSocket(url); const pending = new Map void>(); ws.onmessage = (event) => { const message = JSON.parse(String(event.data)); if (message.id && pending.has(message.id)) { pending.get(message.id)!(message); pending.delete(message.id); } }; await new Promise((resolve, reject) => { ws.onopen = () => resolve(); ws.onerror = reject; }); return { call(method: string, params: Record = {}) { return new Promise((resolve) => { const callId = ++id; pending.set(callId, resolve); ws.send(JSON.stringify({ id: callId, method, params })); }); }, async eval(expression: string) { const result = await this.call("Runtime.evaluate", { expression, returnByValue: true, awaitPromise: true }); if (result.result.exceptionDetails) throw new Error(result.result.exceptionDetails.text ?? "browser eval failed"); return result.result.result.value; }, close() { ws.close(); }, }; } async function findChrome() { for (const command of ["google-chrome-stable", "google-chrome", "chromium", "chromium-browser"]) { try { await execFileAsync(command, ["--version"]); return command; } catch {} } return undefined; } async function git(cwd: string, args: string[]) { await execFileAsync("git", args, { cwd }); } function sleep(ms: number) { return new Promise((resolve) => setTimeout(resolve, ms)); }