repositories / dotfiles

dotfiles

bugabingas dorkfiles

owned by bugabinga

pi/agent/extensions/diff-review/scripts/browser-regression.ts

Raw
File outline
import { execFile, spawn, type ChildProcess } from "node:child_process";
import { mkdtemp, rm, stat, 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 { collectDiff } from "../git.js";
import { parseArgs } from "../args.js";
import { startReviewServer, type ReviewServer } from "../server.js";

const execFileAsync = promisify(execFile);
const EXT_DIR = dirname(dirname(fileURLToPath(import.meta.url)));
const CHROME_COMMANDS = ["google-chrome-stable", "google-chrome", "chromium", "chromium-browser"];
const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));

type CdpClient = Awaited<ReturnType<typeof cdp>>;

async function main() {
  await assertBundleSplit();
  const chrome = process.env.CHROME ?? await findChrome();
  if (!chrome) {
    console.log("browser-regression: bundle checks ok; no Chrome/Chromium found, skipping CDP tests");
    return;
  }
  await testSearchNavigationAndInputs(chrome);
  console.log("browser-regression: bundle split, search navigation, Escape, notes autogrow, content-visibility ok");
}

async function assertBundleSplit() {
  await execFileAsync("bun", ["run", "build"], { cwd: EXT_DIR, maxBuffer: 20 * 1024 * 1024 });
  const app = await stat(join(EXT_DIR, "static", "app.js"));
  if (app.size > 128 * 1024) throw new Error(`expected split app.js <=128 KiB, got ${app.size} bytes`);
}

async function testSearchNavigationAndInputs(chrome: string) {
  const repo = await mkdtemp(join(tmpdir(), "diff-review-regression-repo-"));
  const profile = await mkdtemp(join(tmpdir(), "diff-review-regression-chrome-"));
  const port = 10_500 + Math.floor(Math.random() * 1000);
  let browser: ChildProcess | undefined;
  let server: ReviewServer | undefined;
  try {
    await prepareMultiHunkRepo(repo);
    server = await startReviewServer({ diff: await collectDiff(repo, parseArgs("")), state: { round: 0, findings: [], rounds: [] }, round: 1, timeoutMs: 45_000 });
    browser = spawn(chrome, ["--headless=new", "--no-sandbox", `--remote-debugging-port=${port}`, `--user-data-dir=${profile}`, "--window-size=1200,800", server.url], { stdio: "ignore" });
    const tabInfo = await tab(port);
    const client = await cdp(tabInfo.webSocketDebuggerUrl);
    try {
      await client.call("Runtime.enable");
      await waitForReady(client);
      await assertContentVisibility(client);
      await assertNotesAutogrow(client);
      await assertSearchLineMappingEscapeAndHorizontalScroll(client);
    } finally {
      client.close();
    }
  } finally {
    browser?.kill();
    server?.close("shutdown");
    await rm(repo, { recursive: true, force: true });
    await rm(profile, { recursive: true, force: true });
  }
}

async function prepareMultiHunkRepo(repo: string) {
  await git(repo, ["init", "-q"]);
  await git(repo, ["config", "user.email", "regression@example.invalid"]);
  await git(repo, ["config", "user.name", "Regression"]);
  const lines = Array.from({ length: 220 }, (_, i) => `line ${i + 1}`);
  lines[8] = `needle at nine ${"n".repeat(260)}`;
  lines[191] = `needle at one ninety two ${"x".repeat(260)}`;
  await writeFile(join(repo, "a.txt"), `${lines.join("\n")}\n`);
  await git(repo, ["add", "a.txt"]);
  await git(repo, ["commit", "-qm", "initial"]);
  lines[8] = `needle at nine changed ${"m".repeat(260)}`;
  lines[191] = `needle at one ninety two changed ${"y".repeat(260)}`;
  await writeFile(join(repo, "a.txt"), `${lines.join("\n")}\n`);
}

async function waitForReady(client: CdpClient) {
  for (let i = 0; i < 120; i++) {
    const ready = await client.eval(`document.querySelector('#status')?.textContent === 'Ready' && !!document.querySelector('diffs-container')`);
    if (ready) return;
    await sleep(250);
  }
  throw new Error("browser did not reach Ready state");
}

async function assertContentVisibility(client: CdpClient) {
  const value = await client.eval(`getComputedStyle(document.querySelector('.file-section')).contentVisibility`);
  if (value !== "auto") throw new Error(`content-visibility not active: ${value}`);
}

async function assertNotesAutogrow(client: CdpClient) {
  const result = await client.eval(`(async () => {
    const wait = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
    const notes = document.querySelector('#notes');
    const before = notes.getBoundingClientRect().height;
    notes.value = Array.from({ length: 22 }, (_, i) => 'note line ' + i).join('\\n');
    notes.dispatchEvent(new Event('input', { bubbles: true }));
    await wait(80);
    const after = notes.getBoundingClientRect().height;
    return { before, after, overflowY: getComputedStyle(notes).overflowY };
  })()`);
  if (!(result.after > result.before)) throw new Error(`notes did not grow: ${JSON.stringify(result)}`);
  if (result.overflowY !== "hidden") throw new Error(`notes should avoid internal scrollbar: ${JSON.stringify(result)}`);
}

async function assertSearchLineMappingEscapeAndHorizontalScroll(client: CdpClient) {
  const result = await client.eval(`(async () => {
    const wait = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
    const input = document.querySelector('#search');
    input.focus();
    input.value = 'needle';
    input.dispatchEvent(new Event('input', { bubbles: true }));
    for (let i = 0; i < 80; i++) {
      await wait(100);
      const results = [...document.querySelectorAll('.search-result')].map((node) => node.textContent || '');
      if (results.some((text) => text.includes(':192 +'))) break;
    }
    const resultTexts = [...document.querySelectorAll('.search-result')].map((node) => node.textContent || '');
    const target = [...document.querySelectorAll('.search-result')].find((node) => (node.textContent || '').includes(':192 +'));
    const root = document.querySelector('[data-file-section="a.txt"] diffs-container').shadowRoot;
    for (const code of root.querySelectorAll('code[data-code]')) code.scrollLeft = 420;
    const beforeScrollLeft = [...root.querySelectorAll('code[data-code]')].map((code) => code.scrollLeft);
    target?.click();
    await wait(700);
    const highlighted = [...root.querySelectorAll('.search-highlight[data-line]')].map((line) => line.getAttribute('data-line'));
    const afterScrollLeft = [...root.querySelectorAll('code[data-code]')].map((code) => code.scrollLeft);
    input.dispatchEvent(new KeyboardEvent('keydown', { key: 'Escape', bubbles: true, cancelable: true }));
    await wait(100);
    return {
      resultTexts: resultTexts.slice(0, 8),
      highlighted,
      beforeScrollLeft,
      afterScrollLeft,
      popupHidden: document.querySelector('#search-results').hidden,
      searchValue: input.value,
    };
  })()`);
  if (!result.resultTexts.some((text: string) => text.includes(":9 +")) || !result.resultTexts.some((text: string) => text.includes(":192 +"))) {
    throw new Error(`search results missing real file line numbers: ${JSON.stringify(result.resultTexts)}`);
  }
  if (!result.highlighted.includes("192")) throw new Error(`search did not highlight line 192: ${JSON.stringify(result)}`);
  if (result.beforeScrollLeft.some((value: number, i: number) => result.afterScrollLeft[i] !== value)) {
    throw new Error(`search jump changed horizontal scroll: ${JSON.stringify(result)}`);
  }
  if (!result.popupHidden || result.searchValue !== "needle") throw new Error(`Escape did not close popup and preserve value: ${JSON.stringify(result)}`);
}

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

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

async function tab(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; webSocketDebuggerUrl: string }>;
      const page = tabs.find((entry) => entry.type === "page");
      if (page) return page;
    } catch {}
    await sleep(250);
  }
  throw new Error("Chrome CDP tab not available");
}

async function cdp(url: string) {
  let id = 0;
  const ws = new WebSocket(url);
  const pending = new Map<number, (message: any) => void>();
  ws.onmessage = (event) => {
    const message = JSON.parse(String(event.data));
    pending.get(message.id)?.(message);
    pending.delete(message.id);
  };
  await new Promise<void>((resolve) => { ws.onopen = () => resolve(); });
  return {
    call(method: string, params: Record<string, unknown> = {}) {
      return new Promise<any>((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(JSON.stringify(result.result.exceptionDetails));
      return result.result?.result?.value;
    },
    close() { ws.close(); },
  };
}

main().catch((err) => {
  console.error(err);
  process.exit(1);
});