repositories / dotfiles

dotfiles

bugabingas dorkfiles

owned by bugabinga

pi/agent/extensions/diff-review/browser/index.ts

Raw
import "./style.css";
import type { DiffLineAnnotation, FileDiff, FileDiffMetadata, SelectedLineRange } from "@pierre/diffs";
import type { FileTree, FileTreeRowDecorationRenderer, GitStatusEntry } from "@pierre/trees";
import { DIFF_FONT_CSS, TREE_CSS } from "./shadow-css.js";
import { NUGU_CODE_THEME, registerNuguCodeTheme } from "./theme.js";
import { HEARTBEAT_INTERVAL_MS, REVIEW_POLL_INTERVAL_MS } from "../constants.js";
import type { FindingDraft, ReviewCategory, ReviewPayload, ReviewSeverity, ReviewSide } from "../types.js";

type FindingMeta = { findingId: string; severity: ReviewSeverity; category: ReviewCategory; comment: string };
type ThemeMode = "system" | "dark" | "light";
type PaneSide = "left" | "right";
type ReviewSelection = { file: string; side: ReviewSide; startLine: number; endLine: number };
type ViewPoint = { x: number; y: number };
type SearchEntry = { file: string; side: "additions" | "deletions"; line: number; text: string };
type SearchMatch = SearchEntry & { matchStart: number; matchEnd: number };

type Elements = {
  app: HTMLElement;
  meta: HTMLElement;
  summary: HTMLElement;
  findingCount: HTMLElement;
  drawerCount: HTMLElement;
  tree: HTMLElement;
  diffs: HTMLElement;
  inlineFinding: HTMLElement;
  selection: HTMLElement;
  severity: HTMLSelectElement;
  severitySub: HTMLElement;
  category: HTMLSelectElement;
  categorySub: HTMLElement;
  comment: HTMLTextAreaElement;
  add: HTMLButtonElement;
  inlineCancel: HTMLButtonElement;
  findings: HTMLElement;
  notes: HTMLTextAreaElement;
  search: HTMLInputElement;
  searchClear: HTMLButtonElement;
  searchResults: HTMLElement;
  cancel: HTMLButtonElement;
  submit: HTMLButtonElement;
  status: HTMLElement;
  themeMode: HTMLSelectElement;
  leftSplitter: HTMLElement;
  rightSplitter: HTMLElement;
  toggleLeft: HTMLButtonElement;
  toggleRight: HTMLButtonElement;
};

const ROUTES = {
  review: "/api/review",
  heartbeat: "/api/heartbeat",
  cancel: "/api/cancel",
  validateFinding: "/api/finding/validate",
  submit: "/api/submit",
} as const;
const THEME_STORAGE_KEY = "diff-review-theme";
const LAYOUT_STORAGE_KEY = "diff-review-layout";
const REVIEW_CATEGORIES = ["bug", "style", "perf", "question"] as const satisfies readonly ReviewCategory[];
const REVIEW_SEVERITIES = ["high", "medium", "low"] as const satisfies readonly ReviewSeverity[];
const THEME_MODES = ["system", "dark", "light"] as const satisfies readonly ThemeMode[];
const SEVERITY_SUBS: Record<string, string> = { high: "ship it to prod, coward", medium: "suspicious little gremlin", low: "tiny crime, still crime" };
const CATEGORY_SUBS: Record<string, string> = { bug: "exquisite disaster", style: "crimes against taste", perf: "artisanal slowness", question: "explain yourself" };
const PANE_LIMITS = {
  left: { min: 180, max: 560, fallback: 288 },
  right: { min: 280, max: 680, fallback: 382 },
} as const;

type LayoutState = {
  left: number;
  right: number;
  leftCollapsed: boolean;
  rightCollapsed: boolean;
};

const token = new URLSearchParams(location.search).get("token") ?? "";
const els: Elements = {
  app: must("app"),
  meta: must("meta"),
  summary: must("summary"),
  findingCount: must("finding-count"),
  drawerCount: must("drawer-count"),
  tree: must("tree"),
  diffs: must("diffs"),
  inlineFinding: must("inline-finding"),
  selection: must("selection"),
  severity: mustSelect("severity"),
  severitySub: must("severity-sub"),
  category: mustSelect("category"),
  categorySub: must("category-sub"),
  comment: mustText("comment"),
  add: mustButton("add"),
  inlineCancel: mustButton("inline-cancel"),
  findings: must("findings"),
  notes: mustText("notes"),
  search: must("search") as HTMLInputElement,
  searchClear: mustButton("search-clear"),
  searchResults: must("search-results"),
  cancel: mustButton("cancel"),
  submit: mustButton("submit"),
  status: must("status"),
  themeMode: mustSelect("theme-mode"),
  leftSplitter: must("left-splitter"),
  rightSplitter: must("right-splitter"),
  toggleLeft: mustButton("toggle-left"),
  toggleRight: mustButton("toggle-right"),
};

const findings: FindingDraft[] = [];
const diffViews = new Map<string, FileDiff<FindingMeta>>();
const systemTheme = window.matchMedia("(prefers-color-scheme: light)");
let fileTree: FileTree | undefined;
let selectedFile: string | undefined;
let selected: ReviewSelection | undefined;
let lastDiffPointer: ViewPoint | undefined;
let searchIndex: SearchEntry[] = [];
let searchResults: SearchMatch[] = [];
let searchActiveIndex = -1;
let searchDebounce: number | undefined;
let diffsModule: typeof import("@pierre/diffs") | undefined;
let treesModule: typeof import("@pierre/trees") | undefined;
let heartbeat: number | undefined;
let reviewPoll: number | undefined;
let reviewHash = "";
let renderGeneration = 0;
let searchIndexing = false;
let notesGrowFrame: number | undefined;
let closing = false;
let themeMode: ThemeMode = readThemeMode();

applyThemeMode(themeMode);
els.themeMode.value = themeMode;
applyLayout(readLayout());

main().catch((err) => setDisconnectedStatus(err));
window.addEventListener("pagehide", closeFromBrowser);
systemTheme.addEventListener("change", () => {
  if (themeMode === "system") applyThemeMode(themeMode);
});

async function main() {
  if (!token) throw new Error("Missing review token");
  setStatus("Loading review…");
  const reviewPromise = api<ReviewPayload>(ROUTES.review);
  setStatus("Loading diff renderer…");
  await loadRendererModules();
  const review = await reviewPromise;
  startHeartbeat();
  startReviewPolling();
  wireActions();
  await renderReview(review);
  setStatus("Ready");
}

async function loadRendererModules() {
  if (diffsModule && treesModule) return;
  const [diffs, trees] = await Promise.all([import("@pierre/diffs"), import("@pierre/trees")]);
  diffsModule = diffs;
  treesModule = trees;
  registerNuguCodeTheme(diffs.registerCustomCSSVariableTheme);
}

function diffs() {
  if (!diffsModule) throw new Error("Diff renderer not loaded");
  return diffsModule;
}

function trees() {
  if (!treesModule) throw new Error("File tree renderer not loaded");
  return treesModule;
}

async function renderReview(review: ReviewPayload) {
  const generation = ++renderGeneration;
  reviewHash = hashReview(review);
  renderMeta(review);
  renderTree(review);
  const fileDiffs = await renderDiffs(review, generation);
  if (!fileDiffs || generation !== renderGeneration) return;
  renderAnnotations();
  void buildSearchIndex(fileDiffs, generation);
}

function renderMeta(review: ReviewPayload) {
  const totals = review.files.reduce((sum, file) => ({ additions: sum.additions + file.additions, deletions: sum.deletions + file.deletions }), { additions: 0, deletions: 0 });
  els.meta.replaceChildren(metaChip("round", String(review.round)), metaChip("reviewing", sourceLabel(review.source)));

  els.summary.replaceChildren();
  const stats = document.createElement("span");
  stats.className = "summary-stats";
  stats.textContent = `${review.files.length} files · +${totals.additions} −${totals.deletions}`;
  els.summary.appendChild(stats);
  if (review.skippedFiles.length > 0) {
    const skipped = document.createElement("span");
    skipped.className = "summary-skipped";
    skipped.textContent = `skipped ${review.skippedFiles.length} oversized/binary file${review.skippedFiles.length === 1 ? "" : "s"}`;
    els.summary.appendChild(skipped);
  }
  const hint = document.createElement("span");
  hint.className = "summary-hint";
  hint.textContent = "Click a changed line, describe issue, send findings to Pi.";
  els.summary.appendChild(hint);
  updateFindingCount();
}

function sourceLabel(source: ReviewPayload["source"]): string {
  const scope = source.files?.length ? ` · ${source.files.length} path${source.files.length === 1 ? "" : "s"}` : "";
  if (source.kind === "working-tree") return `unstaged changes${scope}`;
  if (source.kind === "staged") return `staged changes${scope}`;
  return `changes vs ${source.base}${scope}`;
}

function metaChip(label: string, value: string) {
  const chip = document.createElement("span");
  chip.className = `meta-chip meta-${label}`;
  const labelNode = document.createElement("span");
  labelNode.className = "meta-label";
  labelNode.textContent = label;
  const valueNode = document.createElement("span");
  valueNode.className = "meta-value";
  valueNode.textContent = value;
  chip.append(labelNode, valueNode);
  return chip;
}

function renderTree(review: ReviewPayload) {
  fileTree?.cleanUp();
  const skipped = skippedFilesByPath(review);
  const reviewPaths = review.files.flatMap((file) => file.prevPath && file.prevPath !== file.path ? [file.prevPath, file.path] : [file.path]);
  const paths = [...reviewPaths, ...[...skipped.keys()].filter((path) => !reviewPaths.includes(path))];
  fileTree = new (trees().FileTree)({
    paths,
    search: true,
    unsafeCSS: TREE_CSS,
    initialExpansion: "open",
    initialSelectedPaths: selectedFile && review.files.some((file) => file.path === selectedFile) ? [selectedFile] : [],
    gitStatus: [
      ...review.files.flatMap((file) => treeGitStatusEntries(file)),
      ...[...skipped.keys()].map((path) => ({ path, status: "ignored" as const })),
    ] satisfies GitStatusEntry[],
    renderRowDecoration: treeRowDecoration(review, skipped),
    onSelectionChange: ([path]) => {
      const renamedTarget = path ? renamedTargetForPrevPath(review, path) : undefined;
      if (renamedTarget) {
        fileTree?.getItem(path)?.deselect();
        fileTree?.getItem(renamedTarget)?.select();
        selectFile(renamedTarget, true);
        return;
      }
      if (path && skipped.has(path)) {
        fileTree?.getItem(path)?.deselect();
        if (selectedFile) fileTree?.getItem(selectedFile)?.select();
        setStatus(`Skipped ${path}: ${skipped.get(path)}`);
        return;
      }
      selectFile(path, true);
    },
  });
  fileTree.render({ fileTreeContainer: els.tree });
  wireTreeSearchClear(fileTree);
}

function treeGitStatusEntries(file: ReviewPayload["files"][number]): GitStatusEntry[] {
  if (file.status === "renamed" && file.prevPath && file.prevPath !== file.path) return [
    { path: file.prevPath, status: "deleted" },
    { path: file.path, status: "renamed" },
  ];
  return [{ path: file.path, status: toGitStatus(file.status) }];
}

function renamedTargetForPrevPath(review: ReviewPayload, path: string) {
  return review.files.find((file) => file.status === "renamed" && file.prevPath === path)?.path;
}

function treeRowDecoration(review: ReviewPayload, skipped: ReadonlyMap<string, string>): FileTreeRowDecorationRenderer {
  return ({ row }) => {
    if (row.kind !== "file") return null;
    const reason = skipped.get(row.path);
    if (reason) return { text: "skip", title: reason };
    const renameSource = review.files.find((file) => file.status === "renamed" && file.prevPath === row.path);
    if (renameSource) return { text: "from", title: `renamed to ${renameSource.path}` };
    const renameTarget = review.files.find((file) => file.status === "renamed" && file.path === row.path && file.prevPath);
    if (renameTarget?.prevPath) return { text: "to", title: `renamed from ${renameTarget.prevPath}` };
    return null;
  };
}

function wireTreeSearchClear(tree: FileTree) {
  const root = els.tree.shadowRoot;
  if (!root) return;

  const sync = () => {
    const container = root.querySelector<HTMLElement>("[data-file-tree-search-container]");
    const input = root.querySelector<HTMLInputElement>("[data-file-tree-search-input]");
    if (!container || !input || container.querySelector(".tree-search-clear")) return;
    const clear = document.createElement("button");
    clear.type = "button";
    clear.className = "tree-search-clear";
    clear.textContent = "×";
    clear.setAttribute("aria-label", "Clear file search");
    clear.addEventListener("pointerdown", (event) => event.preventDefault());
    clear.addEventListener("click", (event) => {
      event.preventDefault();
      tree.setSearch("");
      input.value = "";
      input.focus();
    });
    container.appendChild(clear);
  };

  sync();
  const observer = new MutationObserver(sync);
  observer.observe(root, { childList: true, subtree: true });
  const cleanup = tree.cleanUp.bind(tree);
  tree.cleanUp = () => {
    observer.disconnect();
    cleanup();
  };
}

function skippedFilesByPath(review: ReviewPayload): Map<string, string> {
  const skipped = new Map<string, string>();
  for (const entry of review.skippedFiles) {
    const { path, reason } = parseSkippedFile(entry);
    skipped.set(path, reason);
  }
  return skipped;
}

function parseSkippedFile(entry: string): { path: string; reason: string } {
  const match = /^(.*) \(([^()]*)\)$/.exec(entry);
  if (!match) return { path: entry, reason: "oversized/binary" };
  return { path: match[1], reason: match[2] };
}

async function renderDiffs(review: ReviewPayload, generation: number): Promise<FileDiffMetadata[] | undefined> {
  for (const view of diffViews.values()) view.cleanUp();
  diffViews.clear();
  els.diffs.replaceChildren();
  clearSelection(false);

  const files = diffs().parsePatchFiles(review.diffText, `diff-review-${review.round}`, true).flatMap((patch) => patch.files);
  for (let index = 0; index < files.length; index++) {
    if (generation !== renderGeneration) return undefined;
    renderFileDiff(files[index]);
    if (files.length > 1) setStatus(`Rendering ${index + 1}/${files.length} files…`);
    await yieldToBrowser();
  }
  return files;
}

function renderFileDiff(fileDiff: FileDiffMetadata) {
  const section = fileSection(fileDiff);
  const view = new (diffs().FileDiff)<FindingMeta>({
    theme: { dark: NUGU_CODE_THEME, light: NUGU_CODE_THEME },
    diffStyle: "split",
    overflow: "scroll",
    enableLineSelection: true,
    enableGutterUtility: true,
    lineHoverHighlight: "both",
    themeType: themeMode,
    unsafeCSS: DIFF_FONT_CSS,
    onLineSelected: (range) => setSelection(fileDiff.name, range, lastDiffPointer),
    onGutterUtilityClick: (range) => setSelection(fileDiff.name, range, lastDiffPointer),
    onLineClick: ({ lineNumber, annotationSide, event }) => setSelection(fileDiff.name, singleLineRange(lineNumber, annotationSide), eventPoint(event)),
    onLineNumberClick: ({ lineNumber, annotationSide, event }) => setSelection(fileDiff.name, singleLineRange(lineNumber, annotationSide), eventPoint(event)),
    renderAnnotation: renderAnnotation,
  });
  view.render({ fileDiff, containerWrapper: section, lineAnnotations: [] });
  diffViews.set(fileDiff.name, view);
}

function fileSection(fileDiff: FileDiffMetadata) {
  const section = document.createElement("section");
  section.className = "file-section";
  section.dataset.fileSection = fileDiff.name;
  if (fileDiff.name === selectedFile) section.dataset.selectedFile = "true";

  const title = document.createElement("h2");
  title.className = "file-title";
  title.textContent = fileTitle(fileDiff);
  section.appendChild(title);
  els.diffs.appendChild(section);
  return section;
}

function fileTitle(fileDiff: FileDiffMetadata) {
  return fileDiff.prevName && fileDiff.prevName !== fileDiff.name ? `${fileDiff.prevName} → ${fileDiff.name}` : fileDiff.name;
}

function renderAnnotation(annotation: DiffLineAnnotation<FindingMeta>) {
  const chip = document.createElement("div");
  chip.className = "finding-chip";
  chip.textContent = `[${annotation.metadata.severity}][${annotation.metadata.category}] ${annotation.metadata.comment}`;
  return chip;
}

function setSelection(file: string, range: SelectedLineRange | null, point?: ViewPoint) {
  const next = normalizeSelection(file, range);
  if (!next) {
    clearSelection(false);
    return;
  }
  selected = next;
  els.add.disabled = false;
  els.selection.className = "selection-active";
  els.selection.textContent = selectionLabel(next);
  showFindingForm(next, point);
}

function showFindingForm(selection: ReviewSelection, point?: ViewPoint) {
  const anchor = point ?? lineAnchor(selection) ?? centerPoint();
  els.inlineFinding.hidden = false;
  els.inlineFinding.dataset.open = "true";
  positionFindingForm(anchor);
  requestAnimationFrame(() => {
    positionFindingForm(anchor);
    els.comment.focus();
  });
}

function hideFindingForm() {
  els.inlineFinding.hidden = true;
  delete els.inlineFinding.dataset.open;
}

function positionFindingForm(point: ViewPoint) {
  const margin = 12;
  const gap = 14;
  const rect = els.inlineFinding.getBoundingClientRect();
  const width = rect.width || 360;
  const height = rect.height || 280;
  let left = point.x + gap;
  let top = point.y - 22;
  if (left + width + margin > window.innerWidth) left = point.x - width - gap;
  left = Math.max(margin, Math.min(left, window.innerWidth - width - margin));
  top = Math.max(margin, Math.min(top, window.innerHeight - height - margin));
  els.inlineFinding.style.left = `${Math.round(left)}px`;
  els.inlineFinding.style.top = `${Math.round(top)}px`;
}

function lineAnchor(selection: ReviewSelection): ViewPoint | undefined {
  const section = document.querySelector<HTMLElement>(`[data-file-section="${cssEscape(selection.file)}"]`);
  const container = section?.querySelector("diffs-container") as HTMLElement | null;
  const root = container?.shadowRoot;
  const line = root?.querySelector<HTMLElement>(`[data-${selection.side}] [data-line="${selection.startLine}"]`);
  if (!line) return undefined;
  const rect = line.getBoundingClientRect();
  return { x: rect.left + 24, y: rect.top + rect.height / 2 };
}

function centerPoint(): ViewPoint {
  return { x: window.innerWidth / 2, y: window.innerHeight / 2 };
}

function eventPoint(event: MouseEvent | PointerEvent): ViewPoint {
  return { x: event.clientX, y: event.clientY };
}

function normalizeSelection(file: string, range: SelectedLineRange | null): ReviewSelection | undefined {
  if (!range) return undefined;
  const side = range.side;
  const endSide = range.endSide ?? side;
  if (!isReviewSide(side) || endSide !== side) return undefined;
  return { file, side, startLine: Math.min(range.start, range.end), endLine: Math.max(range.start, range.end) };
}

function singleLineRange(lineNumber: number, side: SelectedLineRange["side"]): SelectedLineRange | null {
  return side ? { start: lineNumber, end: lineNumber, side, endSide: side } : null;
}

function selectionLabel(selection: ReviewSelection) {
  const { file, startLine, endLine, side } = selection;
  return `${file}:${startLine}${startLine === endLine ? "" : `-${endLine}`} ${side}`;
}

function wireActions() {
  els.themeMode.addEventListener("change", updateThemeMode);
  els.severity.addEventListener("change", () => { els.severitySub.textContent = SEVERITY_SUBS[els.severity.value] ?? ""; });
  els.category.addEventListener("change", () => { els.categorySub.textContent = CATEGORY_SUBS[els.category.value] ?? ""; });
  els.add.addEventListener("click", addFinding);
  els.submit.addEventListener("click", submitReview);
  els.cancel.addEventListener("click", cancelReview);
  els.toggleLeft.addEventListener("click", () => togglePane("left"));
  els.toggleRight.addEventListener("click", () => togglePane("right"));
  els.leftSplitter.addEventListener("pointerdown", (event) => startPaneResize("left", event));
  els.rightSplitter.addEventListener("pointerdown", (event) => startPaneResize("right", event));
  els.diffs.addEventListener("pointerdown", (event) => { lastDiffPointer = eventPoint(event); }, true);
  els.diffs.addEventListener("pointerup", (event) => { lastDiffPointer = eventPoint(event); }, true);
  els.inlineCancel.addEventListener("click", () => {
    clearFindingForm();
    clearSelection(true);
  });
  els.comment.addEventListener("keydown", (event) => {
    if ((event.metaKey || event.ctrlKey) && event.key === "Enter") void addFinding();
    if (event.key === "Escape") clearSelection(true);
  });
  els.notes.addEventListener("input", () => scheduleNotesAutoGrow());
  scheduleNotesAutoGrow();
  els.search.addEventListener("input", () => {
    window.clearTimeout(searchDebounce);
    searchDebounce = window.setTimeout(runSearch, 120);
  });
  els.searchClear.addEventListener("click", () => clearCodeSearch(true));
  els.search.addEventListener("search", () => {
    if (!els.search.value.trim()) clearCodeSearch(false);
  });
  els.search.addEventListener("keydown", (event) => {
    if (isEscapeKey(event)) {
      event.preventDefault();
      event.stopPropagation();
      closeCodeSearchPopup();
      return;
    }
    if (event.key === "ArrowDown" || event.key === "ArrowUp") {
      event.preventDefault();
      navigateSearch(event.key === "ArrowDown" ? 1 : -1);
      return;
    }
    if (event.key === "Enter") {
      event.preventDefault();
      if (searchResults.length === 0) return;
      const idx = searchActiveIndex >= 0 ? searchActiveIndex : 0;
      jumpToMatch(searchResults[idx], idx);
      hideSearch();
    }
  });
  document.addEventListener("keydown", (event) => {
    if (!isEscapeKey(event) || els.searchResults.hidden) return;
    event.preventDefault();
    event.stopPropagation();
    closeCodeSearchPopup();
  }, true);
  document.addEventListener("click", (event) => {
    if (!els.searchResults.contains(event.target as Node) && event.target !== els.search) hideSearch();
  });
}

function scheduleNotesAutoGrow() {
  if (notesGrowFrame !== undefined) return;
  notesGrowFrame = requestAnimationFrame(() => {
    notesGrowFrame = undefined;
    autoGrowTextarea(els.notes);
  });
}

function autoGrowTextarea(textarea: HTMLTextAreaElement) {
  textarea.style.height = "auto";
  textarea.style.height = `${textarea.scrollHeight}px`;
}

function yieldToBrowser() {
  return new Promise<void>((resolve) => {
    const requestIdle = window.requestIdleCallback as ((callback: () => void, options?: { timeout: number }) => number) | undefined;
    if (requestIdle) requestIdle(() => resolve(), { timeout: 80 });
    else requestAnimationFrame(() => resolve());
  });
}

function updateThemeMode() {
  themeMode = themeModeFromValue(els.themeMode.value);
  localStorage.setItem(THEME_STORAGE_KEY, themeMode);
  applyThemeMode(themeMode);
  for (const view of diffViews.values()) view.setThemeType(themeMode);
}

function togglePane(side: PaneSide) {
  const layout = readLayout();
  if (side === "left") layout.leftCollapsed = !layout.leftCollapsed;
  else layout.rightCollapsed = !layout.rightCollapsed;
  applyLayout(layout);
  writeLayout(layout);
}

function startPaneResize(side: PaneSide, event: PointerEvent) {
  if ((event.target as HTMLElement).closest("button")) return;
  event.preventDefault();
  const layout = readLayout();
  if (side === "left") layout.leftCollapsed = false;
  else layout.rightCollapsed = false;
  els.app.dataset.resizing = side;
  try { els.app.setPointerCapture?.(event.pointerId); } catch {}

  const move = (moveEvent: PointerEvent) => {
    const next = { ...layout };
    if (side === "left") next.left = clampPane("left", moveEvent.clientX);
    else next.right = clampPane("right", window.innerWidth - moveEvent.clientX);
    applyLayout(next);
    writeLayout(next);
  };
  const stop = () => {
    delete els.app.dataset.resizing;
    window.removeEventListener("pointermove", move);
    window.removeEventListener("pointerup", stop);
    window.removeEventListener("pointercancel", stop);
  };

  window.addEventListener("pointermove", move);
  window.addEventListener("pointerup", stop, { once: true });
  window.addEventListener("pointercancel", stop, { once: true });
}

function readLayout(): LayoutState {
  const stored = localStorage.getItem(LAYOUT_STORAGE_KEY);
  if (!stored) return defaultLayout();
  try {
    const value = JSON.parse(stored) as Partial<LayoutState>;
    return {
      left: clampPane("left", value.left),
      right: clampPane("right", value.right),
      leftCollapsed: value.leftCollapsed === true,
      rightCollapsed: value.rightCollapsed === true,
    };
  } catch {
    return defaultLayout();
  }
}

function writeLayout(layout: LayoutState) {
  localStorage.setItem(LAYOUT_STORAGE_KEY, JSON.stringify(layout));
}

function defaultLayout(): LayoutState {
  return { left: PANE_LIMITS.left.fallback, right: PANE_LIMITS.right.fallback, leftCollapsed: false, rightCollapsed: false };
}

function applyLayout(layout: LayoutState) {
  els.app.style.setProperty("--left-pane", `${layout.leftCollapsed ? 0 : layout.left}px`);
  els.app.style.setProperty("--right-pane", `${layout.rightCollapsed ? 0 : layout.right}px`);
  els.app.dataset.leftCollapsed = String(layout.leftCollapsed);
  els.app.dataset.rightCollapsed = String(layout.rightCollapsed);
  els.toggleLeft.textContent = layout.leftCollapsed ? "›" : "‹";
  els.toggleRight.textContent = layout.rightCollapsed ? "‹" : "›";
  els.toggleLeft.setAttribute("aria-label", layout.leftCollapsed ? "Expand file tree" : "Collapse file tree");
  els.toggleRight.setAttribute("aria-label", layout.rightCollapsed ? "Expand review panel" : "Collapse review panel");
}

function clampPane(side: PaneSide, value: unknown) {
  const limits = PANE_LIMITS[side];
  const width = typeof value === "number" && Number.isFinite(value) ? value : limits.fallback;
  return Math.min(limits.max, Math.max(limits.min, Math.round(width)));
}

async function addFinding() {
  const draft = draftFromSelection();
  if (!draft) return;
  els.add.disabled = true;
  try {
    await api(ROUTES.validateFinding, postJson(draft));
    findings.push(draft);
    clearFindingForm();
    clearSelection(true);
    renderFindings();
    renderAnnotations();
    setStatus("Finding added");
  } catch (err) {
    setStatus(errorMessage(err), "error");
  } finally {
    els.add.disabled = !selected;
  }
}

function draftFromSelection(): FindingDraft | undefined {
  if (!selected) return undefined;
  const comment = els.comment.value.trim();
  if (!comment) {
    setStatus("Comment required", "error");
    return undefined;
  }
  return {
    ...selected,
    category: categoryFromValue(els.category.value),
    severity: severityFromValue(els.severity.value),
    comment,
  };
}

async function submitReview() {
  if (findings.length === 0 && !els.notes.value.trim() && !confirm("Send empty review to Pi?")) return;
  setDoneButtonsDisabled(true);
  try {
    await api(ROUTES.submit, postJson({ notes: els.notes.value, findings }));
    findings.splice(0);
    els.notes.value = "";
    renderFindings();
    renderAnnotations();
    setStatus("Sent to Pi — keep reviewing or close tab to end", "ok");
  } catch (err) {
    setStatus(errorMessage(err), "error");
  } finally {
    setDoneButtonsDisabled(false);
  }
}

async function cancelReview() {
  closing = true;
  setDoneButtonsDisabled(true);
  await api(ROUTES.cancel, postJson({})).catch(() => undefined);
  cleanup();
  setStatus("Closed — return to Pi");
}

function setDoneButtonsDisabled(disabled: boolean) {
  els.submit.disabled = disabled;
  els.cancel.disabled = disabled;
}

function clearFindingForm() {
  els.comment.value = "";
}

function clearSelection(clearViews: boolean) {
  selected = undefined;
  els.add.disabled = true;
  els.selection.className = "selection-empty";
  els.selection.textContent = "Click an added or deleted line.";
  hideFindingForm();
  if (clearViews) for (const view of diffViews.values()) view.setSelectedLines(null);
}

function renderFindings() {
  els.findings.replaceChildren();
  els.findings.className = findings.length === 0 ? "empty-list" : "";
  if (findings.length === 0) {
    els.findings.textContent = "No findings yet.";
    updateFindingCount();
    return;
  }
  findings.forEach((finding, index) => els.findings.appendChild(findingItem(finding, index)));
  updateFindingCount();
}

function findingItem(finding: FindingDraft, index: number) {
  const item = document.createElement("div");
  item.className = `finding-item severity-${finding.severity}`;
  item.tabIndex = 0;
  item.addEventListener("click", () => selectFile(finding.file, true));
  item.addEventListener("keydown", (event) => {
    if (event.key === "Enter") selectFile(finding.file, true);
  });

  const head = document.createElement("div");
  head.className = "finding-item-head";

  const number = document.createElement("span");
  number.className = "finding-number";
  number.textContent = String(index + 1);

  const severity = document.createElement("span");
  severity.className = `finding-pill ${finding.severity}`;
  severity.textContent = finding.severity;

  const category = document.createElement("span");
  category.className = "finding-pill category";
  category.textContent = finding.category;

  const remove = document.createElement("button");
  remove.className = "remove-finding";
  remove.type = "button";
  remove.textContent = "×";
  remove.title = "Remove finding";
  remove.addEventListener("click", (event) => {
    event.stopPropagation();
    removeFinding(index);
  });

  const location = document.createElement("div");
  location.className = "finding-location";
  location.textContent = selectionLabel(finding);

  const text = document.createElement("div");
  text.className = "finding-comment";
  text.textContent = finding.comment;

  head.append(number, severity, category, remove);
  item.append(head, location, text);
  return item;
}

function removeFinding(index: number) {
  findings.splice(index, 1);
  renderFindings();
  renderAnnotations();
}

function updateFindingCount() {
  els.findingCount.textContent = `${findings.length} finding${findings.length === 1 ? "" : "s"}`;
  els.drawerCount.textContent = String(findings.length);
}

function renderAnnotations() {
  for (const [file, view] of diffViews) {
    view.setLineAnnotations(annotationsFor(file));
    view.rerender();
  }
}

async function buildSearchIndex(fileDiffs: FileDiffMetadata[], generation: number) {
  searchIndexing = true;
  searchIndex = [];
  const restoreStatus = els.status.textContent === "Ready" ? "Ready" : undefined;
  const entries: SearchEntry[] = [];
  for (let index = 0; index < fileDiffs.length; index++) {
    if (generation !== renderGeneration) { searchIndexing = false; return; }
    entries.push(...searchEntriesForFile(fileDiffs[index]));
    if (fileDiffs.length > 1) setStatus(`Indexing search ${index + 1}/${fileDiffs.length} files…`);
    await yieldToBrowser();
  }
  if (generation !== renderGeneration) { searchIndexing = false; return; }
  searchIndex = entries;
  searchIndexing = false;
  if (els.search.value.trim()) runSearch();
  if (restoreStatus && els.status.textContent.startsWith("Indexing search")) setStatus(restoreStatus);
}

function searchEntriesForFile(fileDiff: FileDiffMetadata): SearchEntry[] {
  const entries: SearchEntry[] = [];
  for (const hunk of fileDiff.hunks) {
    let additionLine = hunk.additionStart;
    let deletionLine = hunk.deletionStart;
    for (const content of hunk.hunkContent) {
      if (content.type === "context") {
        for (let i = 0; i < content.lines; i++) {
          const text = fileDiff.additionLines[content.additionLineIndex + i];
          if (text !== undefined) entries.push({ file: fileDiff.name, side: "additions", line: additionLine + i, text });
        }
        additionLine += content.lines;
        deletionLine += content.lines;
      } else {
        for (let i = 0; i < content.deletions; i++) {
          const text = fileDiff.deletionLines[content.deletionLineIndex + i];
          if (text !== undefined) entries.push({ file: fileDiff.name, side: "deletions", line: deletionLine + i, text });
        }
        for (let i = 0; i < content.additions; i++) {
          const text = fileDiff.additionLines[content.additionLineIndex + i];
          if (text !== undefined) entries.push({ file: fileDiff.name, side: "additions", line: additionLine + i, text });
        }
        deletionLine += content.deletions;
        additionLine += content.additions;
      }
    }
  }
  return entries;
}

function runSearch() {
  const query = els.search.value.trim();
  if (!query) { searchResults = []; searchActiveIndex = -1; hideSearch(); return; }
  if (searchIndexing) {
    els.searchResults.hidden = false;
    els.searchResults.replaceChildren();
    const empty = document.createElement("div");
    empty.className = "search-empty";
    empty.textContent = "Indexing search…";
    els.searchResults.appendChild(empty);
    return;
  }
  searchResults = searchCode(query);
  searchActiveIndex = -1;
  if (searchResults.length === 0) {
    els.searchResults.hidden = false;
    els.searchResults.replaceChildren();
    const empty = document.createElement("div");
    empty.className = "search-empty";
    empty.textContent = "No matches.";
    els.searchResults.appendChild(empty);
    updateSearchBadge();
    return;
  }
  renderSearchResults();
  updateSearchBadge();
}

function renderSearchResults() {
  els.searchResults.hidden = false;
  els.searchResults.replaceChildren();
  const max = Math.min(searchResults.length, 200);
  for (let i = 0; i < max; i++) els.searchResults.appendChild(searchResultItem(searchResults[i], i));
  if (searchResults.length > max) {
    const more = document.createElement("div");
    more.className = "search-more";
    more.textContent = `${searchResults.length - max} more matches`;
    els.searchResults.appendChild(more);
  }
}

function navigateSearch(delta: 1 | -1) {
  if (searchResults.length === 0) return;
  searchActiveIndex = searchActiveIndex < 0 ? 0 : Math.max(0, Math.min(searchResults.length - 1, searchActiveIndex + delta));
  const items = els.searchResults.querySelectorAll<HTMLElement>(".search-result");
  items.forEach((el, i) => el.classList.toggle("search-result-active", i === searchActiveIndex));
  const active = items[searchActiveIndex];
  active?.scrollIntoView({ block: "nearest" });
  jumpToMatch(searchResults[searchActiveIndex], searchActiveIndex);
  updateSearchBadge();
}

function updateSearchBadge() {
  const badge = document.querySelector<HTMLElement>("#search-badge");
  if (!badge) return;
  if (searchResults.length === 0) { badge.hidden = true; return; }
  badge.hidden = false;
  badge.textContent = searchActiveIndex >= 0 ? `${searchActiveIndex + 1}/${searchResults.length}` : `${searchResults.length}`;
}

function searchCode(query: string): SearchMatch[] {
  const hits: SearchMatch[] = [];
  const isRegex = query.startsWith("/") && query.endsWith("/");
  const pattern = isRegex ? query.slice(1, -1) : query.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
  let re: RegExp;
  try { re = new RegExp(pattern, "i"); } catch { return hits; }
  for (const entry of searchIndex) {
    const m = re.exec(entry.text);
    if (m && m.index >= 0) {
      hits.push({ ...entry, matchStart: m.index, matchEnd: m.index + m[0].length });
      if (hits.length >= 500) break;
    }
  }
  return hits;
}

function searchResultItem(match: SearchMatch, index: number) {
  const item = document.createElement("div");
  item.className = "search-result";
  item.tabIndex = -1;
  item.addEventListener("click", () => {
    searchActiveIndex = index;
    jumpToMatch(match, index);
    renderSearchResults();
    updateSearchBadge();
  });

  const file = document.createElement("span");
  file.className = "search-result-file";
  file.textContent = match.file;

  const loc = document.createElement("span");
  loc.className = "search-result-loc";
  loc.textContent = `:${match.line} ${match.side === "additions" ? "+" : "-"}`;

  const preview = document.createElement("div");
  preview.className = "search-result-preview";
  const before = match.text.slice(Math.max(0, match.matchStart - 20), match.matchStart);
  const matched = match.text.slice(match.matchStart, match.matchEnd);
  const after = match.text.slice(match.matchEnd, match.matchEnd + 40);
  preview.textContent = before;
  const mark = document.createElement("mark");
  mark.textContent = matched;
  preview.appendChild(mark);
  preview.append(after);

  item.append(file, loc, preview);
  return item;
}

function jumpToMatch(match: SearchMatch, index: number) {
  selectFile(match.file, false);
  requestAnimationFrame(() => {
    const section = document.querySelector<HTMLElement>(`[data-file-section="${cssEscape(match.file)}"]`);
    const container = section?.querySelector("diffs-container") as HTMLElement | null;
    const root = container?.shadowRoot;
    const sideRoot = root?.querySelector<HTMLElement>(match.side === "additions" ? "[data-additions]" : "[data-deletions]");
    const line = sideRoot?.querySelector<HTMLElement>(`[data-line="${match.line}"]`);
    if (line) {
      const lineIndex = line.getAttribute("data-line-index");
      const gutter = lineIndex
        ? sideRoot?.querySelector<HTMLElement>(`[data-column-number][data-line-index="${cssEscape(lineIndex)}"]`)
        : sideRoot?.querySelector<HTMLElement>(`[data-column-number="${match.line}"]`);
      scrollDiffLineIntoView(line);
      flashSearchHighlight([line, gutter]);
    }
  });
}

function scrollDiffLineIntoView(line: HTMLElement) {
  const scroller = els.diffs;
  const lineRect = line.getBoundingClientRect();
  const scrollerRect = scroller.getBoundingClientRect();
  const nextTop = scroller.scrollTop + lineRect.top - scrollerRect.top - (scrollerRect.height / 2) + (lineRect.height / 2);
  scroller.scrollTo({ top: Math.max(0, nextTop), behavior: "smooth" });
}

function flashSearchHighlight(elements: Array<HTMLElement | undefined | null>) {
  const targets = elements.filter((element): element is HTMLElement => Boolean(element));
  for (const target of targets) target.classList.remove("search-highlight");
  if (targets[0]) void targets[0].offsetWidth;
  for (const target of targets) target.classList.add("search-highlight");
}

function isEscapeKey(event: KeyboardEvent) {
  return event.key === "Escape" || event.key === "Esc";
}

function cancelPendingSearch() {
  window.clearTimeout(searchDebounce);
  searchDebounce = undefined;
}

function closeCodeSearchPopup() {
  cancelPendingSearch();
  searchActiveIndex = -1;
  hideSearch();
}

function clearCodeSearch(refocus: boolean) {
  cancelPendingSearch();
  els.search.value = "";
  searchResults = [];
  searchActiveIndex = -1;
  hideSearch();
  updateSearchBadge();
  if (refocus) els.search.focus();
}

function hideSearch() {
  els.searchResults.hidden = true;
  updateSearchBadge();
}

function annotationsFor(file: string): DiffLineAnnotation<FindingMeta>[] {
  return findings
    .filter((finding) => finding.file === file)
    .map((finding, index) => ({
      side: finding.side,
      lineNumber: finding.startLine,
      metadata: { findingId: String(index), severity: finding.severity, category: finding.category, comment: finding.comment },
    }));
}

async function api<T = unknown>(path: string, init: RequestInit = {}): Promise<T> {
  const res = await fetch(path, {
    ...init,
    headers: { "Authorization": `Bearer ${token}`, "Content-Type": "application/json", ...(init.headers ?? {}) },
  });
  const body = await res.text();
  const data = body ? JSON.parse(body) : undefined;
  if (!res.ok) throw new Error(errorPayload(data) ?? `${res.status} ${res.statusText}`);
  return data as T;
}

function postJson(body: unknown): RequestInit {
  return { method: "POST", body: JSON.stringify(body) };
}

function errorPayload(value: unknown) {
  return value && typeof value === "object" && "error" in value && typeof value.error === "string" ? value.error : undefined;
}

function startHeartbeat() {
  heartbeat = window.setInterval(() => api(ROUTES.heartbeat, postJson({})).catch(() => undefined), HEARTBEAT_INTERVAL_MS);
}

function startReviewPolling() {
  reviewPoll = window.setInterval(refreshReview, REVIEW_POLL_INTERVAL_MS);
}

async function refreshReview() {
  try {
    const review = await api<ReviewPayload>(ROUTES.review);
    const nextHash = hashReview(review);
    if (nextHash === reviewHash) return;
    await renderReview(review);
    setStatus("Diff updated", "ok");
  } catch (err) {
    setDisconnectedStatus(err);
  }
}

function hashReview(review: ReviewPayload) {
  return `${review.diffText}\0${review.skippedFiles.join("\0")}`;
}

function stopHeartbeat() {
  if (heartbeat !== undefined) window.clearInterval(heartbeat);
  heartbeat = undefined;
}

function stopReviewPolling() {
  if (reviewPoll !== undefined) window.clearInterval(reviewPoll);
  reviewPoll = undefined;
}

function cleanup() {
  stopHeartbeat();
  stopReviewPolling();
  fileTree?.cleanUp();
  for (const view of diffViews.values()) view.cleanUp();
}

function closeFromBrowser() {
  if (closing) return;
  closing = true;
  navigator.sendBeacon?.(ROUTES.cancel, new Blob(["{}"], { type: "application/json" }));
  cleanup();
}

function setStatus(text: string, tone: "neutral" | "error" | "ok" = "neutral") {
  els.status.textContent = text;
  els.status.className = tone === "neutral" ? "" : tone;
}

function setDisconnectedStatus(err: unknown) {
  const message = errorMessage(err);
  const disconnected = /networkerror|failed to fetch|load failed|fetch resource/i.test(message);
  setStatus(disconnected ? "Disconnected. Run /diff-review, then refresh." : message, "error");
}

function readThemeMode(): ThemeMode {
  return themeModeFromValue(localStorage.getItem(THEME_STORAGE_KEY));
}

function applyThemeMode(mode: ThemeMode) {
  document.documentElement.dataset.theme = mode === "system" ? (systemTheme.matches ? "light" : "dark") : mode;
  document.documentElement.dataset.themeMode = mode;
  const icon = document.querySelector<HTMLElement>(".theme-icon");
  if (icon) icon.textContent = mode === "dark" ? "☾" : mode === "light" ? "☼" : "◐";
}

function selectFile(path: string | undefined, scroll: boolean) {
  selectedFile = path;
  applySelectedFileEmphasis();
  if (scroll) scrollToFile(path);
}

function applySelectedFileEmphasis() {
  for (const section of els.diffs.querySelectorAll<HTMLElement>("[data-file-section]")) {
    const active = section.dataset.fileSection === selectedFile;
    if (active) section.dataset.selectedFile = "true";
    else delete section.dataset.selectedFile;
  }
}

function scrollToFile(path: string | undefined) {
  if (!path) return;
  const section = document.querySelector<HTMLElement>(`[data-file-section="${cssEscape(path)}"]`);
  if (!section) return;
  const scroller = els.diffs;
  const top = section.getBoundingClientRect().top - scroller.getBoundingClientRect().top + scroller.scrollTop;
  scroller.scrollTo({ top: Math.max(0, top - 2), behavior: "smooth" });
}

function toGitStatus(status: ReviewPayload["files"][number]["status"]): GitStatusEntry["status"] {
  if (status === "added" || status === "deleted" || status === "renamed") return status;
  return "modified";
}

function themeModeFromValue(value: unknown): ThemeMode {
  return isOneOf(value, THEME_MODES) ? value : "system";
}

function categoryFromValue(value: unknown): ReviewCategory {
  if (isOneOf(value, REVIEW_CATEGORIES)) return value;
  throw new Error(`Invalid category: ${String(value)}`);
}

function severityFromValue(value: unknown): ReviewSeverity {
  if (isOneOf(value, REVIEW_SEVERITIES)) return value;
  throw new Error(`Invalid severity: ${String(value)}`);
}

function isReviewSide(value: unknown): value is ReviewSide {
  return value === "additions" || value === "deletions";
}

function isOneOf<T extends string>(value: unknown, choices: readonly T[]): value is T {
  return typeof value === "string" && choices.includes(value as T);
}

function must(id: keyof Elements | string) {
  const el = document.getElementById(id);
  if (!el) throw new Error(`Missing #${id}`);
  return el;
}

function mustButton(id: string) { return must(id) as HTMLButtonElement; }
function mustSelect(id: string) { return must(id) as HTMLSelectElement; }
function mustText(id: string) { return must(id) as HTMLTextAreaElement; }

function cssEscape(value: string) {
  return CSS.escape(value);
}

function errorMessage(err: unknown) {
  return err instanceof Error ? err.message : String(err);
}