AI diff review
Multi-file coding agent diff review with live line stats, Accept/Reject/Undo controls, collapsible decided rows and stream replay.
pnpm dlx shadcn@latest add @haze/ai-diff-review---
import { Check, ChevronRight, RotateCcw, X } from "@lucide/astro";
import { cn } from "../../../lib/haze/utils";
interface DiffLine {
kind: "ctx" | "add" | "del";
num: string;
code: string;
}
interface DiffFile {
id: string;
path: string;
isNew?: boolean;
additions: number;
deletions: number;
lines: DiffLine[];
}
interface Props {
id?: string;
heading?: string;
summaryNote?: string;
files?: DiffFile[];
class?: string;
}
const {
id = "haze-ai-diff-review",
heading = "Agent diff review",
files = [
{
id: "validate",
path: "src/auth/validate.ts",
isNew: true,
additions: 5,
deletions: 0,
lines: [
{ kind: "add", num: "1", code: "export function isExpired(expiresAt: number) {" },
{ kind: "add", num: "2", code: " return expiresAt <= Date.now();" },
{ kind: "add", num: "3", code: "}" },
{ kind: "add", num: "4", code: "export function isNearExpiry(expiresAt: number, windowMs = 60_000) {" },
{ kind: "add", num: "5", code: " return expiresAt - Date.now() <= windowMs;" },
{ kind: "ctx", num: "6", code: "}" },
],
},
{
id: "session",
path: "src/auth/session.ts",
additions: 5,
deletions: 4,
lines: [
{ kind: "ctx", num: "12", code: "export async function rotateSession(jar: CookieJar, sid: string) {" },
{ kind: "del", num: "13", code: " const record = await store.get(sid);" },
{ kind: "del", num: "14", code: " if (!record) return null;" },
{ kind: "del", num: "15", code: " return issueCookie(jar, record.userId);" },
{ kind: "add", num: "13", code: " const record = await store.consume(sid);" },
{ kind: "add", num: "14", code: " if (!record || isExpired(record.expiresAt)) {" },
{ kind: "add", num: "15", code: ' jar.clear("sid");' },
{ kind: "add", num: "16", code: " return null;" },
{ kind: "add", num: "17", code: " }" },
{ kind: "del", num: "16", code: " // reuse previous cookie flags" },
{ kind: "ctx", num: "18", code: ' return issueCookie(jar, record.userId, { sameSite: "lax" });' },
{ kind: "ctx", num: "19", code: "}" },
],
},
{
id: "spec",
path: "tests/session.spec.ts",
additions: 4,
deletions: 2,
lines: [
{ kind: "ctx", num: "41", code: 'test("invalidates expired tokens on rotation", async () => {' },
{ kind: "del", num: "42", code: " const next = await rotateSession(jar, expiredId);" },
{ kind: "del", num: "43", code: " expect(next).toBeDefined();" },
{ kind: "add", num: "42", code: " const rotated = await rotateSession(jar, expiredId);" },
{ kind: "add", num: "43", code: " expect(rotated).toBeNull();" },
{ kind: "add", num: "44", code: ' expect(jar.get("sid")).toBeUndefined();' },
{ kind: "add", num: "45", code: " expect(await store.get(expiredId)).toBeNull();" },
{ kind: "ctx", num: "46", code: "});" },
],
},
],
class: className,
} = Astro.props;
const totalAdd = files.reduce((sum, f) => sum + f.additions, 0);
const totalDel = files.reduce((sum, f) => sum + f.deletions, 0);
const defaultOpenIndex = files.length > 1 ? 1 : 0;
function splitPath(fullPath: string) {
const slash = fullPath.lastIndexOf("/");
if (slash === -1) return { dir: "", name: fullPath };
return { dir: fullPath.slice(0, slash + 1), name: fullPath.slice(slash + 1) };
}
function diffSquares(add: number, del: number): ("add" | "del" | "empty")[] {
const total = add + del;
if (total === 0) return ["empty", "empty", "empty", "empty", "empty"];
let green = Math.round((add / total) * 5);
let red = 5 - green;
if (add > 0 && green === 0) {
green = 1;
red = 4;
}
if (del > 0 && red === 0) {
red = 1;
green = 4;
}
return [...Array<"add">(green).fill("add"), ...Array<"del">(red).fill("del")];
}
---
<section aria-labelledby={`${id}-title`} data-haze-ai-diff-review class={cn("bg-background px-4 py-10 sm:px-6 sm:py-14", className)}>
<h2 id={`${id}-title`} class="sr-only">{heading}</h2>
<div class="mx-auto max-w-lg rounded-2xl border border-border bg-muted/40 p-1.5 shadow-key">
{/* Header strip */}
<div class="flex items-center justify-between gap-2 px-3 py-2.5">
<div class="flex min-w-0 items-baseline gap-2.5">
<span class="text-sm font-semibold text-foreground">Editing files</span>
<span class="inline-flex items-baseline gap-1.5 font-mono text-xs font-medium tabular-nums">
<span data-adr-total-add class="text-success">+{totalAdd}</span>
<span data-adr-total-del class="text-destructive">−{totalDel}</span>
</span>
</div>
<button
type="button"
data-adr-replay
class="inline-flex min-h-8 shrink-0 cursor-pointer items-center gap-1.5 rounded-lg px-2 text-xs font-medium text-muted-foreground transition-colors duration-150 ease-snappy hover:bg-accent hover:text-foreground focus-visible:outline-2 focus-visible:outline-offset-1 focus-visible:outline-ring"
>
<RotateCcw class="size-3" aria-hidden="true" />
Replay
</button>
</div>
{/* Inner file list */}
<ul role="list" class="divide-y divide-border overflow-hidden rounded-xl border border-border bg-card">
{
files.map((file, idx) => {
const { dir, name } = splitPath(file.path);
const squares = diffSquares(file.additions, file.deletions);
const isOpen = idx === defaultOpenIndex;
const panelId = `${id}-panel-${file.id}`;
return (
<li
data-adr-file={file.id}
data-path={file.path}
data-add={String(file.additions)}
data-del={String(file.deletions)}
data-decision="pending"
data-open={isOpen ? "true" : "false"}
>
{/* Accordion row header */}
<div class="flex flex-wrap items-center justify-between gap-2 px-3 py-2">
<button
type="button"
data-adr-toggle
aria-expanded={isOpen ? "true" : "false"}
aria-controls={panelId}
class="flex min-h-8 min-w-0 flex-1 cursor-pointer items-center gap-2 rounded-md text-left focus-visible:outline-2 focus-visible:outline-offset-1 focus-visible:outline-ring"
>
<span
data-adr-chevron
class={cn("inline-flex shrink-0 text-muted-foreground transition-transform duration-150 ease-snappy", isOpen && "rotate-90")}
aria-hidden="true"
>
<ChevronRight class="size-3.5" />
</span>
<span class="min-w-0 truncate font-mono text-xs/5">
<span class="text-muted-foreground">{dir}</span><span class="font-semibold text-foreground">{name}</span>
</span>
{file.isNew && (
<span class="shrink-0 rounded-md bg-success/14 px-1.5 py-0.5 font-mono text-[0.6875rem]/4 font-medium text-success">
new
</span>
)}
<span data-adr-badge hidden class="shrink-0 rounded-md px-1.5 py-0.5 text-[0.6875rem]/4 font-medium"></span>
</button>
<div class="flex shrink-0 items-center gap-2">
<span class="inline-flex items-center gap-1 font-mono text-xs tabular-nums">
<span class="text-success">+{file.additions}</span>
<span class="text-destructive">−{file.deletions}</span>
</span>
<span class="hidden items-center gap-0.5 sm:inline-flex" aria-hidden="true">
{squares.map((sq) => (
<span
class={cn(
"size-1.5 rounded-xs",
sq === "add" && "bg-success",
sq === "del" && "bg-destructive",
sq === "empty" && "bg-muted",
)}
/>
))}
</span>
<div data-adr-pending-actions class="flex items-center gap-0.5">
<button
type="button"
data-adr-act="rejected"
aria-label={`Reject changes in ${file.path}`}
class="grid size-8 cursor-pointer place-items-center rounded-md text-muted-foreground transition-colors duration-150 ease-snappy hover:bg-destructive/10 hover:text-destructive focus-visible:outline-2 focus-visible:outline-offset-1 focus-visible:outline-ring"
>
<X class="size-3.5" aria-hidden="true" />
</button>
<button
type="button"
data-adr-act="accepted"
aria-label={`Accept changes in ${file.path}`}
class="grid size-8 cursor-pointer place-items-center rounded-md text-muted-foreground transition-colors duration-150 ease-snappy hover:bg-success/10 hover:text-success focus-visible:outline-2 focus-visible:outline-offset-1 focus-visible:outline-ring"
>
<Check class="size-3.5" aria-hidden="true" />
</button>
</div>
<div data-adr-decided-actions hidden>
<button
type="button"
data-adr-act="pending"
aria-label={`Undo decision for ${file.path}`}
class="inline-flex min-h-8 cursor-pointer items-center rounded-md px-2 text-xs font-medium text-muted-foreground transition-colors duration-150 ease-snappy hover:bg-accent hover:text-foreground focus-visible:outline-2 focus-visible:outline-offset-1 focus-visible:outline-ring"
>
Undo
</button>
</div>
</div>
</div>
{/* Expanded diff hunk */}
<div id={panelId} data-adr-body hidden={!isOpen} class="px-3 pb-3">
<div class="overflow-x-auto rounded-lg border border-border bg-muted/35 py-1.5">
<div class="min-w-max font-mono text-xs/6">
{file.lines.map((line) => (
<div
class={cn(
"flex items-baseline gap-2.5 px-3",
line.kind === "add" && "bg-success/10 text-success",
line.kind === "del" && "bg-destructive/10 text-destructive",
line.kind === "ctx" && "text-muted-foreground",
)}
>
<span class="w-5 shrink-0 text-right text-[0.6875rem] text-muted-foreground select-none tabular-nums">{line.num}</span>
<span class="w-3 shrink-0 text-center font-semibold select-none" aria-hidden="true">
{line.kind === "add" ? "+" : line.kind === "del" ? "−" : " "}
</span>
<code class="whitespace-pre">{line.code}</code>
</div>
))}
</div>
</div>
</div>
</li>
);
})
}
</ul>
<p data-adr-summary hidden class="px-3 pt-2 pb-1 text-xs/5 text-muted-foreground animate-rise"></p>
</div>
<p data-adr-status role="status" class="sr-only"></p>
</section>
<script>
function initAiDiffReview() {
document.querySelectorAll<HTMLElement>("[data-haze-ai-diff-review]").forEach((root) => {
if (root.hasAttribute("data-enhanced")) return;
root.setAttribute("data-enhanced", "");
const totalAddEl = root.querySelector<HTMLElement>("[data-adr-total-add]");
const totalDelEl = root.querySelector<HTMLElement>("[data-adr-total-del]");
const replayBtn = root.querySelector<HTMLButtonElement>("[data-adr-replay]");
const summaryEl = root.querySelector<HTMLElement>("[data-adr-summary]");
const status = root.querySelector<HTMLElement>("[data-adr-status]");
const cards = Array.from(root.querySelectorAll<HTMLElement>("[data-adr-file]"));
if (!totalAddEl || !totalDelEl || !cards.length) return;
let streamId = 0;
const timers: number[] = [];
const clearTimers = () => {
while (timers.length) window.clearTimeout(timers.pop());
};
const setCardOpen = (card: HTMLElement, open: boolean) => {
card.setAttribute("data-open", open ? "true" : "false");
const toggle = card.querySelector<HTMLButtonElement>("[data-adr-toggle]");
const chevron = card.querySelector<HTMLElement>("[data-adr-chevron]");
const body = card.querySelector<HTMLElement>("[data-adr-body]");
if (toggle) toggle.setAttribute("aria-expanded", String(open));
if (chevron) chevron.classList.toggle("rotate-90", open);
if (body) body.hidden = !open;
};
const openSingle = (target: HTMLElement | null) => {
cards.forEach((card) => setCardOpen(card, card === target));
};
const updateAggregates = () => {
let activeAdd = 0;
let activeDel = 0;
let accepted = 0;
let rejected = 0;
cards.forEach((card) => {
const decision = card.getAttribute("data-decision") ?? "pending";
const add = Number(card.dataset.add ?? 0);
const del = Number(card.dataset.del ?? 0);
if (decision !== "rejected") {
activeAdd += add;
activeDel += del;
}
if (decision === "accepted") accepted++;
if (decision === "rejected") rejected++;
});
const reviewed = accepted + rejected;
totalAddEl.textContent = `+${activeAdd}`;
totalDelEl.textContent = `\u2212${activeDel}`;
if (summaryEl) {
const allDone = reviewed === cards.length;
summaryEl.hidden = !allDone;
if (allDone) {
summaryEl.textContent = `All ${cards.length} files reviewed (${accepted} accepted, ${rejected} rejected).`;
}
}
};
const setCardDecision = (card: HTMLElement, decision: "pending" | "accepted" | "rejected", announce: boolean) => {
card.setAttribute("data-decision", decision);
const badge = card.querySelector<HTMLElement>("[data-adr-badge]");
const pendingActs = card.querySelector<HTMLElement>("[data-adr-pending-actions]");
const decidedActs = card.querySelector<HTMLElement>("[data-adr-decided-actions]");
const filePath = card.dataset.path ?? "file";
if (decision === "pending") {
if (badge) badge.hidden = true;
if (pendingActs) pendingActs.hidden = false;
if (decidedActs) decidedActs.hidden = true;
openSingle(card);
} else {
if (badge) {
badge.hidden = false;
badge.textContent = decision === "accepted" ? "Accepted" : "Rejected";
badge.className =
decision === "accepted"
? "shrink-0 rounded-md bg-success/14 px-1.5 py-0.5 text-[0.6875rem]/4 font-medium text-success"
: "shrink-0 rounded-md bg-destructive/14 px-1.5 py-0.5 text-[0.6875rem]/4 font-medium text-destructive";
}
if (pendingActs) pendingActs.hidden = true;
if (decidedActs) decidedActs.hidden = false;
if (card.getAttribute("data-open") === "true") {
const nextPending = cards.find((c) => c !== card && c.getAttribute("data-decision") === "pending") ?? null;
openSingle(nextPending);
}
}
updateAggregates();
if (announce && status) {
if (decision === "accepted") status.textContent = `Accepted changes in ${filePath}.`;
else if (decision === "rejected") status.textContent = `Rejected changes in ${filePath}.`;
else status.textContent = `Reopened diff for ${filePath}.`;
}
};
cards.forEach((card) => {
const toggle = card.querySelector<HTMLButtonElement>("[data-adr-toggle]");
toggle?.addEventListener("click", () => {
const isOpen = card.getAttribute("data-open") === "true";
openSingle(isOpen ? null : card);
});
card.querySelectorAll<HTMLButtonElement>("[data-adr-act]").forEach((btn) => {
btn.addEventListener("click", () => {
const next = btn.dataset.adrAct;
if (next === "accepted" || next === "rejected" || next === "pending") {
setCardDecision(card, next, true);
}
});
});
});
const replayStream = () => {
const myStream = ++streamId;
clearTimers();
const reduced = window.matchMedia("(prefers-reduced-motion: reduce)").matches;
const defaultIdx = cards.length > 1 ? 1 : 0;
cards.forEach((card) => {
card.setAttribute("data-decision", "pending");
const badge = card.querySelector<HTMLElement>("[data-adr-badge]");
const pendingActs = card.querySelector<HTMLElement>("[data-adr-pending-actions]");
const decidedActs = card.querySelector<HTMLElement>("[data-adr-decided-actions]");
if (badge) badge.hidden = true;
if (pendingActs) pendingActs.hidden = false;
if (decidedActs) decidedActs.hidden = true;
setCardOpen(card, false);
card.classList.remove("animate-rise");
if (!reduced) card.hidden = true;
});
updateAggregates();
if (reduced) {
cards.forEach((card, idx) => {
card.hidden = false;
setCardOpen(card, idx === defaultIdx);
});
if (status) status.textContent = `Replayed diff stream for ${cards.length} files.`;
return;
}
if (status) status.textContent = `Streaming ${cards.length} edited files…`;
cards.forEach((card, idx) => {
timers.push(
window.setTimeout(() => {
if (myStream !== streamId) return;
card.hidden = false;
card.classList.add("animate-rise");
if (idx === cards.length - 1) {
openSingle(cards[defaultIdx] ?? cards[0]);
if (status) status.textContent = `Loaded ${cards.length} edited files for review.`;
}
}, idx * 200),
);
});
};
replayBtn?.addEventListener("click", replayStream);
updateAggregates();
});
}
initAiDiffReview();
document.addEventListener("astro:page-load", initAiDiffReview);
</script>When to use
- Reviewing a multi-file patch produced by a coding agent with independent Accept and Reject actions per file
- Collapsing reviewed files into compact status rows while updating aggregate line counts live
- Allowing engineers to undo any per-file decision or replay the incoming file stream
When not to use
- Displaying a read-only side-by-side comparison without agent review state; use diff-viewer
- Showing a single inline prose rewrite suggestion inside a paragraph; use ai-inline-rewrite
Installation
Add the Haze registry to components.json once, then install AI diff review with the shadcn CLI. Works in any Astro project with Tailwind CSS v4.
pnpm dlx shadcn@latest add @haze/ai-diff-reviewnpx shadcn@latest add @haze/ai-diff-reviewyarn dlx shadcn@latest add @haze/ai-diff-reviewbunx --bun shadcn@latest add @haze/ai-diff-reviewFirst time? Registry and theme setup
1. Add to components.json:
{
"registries": {
"@haze": "http://localhost:4329/r/{name}.json"
}
}2. Install the theme once: npx shadcn@latest add @haze/theme, then import it after Tailwind in your global CSS:@import "./haze.css";
API reference
| Prop | Type | Default | Description |
|---|---|---|---|
| id | string | "haze-ai-diff-review" | Unique prefix for section heading IDs. |
| heading | string | "Agent diff review" | Panel header title. |
| summaryNote | string | "Rotate expiring session tokens and clear stale cookies" | One-line patch description under the heading. |
| files | DiffFile[] | 3 edited TypeScript files (+14 −6) | File patches with paths, line counts and semantic diff hunks. |
| class | string | – | Extra classes on the outer section. |
Keyboard interactions
- Tab
- Move across Replay stream and each file's Reject, Accept or Undo controls
- EnterSpace
- Accept, reject or undo a file patch or replay the file stream
Accessibility
- Diff lines pair semantic success and destructive coloring with explicit plus and minus symbols inside horizontally scrollable hunks.
- Accepting, rejecting, undoing or replaying files updates live counters and announces the change through a polite role="status" element.
Notes for AI
Copy into Claude Code, Cursor, Codex or any coding agent. Agents can also read the Markdown version of this page.
Install and use
Install the Haze UI block "AI diff review" with `npx shadcn@latest add @haze/ai-diff-review`. If components.json has no "@haze" registry yet, add "registries": { "@haze": "http://localhost:4329/r/{name}.json" }. If src/styles/haze.css does not exist yet, run `npx shadcn@latest add @haze/theme` once and import it from the global stylesheet after Tailwind. The CLI stops at an overwrite question when a Haze file already exists and differs, even with --yes, and then installs nothing after it: read its output. If the user has not edited their Haze files, re-run with --overwrite to take the registry versions; if they have, ask them before overwriting. Then import AiDiffReview from "@/components/haze/blocks/ai-diff-review.astro" (or the relative path) and render it where it fits the page. Keep Haze token classes (bg-background, text-muted-foreground, border-border...) and never hardcode colors. Docs: http://localhost:4329/blocks/ai-diff-review.md
Customize with real content
Adapt the Haze ai-diff-review block for our product. Replace the demo values of these props with our real content: id, heading, summaryNote, files, class. Keep the layout, the heading level rules and these accessibility details: Diff lines pair semantic success and destructive coloring with explicit plus and minus symbols inside horizontally scrollable hunks. Accepting, rejecting, undoing or replaying files updates live counters and announces the change through a polite role="status" element. Do not add raw color classes; use the Haze tokens.
Choose the right block
Before using ai-diff-review, check it fits: use it when reviewing a multi-file patch produced by a coding agent with independent accept and reject actions per file; collapsing reviewed files into compact status rows while updating aggregate line counts live; allowing engineers to undo any per-file decision or replay the incoming file stream. Avoid it when displaying a read-only side-by-side comparison without agent review state; use diff-viewer; showing a single inline prose rewrite suggestion inside a paragraph; use ai-inline-rewrite. Alternatives: @haze/diff-viewer, @haze/agent-run, @haze/ai-inline-rewrite.
Dependencies
- npm: @lucide/astro
- @haze/utils
- @haze/theme (one-time setup)
Source · Original Haze UI work.