repositories / dotfiles

dotfiles

bugabingas dorkfiles

owned by bugabinga

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

Raw
File outline
import "./style.css";
import { FileDiff, parsePatchFiles, type DiffLineAnnotation, type FileDiffMetadata, type SelectedLineRange } from "@pierre/diffs";
import { FileTree, type GitStatusEntry } from "@pierre/trees";

type ReviewCategory = "bug" | "style" | "perf" | "question";
type ReviewSeverity = "high" | "medium" | "low";
type ReviewSide = "additions" | "deletions";

type FindingDraft = {
  file: string;
  side: ReviewSide;
  startLine: number;
  endLine: number;
  category: ReviewCategory;
  severity: ReviewSeverity;
  comment: string;
  notes?: string;
};

type ReviewPayload = {
  round: number;
  source: { kind: "working-tree" | "staged" | "base"; base?: string; files?: string[] };
  diffText: string;
  files: Array<{ path: string; prevPath?: string; status: "added" | "modified" | "deleted" | "renamed" | "binary"; additions: number; deletions: number }>;
  carriedFindings: unknown[];
};

type FindingMeta = { findingId: string; severity: ReviewSeverity; category: ReviewCategory; comment: string };
type ThemeMode = "system" | "dark" | "light";

const token = new URLSearchParams(location.search).get("token") ?? "";
const findings: FindingDraft[] = [];
const instances = new Map<string, FileDiff<FindingMeta>>();
let selected: { file: string; range: SelectedLineRange } | undefined;
let heartbeat: number | undefined;
let themeMode: ThemeMode = readThemeMode();

const els = {
  meta: must("meta"),
  summary: must("summary"),
  findingCount: must("finding-count"),
  tree: must("tree"),
  diffs: must("diffs"),
  selection: must("selection"),
  severity: mustSelect("severity"),
  category: mustSelect("category"),
  comment: mustText("comment"),
  findingNotes: mustText("finding-notes"),
  add: mustButton("add"),
  findings: must("findings"),
  notes: mustText("notes"),
  cancel: mustButton("cancel"),
  submit: mustButton("submit"),
  status: must("status"),
  themeMode: mustSelect("theme-mode"),
};

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

main().catch((err) => setStatus(String(err?.message ?? err), true));

async function main() {
  if (!token) throw new Error("Missing review token");
  const review = await api<ReviewPayload>("/api/review");
  startHeartbeat();
  renderMeta(review);
  renderTree(review);
  renderDiffs(review);
  wireActions();
  setStatus("Ready");
}

function renderMeta(review: ReviewPayload) {
  const additions = review.files.reduce((sum, file) => sum + file.additions, 0);
  const deletions = review.files.reduce((sum, file) => sum + file.deletions, 0);
  els.meta.textContent = `round ${review.round} · ${review.source.kind} · ${review.files.length} files`;
  els.summary.textContent = `${review.files.length} files · +${additions} −${deletions}. Click a changed line, describe the issue, submit to Pi.`;
  updateFindingCount();
}

function renderTree(review: ReviewPayload) {
  const gitStatus: GitStatusEntry[] = review.files.map((file) => ({ path: file.path, status: toGitStatus(file.status) }));
  const tree = new FileTree({
    paths: review.files.map((file) => file.path),
    search: true,
    initialExpansion: "open",
    gitStatus,
    onSelectionChange(paths) {
      const path = paths[0];
      if (!path) return;
      document.querySelector<HTMLElement>(`[data-file-section="${cssEscape(path)}"]`)?.scrollIntoView({ block: "start" });
    },
  });
  tree.render({ fileTreeContainer: els.tree });
}

function renderDiffs(review: ReviewPayload) {
  const patches = parsePatchFiles(review.diffText, `diff-review-${review.round}`, true);
  for (const patch of patches) {
    for (const fileDiff of patch.files) renderFileDiff(fileDiff);
  }
}

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

  const title = document.createElement("h2");
  title.className = "file-title";
  title.textContent = fileDiff.prevName && fileDiff.prevName !== fileDiff.name ? `${fileDiff.prevName} → ${fileDiff.name}` : fileDiff.name;
  section.appendChild(title);
  els.diffs.appendChild(section);

  const instance = new FileDiff<FindingMeta>({
    theme: { dark: "pierre-dark", light: "pierre-light" },
    diffStyle: "split",
    overflow: "scroll",
    enableLineSelection: true,
    enableGutterUtility: true,
    lineHoverHighlight: "both",
    themeType: themeMode,
    unsafeCSS: diffUnsafeCSS(),
    onLineSelected: (range) => openDrawer(fileDiff.name, range),
    onGutterUtilityClick: (range) => openDrawer(fileDiff.name, range),
    onLineClick: ({ lineNumber, annotationSide }) => openDrawer(fileDiff.name, { start: lineNumber, end: lineNumber, side: annotationSide, endSide: annotationSide }),
    onLineNumberClick: ({ lineNumber, annotationSide }) => openDrawer(fileDiff.name, { start: lineNumber, end: lineNumber, side: annotationSide, endSide: annotationSide }),
    renderAnnotation(annotation) {
      const chip = document.createElement("div");
      chip.className = "finding-chip";
      chip.textContent = `[${annotation.metadata.severity}][${annotation.metadata.category}] ${annotation.metadata.comment}`;
      return chip;
    },
  });
  instance.render({ fileDiff, containerWrapper: section, lineAnnotations: [] });
  instances.set(fileDiff.name, instance);
}

function openDrawer(file: string, range: SelectedLineRange | null) {
  if (!range) {
    selected = undefined;
    els.selection.textContent = "Click an added or deleted line.";
    els.selection.className = "selection-empty";
    els.add.disabled = true;
    return;
  }
  const side = range.side;
  const endSide = range.endSide ?? side;
  if ((side !== "additions" && side !== "deletions") || endSide !== side) {
    selected = undefined;
    els.selection.textContent = "Only single-side additions/deletions selections are supported.";
    els.selection.className = "selection-empty";
    els.add.disabled = true;
    return;
  }
  selected = { file, range };
  const start = Math.min(range.start, range.end);
  const end = Math.max(range.start, range.end);
  els.selection.textContent = `${file}:${start}${start === end ? "" : `-${end}`} ${side}`;
  els.selection.className = "selection-active";
  els.add.disabled = false;
}

function wireActions() {
  els.themeMode.addEventListener("change", () => {
    themeMode = els.themeMode.value as ThemeMode;
    localStorage.setItem("diff-review-theme", themeMode);
    applyThemeMode(themeMode);
    for (const instance of instances.values()) instance.setThemeType(themeMode);
  });

  els.add.addEventListener("click", async () => {
    if (!selected) return;
    const comment = els.comment.value.trim();
    if (!comment) return setStatus("Comment required", true);
    els.add.disabled = true;
    const side = selected.range.side as ReviewSide;
    const draft: FindingDraft = {
      file: selected.file,
      side,
      startLine: Math.min(selected.range.start, selected.range.end),
      endLine: Math.max(selected.range.start, selected.range.end),
      category: els.category.value as ReviewCategory,
      severity: els.severity.value as ReviewSeverity,
      comment,
      ...(els.findingNotes.value.trim() && { notes: els.findingNotes.value.trim() }),
    };
    try {
      await api("/api/finding/validate", { method: "POST", body: JSON.stringify(draft) });
      findings.push(draft);
      els.comment.value = "";
      els.findingNotes.value = "";
      renderFindings();
      renderAnnotations();
      setStatus("Finding added");
    } catch (err) {
      setStatus((err as Error).message, true);
    } finally {
      els.add.disabled = false;
    }
  });

  els.submit.addEventListener("click", async () => {
    if (findings.length === 0 && !confirm("Submit review with no findings?")) return;
    els.submit.disabled = true;
    els.cancel.disabled = true;
    try {
      await api("/api/submit", { method: "POST", body: JSON.stringify({ notes: els.notes.value, findings }) });
      stopHeartbeat();
      setStatus("Submitted — return to Pi", false, true);
    } catch (err) {
      els.submit.disabled = false;
      els.cancel.disabled = false;
      setStatus((err as Error).message, true);
    }
  });

  els.cancel.addEventListener("click", async () => {
    els.submit.disabled = true;
    els.cancel.disabled = true;
    await api("/api/cancel", { method: "POST", body: "{}" }).catch(() => undefined);
    stopHeartbeat();
    setStatus("Cancelled — return to Pi");
  });
}

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;
  }
  for (const [index, finding] of findings.entries()) {
    const item = document.createElement("div");
    item.className = "finding-item";
    const text = document.createElement("div");
    text.textContent = `${index + 1}. [${finding.severity}][${finding.category}] ${finding.file}:${finding.startLine}${finding.startLine === finding.endLine ? "" : `-${finding.endLine}`} ${finding.side} — ${finding.comment}`;
    const remove = document.createElement("button");
    remove.className = "remove-finding";
    remove.type = "button";
    remove.textContent = "Remove";
    remove.addEventListener("click", () => {
      findings.splice(index, 1);
      renderFindings();
      renderAnnotations();
      updateFindingCount();
    });
    item.append(text, remove);
    els.findings.appendChild(item);
  }
  updateFindingCount();
}

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

function renderAnnotations() {
  for (const [file, instance] of instances) {
    const annotations: DiffLineAnnotation<FindingMeta>[] = 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 },
      }));
    instance.setLineAnnotations(annotations);
  }
}

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 ?? {}) },
  });
  if (!res.ok) {
    const data = await res.json().catch(() => ({}));
    throw new Error(data.error ?? `${res.status} ${res.statusText}`);
  }
  return res.json() as Promise<T>;
}

function startHeartbeat() {
  heartbeat = window.setInterval(() => api("/api/heartbeat", { method: "POST", body: "{}" }).catch(() => undefined), 5000);
}

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

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

function readThemeMode(): ThemeMode {
  const stored = localStorage.getItem("diff-review-theme");
  return stored === "dark" || stored === "light" || stored === "system" ? stored : "system";
}

function applyThemeMode(mode: ThemeMode) {
  document.documentElement.dataset.theme = mode;
}

function diffUnsafeCSS() {
  return `
    :host, pre, code, [data-line], [data-code], [data-content], [data-line-number] {
      font-family: 'Nugu Code Nerd', 'JetBrains Mono', 'Fira Code', ui-monospace, SFMono-Regular, Menlo, Consolas, monospace !important;
      font-size: 12px;
      line-height: 1.55;
    }
  `;
}

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

function must(id: 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 globalThis.CSS?.escape ? CSS.escape(value) : value.replace(/"/g, "\\\"");
}