repositories / dotfiles

dotfiles

bugabingas dorkfiles

owned by bugabinga

feat(diff-review): keep browser review live

862c6fdfe8b41dce62f4313bc638e49e45b683a5

Oliver Jan Krylow <oliver@bugabinga.net> ·

unsigned

Browse filesCompare with HEAD

Changed files (13)

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

Modified
30 30 <main id="main">
31 31 <header id="topbar">
32 32 <div>
33 - <div class="eyebrow">Review changed lines</div>
33 + <div class="topbar-title">Review changed lines</div>
34 34 <div id="summary">Select a changed line to add a finding.</div>
35 35 </div>
36 36 <div id="finding-count" class="count-pill">0 findings</div>
63 63 </select>
64 64 </label>
65 65 </div>
66 - <label>Comment
67 - <textarea id="comment" rows="5" placeholder="What should the agent inspect?"></textarea>
68 - </label>
69 - <label>Finding notes
70 - <textarea id="finding-notes" rows="3" placeholder="Optional context for this finding"></textarea>
66 + <label>Finding
67 + <textarea id="comment" rows="6" placeholder="Describe the issue or question for the selected line"></textarea>
71 68 </label>
72 69 <button id="add" disabled>Add finding</button>
73 70 </section>
78 75 </section>
80 77 <section class="card">
81 - <div class="card-title">Round notes</div>
82 - <textarea id="notes" rows="4" placeholder="Optional notes for the agent"></textarea>
78 + <div class="card-title">Review notes</div>
79 + <textarea id="notes" rows="4" placeholder="Optional context for the whole review"></textarea>
83 80 </section>
85 82 <footer class="actions">
86 83 <button id="cancel">Cancel</button>
87 - <button id="submit">Submit review</button>
84 + <button id="submit">Send to Pi</button>
88 85 </footer>
89 86 <div id="status" role="status"></div>
90 87 </aside>

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

Modified
1 1 import "./style.css";
2 2 import { FileDiff, parsePatchFiles, type DiffLineAnnotation, type FileDiffMetadata, type SelectedLineRange } from "@pierre/diffs";
3 3 import { FileTree, type GitStatusEntry } from "@pierre/trees";
5 -type ReviewCategory = "bug" | "style" | "perf" | "question";
6 -type ReviewSeverity = "high" | "medium" | "low";
7 -type ReviewSide = "additions" | "deletions";
9 -type FindingDraft = {
10 - file: string;
11 - side: ReviewSide;
12 - startLine: number;
13 - endLine: number;
14 - category: ReviewCategory;
15 - severity: ReviewSeverity;
16 - comment: string;
17 - notes?: string;
18 -};
20 -type ReviewPayload = {
21 - round: number;
22 - source: { kind: "working-tree" | "staged" | "base"; base?: string; files?: string[] };
23 - diffText: string;
24 - files: Array<{ path: string; prevPath?: string; status: "added" | "modified" | "deleted" | "renamed" | "binary"; additions: number; deletions: number }>;
25 - carriedFindings: unknown[];
26 -};
4 +import { HEARTBEAT_INTERVAL_MS, REVIEW_POLL_INTERVAL_MS } from "../constants.js";
5 +import type { FindingDraft, ReviewCategory, ReviewPayload, ReviewSeverity, ReviewSide } from "../types.js";
28 7 type FindingMeta = { findingId: string; severity: ReviewSeverity; category: ReviewCategory; comment: string };
29 8 type ThemeMode = "system" | "dark" | "light";
9 +type ReviewSelection = { file: string; side: ReviewSide; startLine: number; endLine: number };
11 +type Elements = {
12 + meta: HTMLElement;
13 + summary: HTMLElement;
14 + findingCount: HTMLElement;
15 + tree: HTMLElement;
16 + diffs: HTMLElement;
17 + selection: HTMLElement;
18 + severity: HTMLSelectElement;
19 + category: HTMLSelectElement;
20 + comment: HTMLTextAreaElement;
21 + add: HTMLButtonElement;
22 + findings: HTMLElement;
23 + notes: HTMLTextAreaElement;
24 + cancel: HTMLButtonElement;
25 + submit: HTMLButtonElement;
26 + status: HTMLElement;
27 + themeMode: HTMLSelectElement;
28 +};
30 +const ROUTES = {
31 + review: "/api/review",
32 + heartbeat: "/api/heartbeat",
33 + cancel: "/api/cancel",
34 + validateFinding: "/api/finding/validate",
35 + submit: "/api/submit",
36 +} as const;
37 +const THEME_STORAGE_KEY = "diff-review-theme";
38 +const DIFF_FONT_CSS = `
39 + :host, pre, code, [data-line], [data-code], [data-content], [data-line-number] {
40 + font-family: 'Nugu Code Nerd', 'JetBrains Mono', 'Fira Code', ui-monospace, SFMono-Regular, Menlo, Consolas, monospace !important;
41 + font-size: 12px;
42 + line-height: 1.55;
43 + }
44 +`;
45 +const REVIEW_CATEGORIES = ["bug", "style", "perf", "question"] as const satisfies readonly ReviewCategory[];
46 +const REVIEW_SEVERITIES = ["high", "medium", "low"] as const satisfies readonly ReviewSeverity[];
47 +const THEME_MODES = ["system", "dark", "light"] as const satisfies readonly ThemeMode[];
31 49 const token = new URLSearchParams(location.search).get("token") ?? "";
32 -const findings: FindingDraft[] = [];
33 -const instances = new Map<string, FileDiff<FindingMeta>>();
34 -let selected: { file: string; range: SelectedLineRange } | undefined;
35 -let heartbeat: number | undefined;
36 -let themeMode: ThemeMode = readThemeMode();
38 -const els = {
50 +const els: Elements = {
39 51 meta: must("meta"),
40 52 summary: must("summary"),
41 53 findingCount: must("finding-count"),
45 57 severity: mustSelect("severity"),
46 58 category: mustSelect("category"),
47 59 comment: mustText("comment"),
48 - findingNotes: mustText("finding-notes"),
49 60 add: mustButton("add"),
50 61 findings: must("findings"),
51 62 notes: mustText("notes"),
55 66 themeMode: mustSelect("theme-mode"),
69 +const findings: FindingDraft[] = [];
70 +const diffViews = new Map<string, FileDiff<FindingMeta>>();
71 +const systemTheme = window.matchMedia("(prefers-color-scheme: light)");
72 +let fileTree: FileTree | undefined;
73 +let selected: ReviewSelection | undefined;
74 +let heartbeat: number | undefined;
75 +let reviewPoll: number | undefined;
76 +let reviewHash = "";
77 +let closing = false;
78 +let themeMode: ThemeMode = readThemeMode();
58 80 applyThemeMode(themeMode);
59 81 els.themeMode.value = themeMode;
61 -main().catch((err) => setStatus(String(err?.message ?? err), true));
83 +main().catch((err) => setStatus(errorMessage(err), "error"));
84 +window.addEventListener("pagehide", closeFromBrowser);
85 +systemTheme.addEventListener("change", () => {
86 + if (themeMode === "system") applyThemeMode(themeMode);
87 +});
63 89 async function main() {
64 90 if (!token) throw new Error("Missing review token");
65 - const review = await api<ReviewPayload>("/api/review");
91 + const review = await api<ReviewPayload>(ROUTES.review);
66 92 startHeartbeat();
67 - renderMeta(review);
68 - renderTree(review);
69 - renderDiffs(review);
93 + startReviewPolling();
94 + renderReview(review);
70 95 wireActions();
71 96 setStatus("Ready");
99 +function renderReview(review: ReviewPayload) {
100 + reviewHash = hashReview(review);
101 + renderMeta(review);
102 + renderTree(review);
103 + renderDiffs(review);
104 + renderAnnotations();
74 107 function renderMeta(review: ReviewPayload) {
75 - const additions = review.files.reduce((sum, file) => sum + file.additions, 0);
76 - const deletions = review.files.reduce((sum, file) => sum + file.deletions, 0);
108 + const totals = review.files.reduce((sum, file) => ({ additions: sum.additions + file.additions, deletions: sum.deletions + file.deletions }), { additions: 0, deletions: 0 });
77 109 els.meta.textContent = `round ${review.round} · ${review.source.kind} · ${review.files.length} files`;
78 - els.summary.textContent = `${review.files.length} files · +${additions} −${deletions}. Click a changed line, describe the issue, submit to Pi.`;
110 + const skipped = review.skippedFiles.length === 0 ? "" : ` · skipped ${review.skippedFiles.length} oversized/binary file${review.skippedFiles.length === 1 ? "" : "s"}`;
111 + els.summary.textContent = `${review.files.length} files · +${totals.additions} −${totals.deletions}${skipped}. Click a changed line, describe the issue, send findings to Pi, keep reviewing as the diff changes.`;
79 112 updateFindingCount();
82 115 function renderTree(review: ReviewPayload) {
83 - const gitStatus: GitStatusEntry[] = review.files.map((file) => ({ path: file.path, status: toGitStatus(file.status) }));
84 - const tree = new FileTree({
116 + fileTree?.cleanUp();
117 + fileTree = new FileTree({
85 118 paths: review.files.map((file) => file.path),
86 119 search: true,
87 120 initialExpansion: "open",
88 - gitStatus,
89 - onSelectionChange(paths) {
90 - const path = paths[0];
91 - if (!path) return;
92 - document.querySelector<HTMLElement>(`[data-file-section="${cssEscape(path)}"]`)?.scrollIntoView({ block: "start" });
93 - },
121 + gitStatus: review.files.map((file) => ({ path: file.path, status: toGitStatus(file.status) })) satisfies GitStatusEntry[],
122 + onSelectionChange: ([path]) => scrollToFile(path),
95 - tree.render({ fileTreeContainer: els.tree });
124 + fileTree.render({ fileTreeContainer: els.tree });
98 127 function renderDiffs(review: ReviewPayload) {
99 - const patches = parsePatchFiles(review.diffText, `diff-review-${review.round}`, true);
100 - for (const patch of patches) {
128 + for (const view of diffViews.values()) view.cleanUp();
129 + diffViews.clear();
130 + els.diffs.replaceChildren();
131 + selected = undefined;
132 + setSelection("", null);
133 + for (const patch of parsePatchFiles(review.diffText, `diff-review-${review.round}`, true)) {
101 134 for (const fileDiff of patch.files) renderFileDiff(fileDiff);
105 138 function renderFileDiff(fileDiff: FileDiffMetadata) {
106 - const section = document.createElement("section");
107 - section.className = "file-section";
108 - section.dataset.fileSection = fileDiff.name;
110 - const title = document.createElement("h2");
111 - title.className = "file-title";
112 - title.textContent = fileDiff.prevName && fileDiff.prevName !== fileDiff.name ? `${fileDiff.prevName} → ${fileDiff.name}` : fileDiff.name;
113 - section.appendChild(title);
114 - els.diffs.appendChild(section);
116 - const instance = new FileDiff<FindingMeta>({
139 + const section = fileSection(fileDiff);
140 + const view = new FileDiff<FindingMeta>({
117 141 theme: { dark: "pierre-dark", light: "pierre-light" },
118 142 diffStyle: "split",
119 143 overflow: "scroll",
121 145 enableGutterUtility: true,
122 146 lineHoverHighlight: "both",
123 147 themeType: themeMode,
124 - unsafeCSS: diffUnsafeCSS(),
125 - onLineSelected: (range) => openDrawer(fileDiff.name, range),
126 - onGutterUtilityClick: (range) => openDrawer(fileDiff.name, range),
127 - onLineClick: ({ lineNumber, annotationSide }) => openDrawer(fileDiff.name, { start: lineNumber, end: lineNumber, side: annotationSide, endSide: annotationSide }),
128 - onLineNumberClick: ({ lineNumber, annotationSide }) => openDrawer(fileDiff.name, { start: lineNumber, end: lineNumber, side: annotationSide, endSide: annotationSide }),
129 - renderAnnotation(annotation) {
130 - const chip = document.createElement("div");
131 - chip.className = "finding-chip";
132 - chip.textContent = `[${annotation.metadata.severity}][${annotation.metadata.category}] ${annotation.metadata.comment}`;
133 - return chip;
134 - },
148 + unsafeCSS: DIFF_FONT_CSS,
149 + onLineSelected: (range) => setSelection(fileDiff.name, range),
150 + onGutterUtilityClick: (range) => setSelection(fileDiff.name, range),
151 + onLineClick: ({ lineNumber, annotationSide }) => setSelection(fileDiff.name, singleLineRange(lineNumber, annotationSide)),
152 + onLineNumberClick: ({ lineNumber, annotationSide }) => setSelection(fileDiff.name, singleLineRange(lineNumber, annotationSide)),
153 + renderAnnotation: renderAnnotation,
136 - instance.render({ fileDiff, containerWrapper: section, lineAnnotations: [] });
137 - instances.set(fileDiff.name, instance);
155 + view.render({ fileDiff, containerWrapper: section, lineAnnotations: [] });
156 + diffViews.set(fileDiff.name, view);
140 -function openDrawer(file: string, range: SelectedLineRange | null) {
141 - if (!range) {
142 - selected = undefined;
143 - els.selection.textContent = "Click an added or deleted line.";
144 - els.selection.className = "selection-empty";
145 - els.add.disabled = true;
146 - return;
147 - }
159 +function fileSection(fileDiff: FileDiffMetadata) {
160 + const section = document.createElement("section");
161 + section.className = "file-section";
162 + section.dataset.fileSection = fileDiff.name;
164 + const title = document.createElement("h2");
165 + title.className = "file-title";
166 + title.textContent = fileTitle(fileDiff);
167 + section.appendChild(title);
168 + els.diffs.appendChild(section);
169 + return section;
172 +function fileTitle(fileDiff: FileDiffMetadata) {
173 + return fileDiff.prevName && fileDiff.prevName !== fileDiff.name ? `${fileDiff.prevName} → ${fileDiff.name}` : fileDiff.name;
176 +function renderAnnotation(annotation: DiffLineAnnotation<FindingMeta>) {
177 + const chip = document.createElement("div");
178 + chip.className = "finding-chip";
179 + chip.textContent = `[${annotation.metadata.severity}][${annotation.metadata.category}] ${annotation.metadata.comment}`;
180 + return chip;
183 +function setSelection(file: string, range: SelectedLineRange | null) {
184 + const next = normalizeSelection(file, range);
185 + selected = next;
186 + els.add.disabled = !next;
187 + els.selection.className = next ? "selection-active" : "selection-empty";
188 + els.selection.textContent = next ? selectionLabel(next) : "Click an added or deleted line.";
191 +function normalizeSelection(file: string, range: SelectedLineRange | null): ReviewSelection | undefined {
192 + if (!range) return undefined;
148 193 const side = range.side;
149 194 const endSide = range.endSide ?? side;
150 - if ((side !== "additions" && side !== "deletions") || endSide !== side) {
151 - selected = undefined;
152 - els.selection.textContent = "Only single-side additions/deletions selections are supported.";
153 - els.selection.className = "selection-empty";
154 - els.add.disabled = true;
155 - return;
156 - }
157 - selected = { file, range };
158 - const start = Math.min(range.start, range.end);
159 - const end = Math.max(range.start, range.end);
160 - els.selection.textContent = `${file}:${start}${start === end ? "" : `-${end}`} ${side}`;
161 - els.selection.className = "selection-active";
162 - els.add.disabled = false;
195 + if (!isReviewSide(side) || endSide !== side) return undefined;
196 + return { file, side, startLine: Math.min(range.start, range.end), endLine: Math.max(range.start, range.end) };
199 +function singleLineRange(lineNumber: number, side: SelectedLineRange["side"]): SelectedLineRange | null {
200 + return side ? { start: lineNumber, end: lineNumber, side, endSide: side } : null;
203 +function selectionLabel(selection: ReviewSelection) {
204 + const { file, startLine, endLine, side } = selection;
205 + return `${file}:${startLine}${startLine === endLine ? "" : `-${endLine}`} ${side}`;
165 208 function wireActions() {
166 - els.themeMode.addEventListener("change", () => {
167 - themeMode = els.themeMode.value as ThemeMode;
168 - localStorage.setItem("diff-review-theme", themeMode);
169 - applyThemeMode(themeMode);
170 - for (const instance of instances.values()) instance.setThemeType(themeMode);
171 - });
209 + els.themeMode.addEventListener("change", updateThemeMode);
210 + els.add.addEventListener("click", addFinding);
211 + els.submit.addEventListener("click", submitReview);
212 + els.cancel.addEventListener("click", cancelReview);
173 - els.add.addEventListener("click", async () => {
174 - if (!selected) return;
175 - const comment = els.comment.value.trim();
176 - if (!comment) return setStatus("Comment required", true);
177 - els.add.disabled = true;
178 - const side = selected.range.side as ReviewSide;
179 - const draft: FindingDraft = {
180 - file: selected.file,
181 - side,
182 - startLine: Math.min(selected.range.start, selected.range.end),
183 - endLine: Math.max(selected.range.start, selected.range.end),
184 - category: els.category.value as ReviewCategory,
185 - severity: els.severity.value as ReviewSeverity,
186 - comment,
187 - ...(els.findingNotes.value.trim() && { notes: els.findingNotes.value.trim() }),
188 - };
189 - try {
190 - await api("/api/finding/validate", { method: "POST", body: JSON.stringify(draft) });
191 - findings.push(draft);
192 - els.comment.value = "";
193 - els.findingNotes.value = "";
194 - renderFindings();
195 - renderAnnotations();
196 - setStatus("Finding added");
197 - } catch (err) {
198 - setStatus((err as Error).message, true);
199 - } finally {
200 - els.add.disabled = false;
201 - }
202 - });
215 +function updateThemeMode() {
216 + themeMode = themeModeFromValue(els.themeMode.value);
217 + localStorage.setItem(THEME_STORAGE_KEY, themeMode);
218 + applyThemeMode(themeMode);
219 + for (const view of diffViews.values()) view.setThemeType(themeMode);
204 - els.submit.addEventListener("click", async () => {
205 - if (findings.length === 0 && !confirm("Submit review with no findings?")) return;
206 - els.submit.disabled = true;
207 - els.cancel.disabled = true;
208 - try {
209 - await api("/api/submit", { method: "POST", body: JSON.stringify({ notes: els.notes.value, findings }) });
210 - stopHeartbeat();
211 - setStatus("Submitted — return to Pi", false, true);
212 - } catch (err) {
213 - els.submit.disabled = false;
214 - els.cancel.disabled = false;
215 - setStatus((err as Error).message, true);
216 - }
217 - });
222 +async function addFinding() {
223 + const draft = draftFromSelection();
224 + if (!draft) return;
225 + els.add.disabled = true;
226 + try {
227 + await api(ROUTES.validateFinding, postJson(draft));
228 + findings.push(draft);
229 + clearFindingForm();
230 + renderFindings();
231 + renderAnnotations();
232 + setStatus("Finding added");
233 + } catch (err) {
234 + setStatus(errorMessage(err), "error");
235 + } finally {
236 + els.add.disabled = false;
219 - els.cancel.addEventListener("click", async () => {
220 - els.submit.disabled = true;
221 - els.cancel.disabled = true;
222 - await api("/api/cancel", { method: "POST", body: "{}" }).catch(() => undefined);
223 - stopHeartbeat();
224 - setStatus("Cancelled — return to Pi");
225 - });
240 +function draftFromSelection(): FindingDraft | undefined {
241 + if (!selected) return undefined;
242 + const comment = els.comment.value.trim();
243 + if (!comment) {
244 + setStatus("Comment required", "error");
245 + return undefined;
247 + return {
248 + ...selected,
249 + category: categoryFromValue(els.category.value),
250 + severity: severityFromValue(els.severity.value),
251 + comment,
252 + };
255 +async function submitReview() {
256 + if (findings.length === 0 && !els.notes.value.trim() && !confirm("Send empty review to Pi?")) return;
257 + setDoneButtonsDisabled(true);
258 + try {
259 + await api(ROUTES.submit, postJson({ notes: els.notes.value, findings }));
260 + findings.splice(0);
261 + els.notes.value = "";
262 + renderFindings();
263 + renderAnnotations();
264 + setStatus("Sent to Pi — keep reviewing or close tab to end", "ok");
265 + } catch (err) {
266 + setStatus(errorMessage(err), "error");
267 + } finally {
268 + setDoneButtonsDisabled(false);
272 +async function cancelReview() {
273 + closing = true;
274 + setDoneButtonsDisabled(true);
275 + await api(ROUTES.cancel, postJson({})).catch(() => undefined);
276 + cleanup();
277 + setStatus("Closed — return to Pi");
280 +function setDoneButtonsDisabled(disabled: boolean) {
281 + els.submit.disabled = disabled;
282 + els.cancel.disabled = disabled;
285 +function clearFindingForm() {
286 + els.comment.value = "";
228 289 function renderFindings() {
233 294 updateFindingCount();
234 295 return;
236 - for (const [index, finding] of findings.entries()) {
237 - const item = document.createElement("div");
238 - item.className = "finding-item";
239 - const text = document.createElement("div");
240 - text.textContent = `${index + 1}. [${finding.severity}][${finding.category}] ${finding.file}:${finding.startLine}${finding.startLine === finding.endLine ? "" : `-${finding.endLine}`} ${finding.side} — ${finding.comment}`;
241 - const remove = document.createElement("button");
242 - remove.className = "remove-finding";
243 - remove.type = "button";
244 - remove.textContent = "Remove";
245 - remove.addEventListener("click", () => {
246 - findings.splice(index, 1);
247 - renderFindings();
248 - renderAnnotations();
249 - updateFindingCount();
250 - });
251 - item.append(text, remove);
252 - els.findings.appendChild(item);
253 - }
297 + findings.forEach((finding, index) => els.findings.appendChild(findingItem(finding, index)));
254 298 updateFindingCount();
301 +function findingItem(finding: FindingDraft, index: number) {
302 + const item = document.createElement("div");
303 + item.className = "finding-item";
305 + const text = document.createElement("div");
306 + text.textContent = `${index + 1}. [${finding.severity}][${finding.category}] ${selectionLabel(finding)} — ${finding.comment}`;
308 + const remove = document.createElement("button");
309 + remove.className = "remove-finding";
310 + remove.type = "button";
311 + remove.textContent = "Remove";
312 + remove.addEventListener("click", () => removeFinding(index));
314 + item.append(text, remove);
315 + return item;
318 +function removeFinding(index: number) {
319 + findings.splice(index, 1);
320 + renderFindings();
321 + renderAnnotations();
257 324 function updateFindingCount() {
258 325 els.findingCount.textContent = `${findings.length} finding${findings.length === 1 ? "" : "s"}`;
261 328 function renderAnnotations() {
262 - for (const [file, instance] of instances) {
263 - const annotations: DiffLineAnnotation<FindingMeta>[] = findings
264 - .filter((finding) => finding.file === file)
265 - .map((finding, index) => ({
266 - side: finding.side,
267 - lineNumber: finding.startLine,
268 - metadata: { findingId: String(index), severity: finding.severity, category: finding.category, comment: finding.comment },
269 - }));
270 - instance.setLineAnnotations(annotations);
271 - }
329 + for (const [file, view] of diffViews) view.setLineAnnotations(annotationsFor(file));
332 +function annotationsFor(file: string): DiffLineAnnotation<FindingMeta>[] {
333 + return findings
334 + .filter((finding) => finding.file === file)
335 + .map((finding, index) => ({
336 + side: finding.side,
337 + lineNumber: finding.startLine,
338 + metadata: { findingId: String(index), severity: finding.severity, category: finding.category, comment: finding.comment },
339 + }));
274 342 async function api<T = unknown>(path: string, init: RequestInit = {}): Promise<T> {
276 344 ...init,
277 345 headers: { "Authorization": `Bearer ${token}`, "Content-Type": "application/json", ...(init.headers ?? {}) },
279 - if (!res.ok) {
280 - const data = await res.json().catch(() => ({}));
281 - throw new Error(data.error ?? `${res.status} ${res.statusText}`);
282 - }
283 - return res.json() as Promise<T>;
347 + const body = await res.text();
348 + const data = body ? JSON.parse(body) : undefined;
349 + if (!res.ok) throw new Error(errorPayload(data) ?? `${res.status} ${res.statusText}`);
350 + return data as T;
353 +function postJson(body: unknown): RequestInit {
354 + return { method: "POST", body: JSON.stringify(body) };
357 +function errorPayload(value: unknown) {
358 + return value && typeof value === "object" && "error" in value && typeof value.error === "string" ? value.error : undefined;
286 361 function startHeartbeat() {
287 - heartbeat = window.setInterval(() => api("/api/heartbeat", { method: "POST", body: "{}" }).catch(() => undefined), 5000);
362 + heartbeat = window.setInterval(() => api(ROUTES.heartbeat, postJson({})).catch(() => undefined), HEARTBEAT_INTERVAL_MS);
365 +function startReviewPolling() {
366 + reviewPoll = window.setInterval(refreshReview, REVIEW_POLL_INTERVAL_MS);
369 +async function refreshReview() {
370 + try {
371 + const review = await api<ReviewPayload>(ROUTES.review);
372 + const nextHash = hashReview(review);
373 + if (nextHash === reviewHash) return;
374 + renderReview(review);
375 + setStatus("Diff updated", "ok");
376 + } catch (err) {
377 + setStatus(errorMessage(err), "error");
381 +function hashReview(review: ReviewPayload) {
382 + return `${review.diffText}\0${review.skippedFiles.join("\0")}`;
290 385 function stopHeartbeat() {
292 387 heartbeat = undefined;
295 -function setStatus(text: string, error = false, ok = false) {
390 +function stopReviewPolling() {
391 + if (reviewPoll !== undefined) window.clearInterval(reviewPoll);
392 + reviewPoll = undefined;
395 +function cleanup() {
396 + stopHeartbeat();
397 + stopReviewPolling();
398 + fileTree?.cleanUp();
399 + for (const view of diffViews.values()) view.cleanUp();
402 +function closeFromBrowser() {
403 + if (closing) return;
404 + closing = true;
405 + navigator.sendBeacon?.(ROUTES.cancel, new Blob(["{}"], { type: "application/json" }));
406 + cleanup();
409 +function setStatus(text: string, tone: "neutral" | "error" | "ok" = "neutral") {
296 410 els.status.textContent = text;
297 - els.status.className = error ? "error" : ok ? "ok" : "";
411 + els.status.className = tone === "neutral" ? "" : tone;
300 414 function readThemeMode(): ThemeMode {
301 - const stored = localStorage.getItem("diff-review-theme");
302 - return stored === "dark" || stored === "light" || stored === "system" ? stored : "system";
415 + return themeModeFromValue(localStorage.getItem(THEME_STORAGE_KEY));
305 418 function applyThemeMode(mode: ThemeMode) {
306 - document.documentElement.dataset.theme = mode;
419 + document.documentElement.dataset.theme = mode === "system" ? (systemTheme.matches ? "light" : "dark") : mode;
420 + document.documentElement.dataset.themeMode = mode;
309 -function diffUnsafeCSS() {
310 - return `
311 - :host, pre, code, [data-line], [data-code], [data-content], [data-line-number] {
312 - font-family: 'Nugu Code Nerd', 'JetBrains Mono', 'Fira Code', ui-monospace, SFMono-Regular, Menlo, Consolas, monospace !important;
313 - font-size: 12px;
314 - line-height: 1.55;
315 - }
316 - `;
423 +function scrollToFile(path: string | undefined) {
424 + if (!path) return;
425 + document.querySelector<HTMLElement>(`[data-file-section="${cssEscape(path)}"]`)?.scrollIntoView({ block: "start" });
319 -function toGitStatus(status: string): GitStatusEntry["status"] {
320 - if (status === "added") return "added";
321 - if (status === "deleted") return "deleted";
322 - if (status === "renamed") return "renamed";
428 +function toGitStatus(status: ReviewPayload["files"][number]["status"]): GitStatusEntry["status"] {
429 + if (status === "added" || status === "deleted" || status === "renamed") return status;
323 430 return "modified";
326 -function must(id: string) {
433 +function themeModeFromValue(value: unknown): ThemeMode {
434 + return isOneOf(value, THEME_MODES) ? value : "system";
437 +function categoryFromValue(value: unknown): ReviewCategory {
438 + if (isOneOf(value, REVIEW_CATEGORIES)) return value;
439 + throw new Error(`Invalid category: ${String(value)}`);
442 +function severityFromValue(value: unknown): ReviewSeverity {
443 + if (isOneOf(value, REVIEW_SEVERITIES)) return value;
444 + throw new Error(`Invalid severity: ${String(value)}`);
447 +function isReviewSide(value: unknown): value is ReviewSide {
448 + return value === "additions" || value === "deletions";
451 +function isOneOf<T extends string>(value: unknown, choices: readonly T[]): value is T {
452 + return typeof value === "string" && choices.includes(value as T);
455 +function must(id: keyof Elements | string) {
327 456 const el = document.getElementById(id);
328 457 if (!el) throw new Error(`Missing #${id}`);
329 458 return el;
331 461 function mustButton(id: string) { return must(id) as HTMLButtonElement; }
332 462 function mustSelect(id: string) { return must(id) as HTMLSelectElement; }
333 463 function mustText(id: string) { return must(id) as HTMLTextAreaElement; }
335 465 function cssEscape(value: string) {
336 - return globalThis.CSS?.escape ? CSS.escape(value) : value.replace(/"/g, "\\\"");
466 + return CSS.escape(value);
469 +function errorMessage(err: unknown) {
470 + return err instanceof Error ? err.message : String(err);

pi/agent/extensions/diff-review/browser/style.css

Modified
80 80 --shadow: 0 18px 60px color-mix(in srgb, #000 14%, transparent);
83 -@media (prefers-color-scheme: light) {
84 - :root[data-theme="system"] {
85 - color-scheme: light;
86 - --nugu-debug: #a112a1;
87 - --nugu-error: #c0223c;
88 - --nugu-warning: #242317;
89 - --nugu-info: #13616e;
90 - --nugu-content-normal: #121212;
91 - --nugu-content-backdrop: #ededed;
92 - --nugu-content-accent: #ae2eae;
93 - --nugu-content-minor: #3b3b3b;
94 - --nugu-content-focus: #184e5b;
95 - --nugu-content-unfocus: #6f6f6f;
96 - --nugu-content-important-local: #715696;
97 - --nugu-content-important-global: #4f3c69;
98 - --nugu-ui-normal: #242424;
99 - --nugu-ui-backdrop: #dbdbdb;
100 - --nugu-ui-accent: #922792;
101 - --nugu-ui-minor: #292929;
102 - --nugu-ui-focus: #15333b;
103 - --nugu-ui-unfocus: #5d5d5d;
104 - --nugu-ui-important-local: #604980;
105 - --nugu-ui-important-global: #3e2f53;
106 - --panel: color-mix(in srgb, var(--nugu-ui-backdrop) 72%, white);
107 - --panel-2: color-mix(in srgb, var(--nugu-ui-backdrop) 88%, white);
108 - --panel-3: color-mix(in srgb, var(--nugu-ui-backdrop) 55%, white);
109 - --border: color-mix(in srgb, var(--nugu-ui-normal) 16%, transparent);
110 - --shadow: 0 18px 60px color-mix(in srgb, #000 14%, transparent);
111 - }
114 84 * { box-sizing: border-box; }
115 85 html, body { height: 100%; }
139 109 overflow: hidden;
141 111 #sidebar { border-inline-end: 1px solid var(--border); }
142 -#drawer { border-inline-start: 1px solid var(--border); overflow-y: auto; }
112 +#drawer { border-inline-start: 1px solid var(--border); overflow-y: auto; contain: layout paint; }
143 113 #main { display: grid; grid-template-rows: auto minmax(0, 1fr); overflow: hidden; }
145 115 #topbar {
149 119 gap: 14px;
150 120 padding: 14px 14px 10px;
151 121 border-bottom: 1px solid var(--border);
152 - background: color-mix(in srgb, var(--bg) 82%, transparent);
153 - backdrop-filter: blur(8px);
122 + background: color-mix(in srgb, var(--bg) 92%, var(--panel));
155 124 #diffs { overflow: auto; padding: 16px 14px 40px; }
157 126 .brand { display: grid; grid-template-columns: 1fr auto; gap: 10px; align-items: start; margin-bottom: 14px; }
158 -h1 { font-size: 20px; line-height: 1; margin: 0; letter-spacing: -0.03em; color: var(--nugu-content-important-global); }
159 -.subtitle, .eyebrow { margin-top: 6px; font-size: 12px; color: var(--muted); }
160 -.eyebrow { margin: 0 0 3px; text-transform: uppercase; letter-spacing: .08em; font-weight: 750; color: var(--accent-2); }
161 -#summary { color: var(--fg-soft); font-size: 13px; }
127 +h1 { font-size: 22px; line-height: 1; margin: 0; letter-spacing: -0.03em; color: var(--nugu-content-important-global); }
128 +.subtitle { margin-top: 6px; font-size: 14px; color: var(--muted); }
129 +.topbar-title { margin: 0 0 3px; font-size: 16px; font-weight: 800; color: var(--nugu-content-important-global); }
130 +#summary { color: var(--fg-soft); font-size: 14px; }
162 131 .card-title, .file-title { color: var(--nugu-content-important-global); font-weight: 800; }
163 -.card-title { font-size: 13px; margin-bottom: 8px; }
164 -#meta, #status, #selection { color: var(--muted); font-size: 12px; line-height: 1.5; }
132 +.card-title { font-size: 15px; margin-bottom: 8px; }
133 +#meta, #status, #selection { color: var(--muted); font-size: 14px; line-height: 1.5; }
165 134 #meta { margin-bottom: 8px; }
166 135 #tree { height: calc(100vh - 116px); border-radius: var(--radius); background: color-mix(in srgb, var(--bg) 65%, var(--panel)); overflow: hidden; }
167 136 .count-pill {
170 139 border: 1px solid color-mix(in srgb, var(--accent) 35%, var(--border));
171 140 background: color-mix(in srgb, var(--accent) 16%, transparent);
172 141 color: var(--nugu-content-important-global);
173 - font-size: 12px;
142 + font-size: 14px;
174 143 font-weight: 750;
175 144 white-space: nowrap;
187 156 .selection-active { color: var(--fg); font-weight: 800; }
188 157 .field-row { display: grid; grid-template-columns: 1fr 1fr; gap: 10px; }
189 158 .theme-label { margin: 0; min-width: 102px; }
190 -.theme-label select { padding: 7px 28px 7px 8px; font-size: 12px; }
159 +.theme-label select { padding: 7px 28px 7px 8px; font-size: 14px; }
192 -label { display: grid; gap: 6px; margin-block: 10px; font-size: 12px; color: var(--fg-soft); font-weight: 700; }
161 +label { display: grid; gap: 6px; margin-block: 10px; font-size: 14px; color: var(--fg-soft); font-weight: 700; }
193 162 textarea, select {
194 163 width: 100%;
195 164 border: 1px solid var(--border);
224 193 z-index: 2;
225 194 margin: 0 0 8px;
226 195 padding: 8px 0;
227 - font-size: 13px;
196 + font-size: 14px;
228 197 background: linear-gradient(var(--bg), color-mix(in srgb, var(--bg) 78%, transparent));
230 199 diffs-container { border-radius: var(--radius); overflow: hidden; box-shadow: 0 0 0 1px var(--border); }
231 -.empty-list { color: var(--muted); font-size: 12px; }
200 +.empty-list { color: var(--muted); font-size: 14px; }
232 201 .finding-item {
233 202 display: grid;
234 203 gap: 6px;
237 206 border-radius: 8px;
238 207 padding: 8px;
239 208 margin-block: 7px;
240 - font-size: 12px;
209 + font-size: 14px;
241 210 background: color-mix(in srgb, var(--panel-2) 72%, transparent);
243 212 .finding-chip {
248 217 color: var(--fg);
249 218 border: 1px solid color-mix(in srgb, var(--accent) 42%, transparent);
251 -.remove-finding { justify-self: start; padding: 4px 8px; font-size: 11px; color: var(--nugu-error); }
220 +.remove-finding { justify-self: start; padding: 4px 8px; font-size: 13px; color: var(--nugu-error); }
252 221 .error { color: var(--nugu-error); }
253 222 .ok { color: var(--nugu-info); }

pi/agent/extensions/diff-review/constants.ts

Modified
2 2 export const EXTENSION_ID = "diff-review";
3 3 export const REVIEW_COMMAND = "diff-review";
4 4 export const CANCEL_COMMAND = "diff-review-cancel";
5 5 export const STATUS_ID = "diff-review";
6 -export const DEFAULT_TIMEOUT_MS = 30 * 60 * 1000;
7 6 export const HEARTBEAT_INTERVAL_MS = 5 * 1000;
7 +export const REVIEW_POLL_INTERVAL_MS = 2 * 1000;
8 +export const HEARTBEAT_CHECK_INTERVAL_MS = 10 * 1000;
8 9 export const HEARTBEAT_LOST_MS = 30 * 1000;
9 10 export const MAX_DIFF_BYTES = 5 * 1024 * 1024;
11 +export const MAX_FILE_DIFF_BYTES = 1024 * 1024;
12 +export const REQUEST_BODY_MAX_BYTES = 1024 * 1024;
13 +export const ANCHOR_CONTEXT_LINES = 3;
10 14 export const TOKEN_COOKIE = "diff_review_token";

pi/agent/extensions/diff-review/format.ts

Modified
2 2 import type { CollectedDiff, Finding, ReviewRoundEntry } from "./types.js";
4 4 export function formatReviewMarkdown(round: ReviewRoundEntry): string {
5 5 const lines: string[] = [`# Diff Review Round ${round.round}`, ""];
6 + if (round.diffSummary.skippedFiles.length > 0) lines.push("## Skipped Files", ...round.diffSummary.skippedFiles.map((file) => `- ${file}`), "");
6 7 if (round.findings.length === 0) {
7 8 lines.push("No findings recorded.", "", "Use this review result to decide whether any follow-up is needed. Do not edit files yet.");
8 9 return lines.join("\n");

pi/agent/extensions/diff-review/git.ts

Modified
1 -import { execFile } from "node:child_process";
1 +import { execFile, spawn } from "node:child_process";
2 +import { join, relative } from "node:path";
2 3 import { promisify } from "node:util";
3 -import { MAX_DIFF_BYTES } from "./constants.js";
4 +import { MAX_DIFF_BYTES, MAX_FILE_DIFF_BYTES } from "./constants.js";
4 5 import { sourceFromArgs, type DiffReviewArgs } from "./args.js";
5 -import type { CollectedDiff, DiffFileStatus, DiffIndex, IndexedFileDiff } from "./types.js";
6 +import type { CollectedDiff, DiffFileSummary, DiffFileStatus, DiffIndex, IndexedFileDiff } from "./types.js";
7 8 const execFileAsync = promisify(execFile);
9 +const DEFAULT_GIT_BUFFER_BYTES = 10 * 1024 * 1024;
10 +const STDERR_BUFFER_BYTES = 64 * 1024;
11 +const HUNK_HEADER = /^@@ -(\d+)(?:,\d+)? \+(\d+)(?:,\d+)? @@/;
12 +const DIFF_GIT_HEADER = /^diff --git a\/(.*) b\/(.*)$/;
9 14 export async function collectDiff(cwd: string, args: DiffReviewArgs): Promise<CollectedDiff> {
10 15 const repoRoot = (await git(cwd, ["rev-parse", "--show-toplevel"])).trim();
11 - const source = sourceFromArgs(args);
12 - const diffArgs = buildDiffArgs(args);
13 - const diffText = await git(cwd, diffArgs, { maxBuffer: MAX_DIFF_BYTES + 1024 });
14 - if (Buffer.byteLength(diffText, "utf8") > MAX_DIFF_BYTES) throw new Error(`Diff exceeds ${Math.round(MAX_DIFF_BYTES / 1024 / 1024)} MiB limit`);
15 - const parsed = parseUnifiedDiff(diffText);
16 - return { repoRoot, source, diffText, ...parsed };
16 + const repoArgs = rebasePathArgs(args, repoRoot, cwd);
17 + const source = sourceFromArgs(repoArgs);
18 + const pieces = await collectRenderableDiff(repoRoot, repoArgs);
19 + const parsed = parseUnifiedDiff(pieces.diffText);
20 + const skippedFiles = [...parsed.skippedFiles, ...pieces.skippedFiles];
21 + if (!pieces.diffText.trim() && skippedFiles.length > 0) throw new Error(`No renderable diff; skipped oversized/binary files: ${skippedFiles.join(", ")}`);
22 + return { repoRoot, source, diffText: pieces.diffText, ...parsed, skippedFiles };
19 -function buildDiffArgs(args: DiffReviewArgs): string[] {
20 - const base = ["diff", "--no-ext-diff", "--find-renames", "--src-prefix=a/", "--dst-prefix=b/", "--unified=3"];
21 - if (args.staged) base.push("--cached");
22 - if (args.base) base.push(`${args.base}...HEAD`);
23 - base.push("--");
24 - if (args.files) base.push(...args.files);
25 - return base;
25 +function rebasePathArgs(args: DiffReviewArgs, repoRoot: string, cwd: string): DiffReviewArgs {
26 + if (!args.files) return args;
27 + const prefix = relative(repoRoot, cwd).replace(/\\/g, "/");
28 + return { ...args, files: args.files.map((file) => prefix ? join(prefix, file).replace(/\\/g, "/") : file) };
31 +async function collectRenderableDiff(cwd: string, args: DiffReviewArgs) {
32 + const files = await changedFiles(cwd, args);
33 + const chunks: string[] = [];
34 + const skippedFiles: string[] = [];
35 + let totalBytes = 0;
37 + for (const file of files) {
38 + try {
39 + const chunk = await gitDiff(cwd, diffArgs(args, [file]), MAX_FILE_DIFF_BYTES);
40 + const bytes = Buffer.byteLength(chunk, "utf8");
41 + if (totalBytes + bytes > MAX_DIFF_BYTES) {
42 + skippedFiles.push(`${file} (review diff limit)`);
43 + continue;
44 + }
45 + totalBytes += bytes;
46 + chunks.push(chunk);
47 + } catch (err) {
48 + if (err instanceof DiffTooLargeError) skippedFiles.push(`${file} (${Math.round(MAX_FILE_DIFF_BYTES / 1024 / 1024)} MiB per-file limit)`);
49 + else throw err;
50 + }
51 + }
53 + return { diffText: chunks.join(""), skippedFiles };
56 +async function changedFiles(cwd: string, args: DiffReviewArgs) {
57 + const output = await git(cwd, nameOnlyArgs(args), { maxBuffer: DEFAULT_GIT_BUFFER_BYTES });
58 + return output.split("\0").filter(Boolean);
61 +function diffArgs(args: DiffReviewArgs, files = args.files): string[] {
62 + const out = baseDiffArgs(args);
63 + out.push("--");
64 + if (files) out.push(...files);
65 + return out;
68 +function nameOnlyArgs(args: DiffReviewArgs): string[] {
69 + const out = [...baseDiffArgs(args), "--name-only", "-z", "--"];
70 + if (args.files) out.push(...args.files);
71 + return out;
74 +function baseDiffArgs(args: DiffReviewArgs): string[] {
75 + const out = ["diff", "--no-ext-diff", "--find-renames", "--src-prefix=a/", "--dst-prefix=b/", "--unified=3"];
76 + if (args.staged) out.push("--cached");
77 + if (args.base) out.push(`${args.base}...HEAD`);
78 + return out;
28 81 async function git(cwd: string, args: string[], options: { maxBuffer?: number } = {}): Promise<string> {
29 82 try {
30 - const { stdout } = await execFileAsync("git", args, { cwd, maxBuffer: options.maxBuffer ?? 1024 * 1024 * 10 });
31 - return typeof stdout === "string" ? stdout : String(stdout);
83 + const { stdout } = await execFileAsync("git", args, { cwd, maxBuffer: options.maxBuffer ?? DEFAULT_GIT_BUFFER_BYTES });
84 + return String(stdout);
32 85 } catch (err) {
33 - const anyErr = err as { stderr?: string | Buffer; message?: string };
34 - const stderr = anyErr.stderr ? String(anyErr.stderr).trim() : "";
35 - throw new Error(stderr || anyErr.message || "git failed");
86 + throw new Error(gitError(err));
90 +function gitDiff(cwd: string, args: string[], maxBytes: number): Promise<string> {
91 + return new Promise((resolve, reject) => {
92 + const child = spawn("git", args, { cwd, stdio: ["ignore", "pipe", "pipe"] });
93 + const stdout: Buffer[] = [];
94 + const stderr: Buffer[] = [];
95 + let stdoutBytes = 0;
96 + let stderrBytes = 0;
97 + let settled = false;
99 + const resolveOnce = (text: string) => {
100 + if (settled) return;
101 + settled = true;
102 + resolve(text);
103 + };
104 + const rejectOnce = (error: Error) => {
105 + if (settled) return;
106 + settled = true;
107 + reject(error);
108 + };
110 + child.stdout.on("data", (chunk: Buffer) => {
111 + stdoutBytes += chunk.length;
112 + if (stdoutBytes > maxBytes) {
113 + child.kill("SIGTERM");
114 + rejectOnce(new DiffTooLargeError(maxBytes));
115 + return;
117 + stdout.push(chunk);
118 + });
119 + child.stderr.on("data", (chunk: Buffer) => {
120 + if (stderrBytes >= STDERR_BUFFER_BYTES) return;
121 + const remaining = STDERR_BUFFER_BYTES - stderrBytes;
122 + stderr.push(chunk.subarray(0, remaining));
123 + stderrBytes += Math.min(chunk.length, remaining);
124 + });
125 + child.once("error", rejectOnce);
126 + child.once("close", (code) => {
127 + if (settled) return;
128 + if (code === 0) resolveOnce(Buffer.concat(stdout).toString("utf8"));
129 + else rejectOnce(new Error(Buffer.concat(stderr).toString("utf8").trim() || `git diff exited with code ${code ?? "unknown"}`));
130 + });
131 + });
134 +function gitError(err: unknown) {
135 + const e = err as { stderr?: string | Buffer; message?: string };
136 + return String(e.stderr ?? "").trim() || e.message || "git failed";
39 139 function parseUnifiedDiff(diffText: string): Omit<CollectedDiff, "repoRoot" | "source" | "diffText"> {
40 - const diffIndex: DiffIndex = new Map();
41 - const files: Array<{ path: string; prevPath?: string; status: DiffFileStatus; additions: number; deletions: number }> = [];
42 - const skippedFiles: string[] = [];
43 - let current: IndexedFileDiff | undefined;
44 - let oldLine = 0;
45 - let newLine = 0;
47 - const finish = () => {
48 - if (!current) return;
49 - if (current.status === "binary") skippedFiles.push(current.file);
50 - diffIndex.set(current.file, current);
51 - files.push({
52 - path: current.file,
53 - ...(current.prevFile && current.prevFile !== current.file && { prevPath: current.prevFile }),
54 - status: current.status,
55 - additions: current.additions.size,
56 - deletions: current.deletions.size,
57 - });
140 + const state: DiffParserState = {
141 + diffIndex: new Map(),
142 + files: [],
143 + skippedFiles: [],
144 + oldLine: 0,
145 + newLine: 0,
146 + inHunk: false,
60 - for (const rawLine of diffText.split(/\r?\n/)) {
61 - const line = rawLine;
62 - if (line.startsWith("diff --git ")) {
63 - finish();
64 - const { oldPath, newPath } = parseDiffGitLine(line);
65 - current = { file: newPath, prevFile: oldPath, status: "modified", additions: new Map(), deletions: new Map() };
66 - oldLine = 0;
67 - newLine = 0;
68 - continue;
69 - }
70 - if (!current) continue;
71 - if (line.startsWith("new file mode ")) { current.status = "added"; continue; }
72 - if (line.startsWith("deleted file mode ")) { current.status = "deleted"; continue; }
73 - if (line.startsWith("similarity index ") || line.startsWith("rename from ") || line.startsWith("rename to ")) {
74 - if (current.status !== "added" && current.status !== "deleted") current.status = "renamed";
75 - continue;
76 - }
77 - if (line.startsWith("Binary files ")) { current.status = "binary"; continue; }
78 - if (line.startsWith("--- ")) {
79 - const path = parseHeaderPath(line.slice(4));
80 - if (path && path !== "/dev/null") current.prevFile = path;
81 - continue;
82 - }
83 - if (line.startsWith("+++ ")) {
84 - const path = parseHeaderPath(line.slice(4));
85 - if (path && path !== "/dev/null") current.file = path;
86 - continue;
87 - }
88 - if (line.startsWith("@@ ")) {
89 - const match = line.match(/^@@ -(\d+)(?:,\d+)? \+(\d+)(?:,\d+)? @@/);
90 - if (match) {
91 - oldLine = Number(match[1]);
92 - newLine = Number(match[2]);
93 - }
94 - continue;
95 - }
96 - if (!oldLine && !newLine) continue;
97 - if (line.startsWith("+")) {
98 - current.additions.set(newLine, line.slice(1));
99 - newLine++;
100 - continue;
101 - }
102 - if (line.startsWith("-")) {
103 - current.deletions.set(oldLine, line.slice(1));
104 - oldLine++;
105 - continue;
106 - }
107 - if (line.startsWith(" ")) {
108 - oldLine++;
109 - newLine++;
110 - }
111 - }
112 - finish();
149 + for (const line of diffText.split(/\r?\n/)) parseDiffLine(state, line);
150 + finishFile(state);
114 152 return {
115 - files,
116 - diffIndex,
117 - skippedFiles,
118 - additions: files.reduce((sum, file) => sum + file.additions, 0),
119 - deletions: files.reduce((sum, file) => sum + file.deletions, 0),
153 + files: state.files,
154 + diffIndex: state.diffIndex,
155 + skippedFiles: state.skippedFiles,
156 + additions: sumChanges(state.files, "additions"),
157 + deletions: sumChanges(state.files, "deletions"),
161 +type DiffParserState = {
162 + current?: IndexedFileDiff;
163 + diffIndex: DiffIndex;
164 + files: DiffFileSummary[];
165 + skippedFiles: string[];
166 + oldLine: number;
167 + newLine: number;
168 + inHunk: boolean;
171 +function parseDiffLine(state: DiffParserState, line: string) {
172 + if (line.startsWith("diff --git ")) return startFile(state, line);
173 + if (!state.current) return;
174 + if (updateFileMetadata(state.current, line)) return;
175 + if (updateHeaderPath(state.current, line)) return;
176 + if (startHunk(state, line)) return;
177 + if (!state.inHunk) return;
178 + applyHunkLine(state, line);
181 +function startFile(state: DiffParserState, line: string) {
182 + finishFile(state);
183 + const { oldPath, newPath } = parseDiffGitLine(line);
184 + state.current = { file: newPath, prevFile: oldPath, status: "modified", additions: new Map(), deletions: new Map(), oldLines: new Map(), newLines: new Map() };
185 + state.oldLine = 0;
186 + state.newLine = 0;
187 + state.inHunk = false;
190 +function finishFile(state: DiffParserState) {
191 + const file = state.current;
192 + if (!file) return;
193 + if (file.status === "binary") state.skippedFiles.push(file.file);
194 + state.diffIndex.set(file.file, file);
195 + state.files.push(summary(file));
196 + state.current = undefined;
199 +function summary(file: IndexedFileDiff): DiffFileSummary {
200 + return {
201 + path: file.file,
202 + ...(file.prevFile && file.prevFile !== file.file && { prevPath: file.prevFile }),
203 + status: file.status,
204 + additions: file.additions.size,
205 + deletions: file.deletions.size,
206 + };
209 +function updateFileMetadata(file: IndexedFileDiff, line: string) {
210 + const status = statusFromMetadata(line, file.status);
211 + if (!status) return false;
212 + file.status = status;
213 + return true;
216 +function statusFromMetadata(line: string, current: DiffFileStatus): DiffFileStatus | undefined {
217 + if (line.startsWith("new file mode ")) return "added";
218 + if (line.startsWith("deleted file mode ")) return "deleted";
219 + if (line.startsWith("Binary files ")) return "binary";
220 + if (line.startsWith("similarity index ") || line.startsWith("rename from ") || line.startsWith("rename to ")) return current === "added" || current === "deleted" ? current : "renamed";
221 + return undefined;
224 +function updateHeaderPath(file: IndexedFileDiff, line: string) {
225 + if (line.startsWith("--- ")) {
226 + const path = parseHeaderPath(line.slice(4));
227 + if (path && path !== "/dev/null") file.prevFile = path;
228 + return true;
230 + if (line.startsWith("+++ ")) {
231 + const path = parseHeaderPath(line.slice(4));
232 + if (path && path !== "/dev/null") file.file = path;
233 + return true;
235 + return false;
238 +function startHunk(state: DiffParserState, line: string) {
239 + const match = HUNK_HEADER.exec(line);
240 + if (!match) return false;
241 + state.oldLine = Number(match[1]);
242 + state.newLine = Number(match[2]);
243 + state.inHunk = true;
244 + return true;
247 +function applyHunkLine(state: DiffParserState, line: string) {
248 + const file = state.current;
249 + if (!file || line.startsWith("\\")) return;
250 + if (line.startsWith("+")) return addLine(file, state, line);
251 + if (line.startsWith("-")) return deleteLine(file, state, line);
252 + if (line.startsWith(" ")) return contextLine(state, line);
255 +function addLine(file: IndexedFileDiff, state: DiffParserState, line: string) {
256 + const text = line.slice(1);
257 + file.additions.set(state.newLine, text);
258 + file.newLines.set(state.newLine, text);
259 + state.newLine++;
262 +function deleteLine(file: IndexedFileDiff, state: DiffParserState, line: string) {
263 + const text = line.slice(1);
264 + file.deletions.set(state.oldLine, text);
265 + file.oldLines.set(state.oldLine, text);
266 + state.oldLine++;
269 +function contextLine(state: DiffParserState, line: string) {
270 + if (state.current) {
271 + const text = line.slice(1);
272 + state.current.oldLines.set(state.oldLine, text);
273 + state.current.newLines.set(state.newLine, text);
275 + state.oldLine++;
276 + state.newLine++;
123 279 function parseDiffGitLine(line: string) {
124 - const match = line.match(/^diff --git a\/(.*) b\/(.*)$/);
280 + const match = DIFF_GIT_HEADER.exec(line);
125 281 return { oldPath: match?.[1] ?? "", newPath: match?.[2] ?? match?.[1] ?? "" };
131 287 if (trimmed.startsWith("a/") || trimmed.startsWith("b/")) return trimmed.slice(2);
132 288 return trimmed.split(/\s+/)[0];
291 +function sumChanges(files: DiffFileSummary[], key: "additions" | "deletions") {
292 + return files.reduce((sum, file) => sum + file[key], 0);
295 +class DiffTooLargeError extends Error {
296 + constructor(readonly maxBytes: number) {
297 + super(`diff exceeds ${Math.round(maxBytes / 1024 / 1024)} MiB limit`);

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

Modified
60 60 diff,
61 61 state,
62 62 round,
63 - onHeartbeatLost: () => ctx.ui.notify("diff-review browser heartbeat lost; reopen URL or run /diff-review-cancel", "warning"),
63 + refreshDiff: () => collectDiff(ctx.cwd, args),
64 + onSubmit: (result, latestDiff) => {
65 + const entry = makeReviewRound(round, latestDiff, result.findings, result.notes);
66 + appendReviewRound(ctx, entry);
67 + state = restoreReviewState(ctx);
68 + const markdown = formatReviewMarkdown(entry);
69 + ctx.ui.notify(`diff review sent to Pi: ${result.findings.length} finding${result.findings.length === 1 ? "" : "s"}`, "info");
70 + pi.sendUserMessage([{ type: "text", text: markdown }]);
71 + },
72 + onHeartbeatLost: () => ctx.ui.notify("diff-review browser closed", "info"),
65 74 active = server;
66 - ctx.ui.setStatus(STATUS_ID, `open ${server.url}`);
67 - ctx.ui.notify(`Open diff review: ${server.url}`, "info");
75 + server.result.then((result) => {
76 + if (active?.id === server.id) active = undefined;
77 + ctx.ui.setStatus(STATUS_ID, undefined);
78 + ctx.ui.notify(`/diff-review ended (${result.reason})`, result.reason === "timeout" ? "warning" : "info");
79 + });
80 + ctx.ui.setStatus(STATUS_ID, `live ${server.url}`);
81 + ctx.ui.notify(`Diff review live: ${server.url}`, "info");
69 83 const opened = await openBrowser(server.url);
70 84 if (!opened.ok) ctx.ui.notify(`Could not open browser automatically. Open manually: ${server.url}`, "warning");
72 - const result = await server.result;
73 - active = undefined;
74 - ctx.ui.setStatus(STATUS_ID, undefined);
76 - if (result.type === "cancel") {
77 - ctx.ui.notify(`/diff-review cancelled (${result.reason})`, result.reason === "timeout" ? "warning" : "info");
78 - return;
79 - }
81 - const entry = makeReviewRound(round, diff, result.findings, result.notes);
82 - appendReviewRound(ctx, entry);
83 - state = restoreReviewState(ctx);
84 - const markdown = formatReviewMarkdown(entry);
85 - ctx.ui.notify(`diff review submitted: ${result.findings.length} finding${result.findings.length === 1 ? "" : "s"}`, "info");
86 - pi.sendUserMessage([{ type: "text", text: markdown }]);
87 85 } catch (err) {
88 86 active?.close("command");
89 87 active = undefined;

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

Modified
7 7 import { collectDiff } from "../git.js";
8 8 import { parseArgs } from "../args.js";
9 9 import { startReviewServer } from "../server.js";
10 +import type { BrowserResult } from "../types.js";
11 12 const execFileAsync = promisify(execFile);
12 13 const EXT_DIR = dirname(dirname(fileURLToPath(import.meta.url)));
14 +const BUILD_BUFFER_BYTES = 10 * 1024 * 1024;
15 +const REVIEW_TIMEOUT_MS = 30_000;
16 +const DEBUG_PORT_BASE = 9400;
17 +const DEBUG_PORT_SPAN = 1000;
18 +const TAB_RETRIES = 80;
19 +const TAB_POLL_MS = 250;
20 +const BROWSER_BOOT_MS = 5_000;
21 +const CHROME_COMMANDS = ["google-chrome-stable", "google-chrome", "chromium", "chromium-browser"];
14 -await execFileAsync("bun", ["run", "build"], { cwd: EXT_DIR, maxBuffer: 1024 * 1024 * 10 });
15 -await assertStaticBundle();
16 -await smokeRealBrowser();
23 +async function main() {
24 + await execFileAsync("bun", ["run", "build"], { cwd: EXT_DIR, maxBuffer: BUILD_BUFFER_BYTES });
25 + await assertStaticBundle();
26 + await smokeRealBrowser();
18 29 async function assertStaticBundle() {
19 - const index = await readFile(join(EXT_DIR, "static", "index.html"), "utf8").catch(() => "");
20 - const app = await readFile(join(EXT_DIR, "static", "app.js"), "utf8").catch(() => "");
21 - const manifest = await readFile(join(EXT_DIR, "static", "manifest.json"), "utf8").catch(() => "");
30 + const [index, app, manifest] = await Promise.all([
31 + readText(join(EXT_DIR, "static", "index.html")),
32 + readText(join(EXT_DIR, "static", "app.js")),
33 + readText(join(EXT_DIR, "static", "manifest.json")),
34 + ]);
22 35 if (!index || !app || !manifest) throw new Error("static browser bundle missing; run bun run build");
23 36 if (!index.includes("/static/app.js")) throw new Error("static/index.html does not load /static/app.js");
24 37 JSON.parse(manifest);
27 40 async function smokeRealBrowser() {
28 41 const chrome = process.env.CHROME ?? await findChrome();
29 - if (!chrome) {
30 - console.log("smoke: static bundle ok; no Chrome/Chromium found, skipping real browser smoke");
31 - return;
32 - }
42 + if (!chrome) return console.log("smoke: static bundle ok; no Chrome/Chromium found, skipping real browser smoke");
34 - const repo = await mkdtemp(join(tmpdir(), "diff-review-smoke-repo-"));
35 - const profile = await mkdtemp(join(tmpdir(), "diff-review-smoke-chrome-"));
36 - const debugPort = 9400 + Math.floor(Math.random() * 1000);
37 - let server: Awaited<ReturnType<typeof startReviewServer>> | undefined;
38 - let chromeProcess: ChildProcess | undefined;
44 + const ctx = await createSmokeContext(chrome);
39 45 try {
40 - await git(repo, ["init", "-q"]);
41 - await git(repo, ["config", "user.email", "smoke@example.invalid"]);
42 - await git(repo, ["config", "user.name", "smoke"]);
43 - await writeFile(join(repo, "a.ts"), "const a = 1;\n");
44 - await git(repo, ["add", "a.ts"]);
45 - await git(repo, ["commit", "-qm", "init"]);
46 - await writeFile(join(repo, "a.ts"), "const a = 2;\nconst b = 3;\n");
48 - const diff = await collectDiff(repo, parseArgs(""));
49 - server = await startReviewServer({ diff, state: { round: 0, findings: [], rounds: [] }, round: 1, timeoutMs: 30_000 });
50 - chromeProcess = spawn(chrome, [
51 - "--headless=new",
52 - "--disable-gpu",
53 - "--no-sandbox",
54 - "--disable-dev-shm-usage",
55 - `--remote-debugging-port=${debugPort}`,
56 - `--user-data-dir=${profile}`,
57 - "--window-size=1400,900",
58 - server.url,
59 - ], { stdio: "ignore" });
61 - const tab = await waitForTab(debugPort);
62 - const client = await connectCdp(tab.webSocketDebuggerUrl);
63 - try {
64 - await client.call("Runtime.enable");
65 - await sleep(5000);
66 - const browser = await client.eval(`(async () => {
67 - await document.fonts.ready;
68 - const dc = document.querySelector('diffs-container');
69 - const sr = dc?.shadowRoot;
70 - const addLine1 = sr?.querySelector('[data-additions] [data-line="1"]');
71 - const addLine2 = sr?.querySelector('[data-additions] [data-line="2"]');
72 - if (!addLine1 || !addLine2) throw new Error('addition lines not rendered');
73 - document.querySelector('#theme-mode').value = 'light';
74 - document.querySelector('#theme-mode').dispatchEvent(new Event('change', { bubbles: true }));
76 - addLine1.dispatchEvent(new MouseEvent('click', { bubbles: true, composed: true, clientX: 900, clientY: 350 }));
77 - await new Promise((r) => setTimeout(r, 200));
78 - let comment = document.querySelector('#comment');
79 - comment.value = 'remove me';
80 - comment.dispatchEvent(new Event('input', { bubbles: true }));
81 - document.querySelector('#add').click();
82 - await new Promise((r) => setTimeout(r, 350));
84 - addLine2.dispatchEvent(new MouseEvent('click', { bubbles: true, composed: true, clientX: 900, clientY: 370 }));
85 - await new Promise((r) => setTimeout(r, 200));
86 - comment = document.querySelector('#comment');
87 - comment.value = 'smoke finding';
88 - comment.dispatchEvent(new Event('input', { bubbles: true }));
89 - document.querySelector('#add').click();
90 - await new Promise((r) => setTimeout(r, 500));
92 - document.querySelector('.remove-finding').click();
93 - await new Promise((r) => setTimeout(r, 200));
94 - const added = document.querySelector('#findings').innerText;
95 - const failedResources = performance.getEntriesByType('resource')
96 - .filter((entry) => 'responseStatus' in entry && entry.responseStatus >= 400)
97 - .map((entry) => [entry.name, entry.responseStatus]);
98 - const fontLoaded = document.fonts.check('12px "Nugu Code Nerd"');
99 - document.querySelector('#submit').click();
100 - return { added, failedResources, fontLoaded, theme: document.documentElement.dataset.theme, body: document.body.innerText };
101 - })()`);
102 - if (!browser.added.includes("smoke finding") || browser.added.includes("remove me")) throw new Error("finding add/remove flow failed in browser UI");
103 - if (!browser.fontLoaded) throw new Error("Nugu Code Nerd font did not load");
104 - if (browser.theme !== "light") throw new Error("theme selector did not apply light mode");
105 - if (browser.failedResources.length > 0) throw new Error(`resource failures: ${JSON.stringify(browser.failedResources)}`);
106 - const result = await server.result;
107 - if (result.type !== "submit" || result.findings.length !== 1 || result.findings[0]?.comment !== "smoke finding") throw new Error("server did not receive expected submitted finding");
108 - console.log("smoke: real browser loaded UI, switched theme, loaded font, added/removed finding, submitted review");
109 - } finally {
110 - client.close();
111 - }
46 + await prepareRepo(ctx.repo);
47 + const running = await startSmokeServer(ctx.repo);
48 + ctx.server = running.server;
49 + ctx.submitted = running.submitted;
50 + ctx.chrome = launchChrome(chrome, ctx.profile, ctx.debugPort, ctx.server.url);
51 + await exerciseBrowser(ctx.debugPort, ctx.server, ctx.submitted);
52 + console.log("smoke: real browser loaded UI, switched theme, loaded font, added/removed finding, submitted review");
112 53 } finally {
113 - chromeProcess?.kill();
114 - server?.close("timeout");
115 - await rm(repo, { recursive: true, force: true });
116 - await rm(profile, { recursive: true, force: true });
54 + await cleanup(ctx);
58 +type SmokeContext = {
59 + repo: string;
60 + profile: string;
61 + debugPort: number;
62 + server?: Awaited<ReturnType<typeof startReviewServer>>;
63 + submitted?: Promise<Extract<BrowserResult, { type: "submit" }>>;
64 + chrome?: ChildProcess;
65 +};
67 +async function createSmokeContext(_chrome: string): Promise<SmokeContext> {
68 + return {
69 + repo: await mkdtemp(join(tmpdir(), "diff-review-smoke-repo-")),
70 + profile: await mkdtemp(join(tmpdir(), "diff-review-smoke-chrome-")),
71 + debugPort: DEBUG_PORT_BASE + Math.floor(Math.random() * DEBUG_PORT_SPAN),
72 + };
75 +async function prepareRepo(repo: string) {
76 + await git(repo, ["init", "-q"]);
77 + await git(repo, ["config", "user.email", "smoke@example.invalid"]);
78 + await git(repo, ["config", "user.name", "smoke"]);
79 + await writeFile(join(repo, "a.ts"), "const a = 1;\n");
80 + await git(repo, ["add", "a.ts"]);
81 + await git(repo, ["commit", "-qm", "init"]);
82 + await writeFile(join(repo, "a.ts"), "const a = 2;\nconst b = 3;\n");
85 +async function startSmokeServer(repo: string) {
86 + const diff = await collectDiff(repo, parseArgs(""));
87 + let resolveSubmit!: (result: Extract<BrowserResult, { type: "submit" }>) => void;
88 + const submitted = new Promise<Extract<BrowserResult, { type: "submit" }>>((resolve) => { resolveSubmit = resolve; });
89 + const server = await startReviewServer({ diff, state: { round: 0, findings: [], rounds: [] }, round: 1, timeoutMs: REVIEW_TIMEOUT_MS, onSubmit: resolveSubmit });
90 + return { server, submitted };
93 +function launchChrome(chrome: string, profile: string, debugPort: number, url: string) {
94 + return spawn(chrome, [
95 + "--headless=new",
96 + "--disable-gpu",
97 + "--no-sandbox",
98 + "--disable-dev-shm-usage",
99 + `--remote-debugging-port=${debugPort}`,
100 + `--user-data-dir=${profile}`,
101 + "--window-size=1400,900",
102 + url,
103 + ], { stdio: "ignore" });
106 +async function exerciseBrowser(debugPort: number, server: Awaited<ReturnType<typeof startReviewServer>>, submitted: Promise<Extract<BrowserResult, { type: "submit" }>>) {
107 + const tab = await waitForTab(debugPort);
108 + const client = await connectCdp(tab.webSocketDebuggerUrl);
109 + try {
110 + await client.call("Runtime.enable");
111 + await sleep(BROWSER_BOOT_MS);
112 + assertBrowserSmokeResult(await client.eval(BROWSER_SCRIPT));
113 + const result = await submitted;
114 + if (result.findings.length !== 1 || result.findings[0]?.comment !== "smoke finding") throw new Error("server did not receive expected submitted finding");
115 + server.close("browser");
116 + } finally {
117 + client.close();
121 +const BROWSER_SCRIPT = String.raw`(async () => {
122 + const wait = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
123 + const must = (selector, root = document) => {
124 + const el = root.querySelector(selector);
125 + if (!el) throw new Error('missing ' + selector);
126 + return el;
127 + };
128 + const clickLine = async (line, y) => {
129 + line.dispatchEvent(new MouseEvent('click', { bubbles: true, composed: true, clientX: 900, clientY: y }));
130 + await wait(200);
131 + };
132 + const addFinding = async (line, commentText, y) => {
133 + await clickLine(line, y);
134 + const comment = must('#comment');
135 + comment.value = commentText;
136 + comment.dispatchEvent(new Event('input', { bubbles: true }));
137 + must('#add').click();
138 + await wait(400);
139 + };
141 + await document.fonts.ready;
142 + const shadowRoot = must('diffs-container').shadowRoot;
143 + const addLine1 = must('[data-additions] [data-line="1"]', shadowRoot);
144 + const addLine2 = must('[data-additions] [data-line="2"]', shadowRoot);
145 + const themeMode = must('#theme-mode');
146 + themeMode.value = 'light';
147 + themeMode.dispatchEvent(new Event('change', { bubbles: true }));
149 + await addFinding(addLine1, 'remove me', 350);
150 + await addFinding(addLine2, 'smoke finding', 370);
151 + must('.remove-finding').click();
152 + await wait(200);
154 + const failedResources = performance.getEntriesByType('resource')
155 + .filter((entry) => 'responseStatus' in entry && entry.responseStatus >= 400)
156 + .map((entry) => [entry.name, entry.responseStatus]);
157 + const result = {
158 + findingsText: must('#findings').innerText,
159 + failedResources,
160 + fontLoaded: document.fonts.check('12px "Nugu Code Nerd"'),
161 + theme: document.documentElement.dataset.theme,
162 + };
163 + must('#submit').click();
164 + return result;
165 +})()`;
167 +type BrowserSmokeResult = {
168 + findingsText: string;
169 + failedResources: Array<[string, number]>;
170 + fontLoaded: boolean;
171 + theme: string;
174 +function assertBrowserSmokeResult(value: unknown): asserts value is BrowserSmokeResult {
175 + if (!isRecord(value)) throw new Error("browser smoke returned invalid result");
176 + if (typeof value.findingsText !== "string") throw new Error("browser smoke missing findings text");
177 + if (!value.findingsText.includes("smoke finding") || value.findingsText.includes("remove me")) throw new Error("finding add/remove flow failed in browser UI");
178 + if (value.fontLoaded !== true) throw new Error("Nugu Code Nerd font did not load");
179 + if (value.theme !== "light") throw new Error("theme selector did not apply light mode");
180 + if (Array.isArray(value.failedResources) && value.failedResources.length > 0) throw new Error(`resource failures: ${JSON.stringify(value.failedResources)}`);
183 +async function cleanup(ctx: SmokeContext) {
184 + ctx.chrome?.kill();
185 + ctx.server?.close("timeout");
186 + await Promise.all([
187 + rm(ctx.repo, { recursive: true, force: true }),
188 + rm(ctx.profile, { recursive: true, force: true }),
189 + ]);
120 192 async function waitForTab(port: number): Promise<{ webSocketDebuggerUrl: string }> {
121 - for (let i = 0; i < 80; i++) {
122 - try {
123 - const tabs = await fetch(`http://127.0.0.1:${port}/json/list`).then((res) => res.json()) as Array<{ type: string; url: string; webSocketDebuggerUrl: string }>;
124 - const tab = tabs.find((candidate) => candidate.type === "page" && candidate.url.startsWith("http://127.0.0.1"));
125 - if (tab) return tab;
126 - } catch {}
127 - await sleep(250);
193 + for (let i = 0; i < TAB_RETRIES; i++) {
194 + const tab = await localChromeTabs(port).catch(() => undefined);
195 + if (tab) return tab;
196 + await sleep(TAB_POLL_MS);
129 198 throw new Error("Chrome CDP tab not found");
132 -async function connectCdp(url: string) {
201 +async function localChromeTabs(port: number) {
202 + const tabs = await fetch(`http://127.0.0.1:${port}/json/list`).then((res) => res.json()) as Array<{ type: string; url: string; webSocketDebuggerUrl: string }>;
203 + return tabs.find((candidate) => candidate.type === "page" && candidate.url.startsWith("http://127.0.0.1"));
206 +type CdpClient = {
207 + call(method: string, params?: Record<string, unknown>): Promise<CdpResponse>;
208 + eval(expression: string): Promise<unknown>;
209 + close(): void;
211 +type CdpResponse = { id?: number; result?: { result?: { value?: unknown }; exceptionDetails?: { text?: string } }; error?: { message?: string } };
213 +async function connectCdp(url: string): Promise<CdpClient> {
133 214 let id = 0;
134 215 const ws = new WebSocket(url);
135 - const pending = new Map<number, (value: any) => void>();
136 - ws.onmessage = (event) => {
137 - const message = JSON.parse(String(event.data));
138 - if (message.id && pending.has(message.id)) {
139 - pending.get(message.id)!(message);
140 - pending.delete(message.id);
141 - }
142 - };
216 + const pending = new Map<number, (value: CdpResponse) => void>();
217 + ws.onmessage = (event) => receiveCdpMessage(pending, event.data);
143 218 await new Promise<void>((resolve, reject) => { ws.onopen = () => resolve(); ws.onerror = reject; });
144 219 return {
145 220 call(method: string, params: Record<string, unknown> = {}) {
146 - return new Promise<any>((resolve) => {
221 + return new Promise<CdpResponse>((resolve) => {
147 222 const callId = ++id;
148 223 pending.set(callId, resolve);
149 224 ws.send(JSON.stringify({ id: callId, method, params }));
152 227 async eval(expression: string) {
153 - const result = await this.call("Runtime.evaluate", { expression, returnByValue: true, awaitPromise: true });
154 - if (result.result.exceptionDetails) throw new Error(result.result.exceptionDetails.text ?? "browser eval failed");
155 - return result.result.result.value;
228 + const response = await this.call("Runtime.evaluate", { expression, returnByValue: true, awaitPromise: true });
229 + if (response.error) throw new Error(response.error.message ?? "browser eval protocol error");
230 + if (response.result?.exceptionDetails) throw new Error(response.result.exceptionDetails.text ?? "browser eval failed");
231 + return response.result?.result?.value;
157 233 close() { ws.close(); },
237 +function receiveCdpMessage(pending: Map<number, (value: CdpResponse) => void>, data: unknown) {
238 + const message = JSON.parse(String(data)) as CdpResponse;
239 + if (!message.id) return;
240 + pending.get(message.id)?.(message);
241 + pending.delete(message.id);
161 244 async function findChrome() {
162 - for (const command of ["google-chrome-stable", "google-chrome", "chromium", "chromium-browser"]) {
245 + for (const command of CHROME_COMMANDS) {
164 247 await execFileAsync(command, ["--version"]);
165 248 return command;
172 255 await execFileAsync("git", args, { cwd });
258 +async function readText(path: string) {
259 + return readFile(path, "utf8").catch(() => "");
175 262 function sleep(ms: number) {
176 263 return new Promise((resolve) => setTimeout(resolve, ms));
266 +function isRecord(value: unknown): value is Record<string, unknown> {
267 + return !!value && typeof value === "object" && !Array.isArray(value);
270 +await main();

pi/agent/extensions/diff-review/server.ts

Modified
2 2 import { randomBytes, randomUUID } from "node:crypto";
3 3 import { createReadStream } from "node:fs";
4 4 import { stat } from "node:fs/promises";
5 5 import { createServer, type IncomingMessage, type Server, type ServerResponse } from "node:http";
6 -import { extname, join, normalize } from "node:path";
7 -import { DEFAULT_TIMEOUT_MS, HEARTBEAT_LOST_MS, TOKEN_COOKIE } from "./constants.js";
6 +import { extname, resolve, sep } from "node:path";
7 +import { ANCHOR_CONTEXT_LINES, HEARTBEAT_CHECK_INTERVAL_MS, HEARTBEAT_LOST_MS, REQUEST_BODY_MAX_BYTES, TOKEN_COOKIE } from "./constants.js";
8 8 import { staticDir } from "./bundle.js";
9 -import type { BrowserResult, CollectedDiff, Finding, FindingDraft, ReviewPayload, ReviewSide, ReviewState } from "./types.js";
9 +import type { BrowserResult, CollectedDiff, Finding, FindingDraft, ReviewCategory, ReviewPayload, ReviewSeverity, ReviewSide, ReviewState } from "./types.js";
11 11 export type ReviewServer = {
12 12 id: string;
13 13 url: string;
14 - result: Promise<BrowserResult>;
15 - close(reason: Extract<BrowserResult, { type: "cancel" }>["reason"]): void;
14 + result: Promise<Extract<BrowserResult, { type: "cancel" }>>;
15 + close(reason: CancelReason): void;
18 +type CancelReason = Extract<BrowserResult, { type: "cancel" }>["reason"];
18 19 type StartServerOptions = {
19 20 diff: CollectedDiff;
20 21 state: ReviewState;
21 22 round: number;
22 23 timeoutMs?: number;
24 + refreshDiff?: () => Promise<CollectedDiff>;
25 + onSubmit?: (result: Extract<BrowserResult, { type: "submit" }>, diff: CollectedDiff) => Promise<void> | void;
23 26 onHeartbeatLost?: () => void;
28 +type RouteContext = StartServerOptions & { token: string; diff: CollectedDiff; finish(event: ServerEvent): void };
29 +type ServerEvent = Extract<BrowserResult, { type: "cancel" }> | "heartbeat";
31 +type Route = {
32 + method: string;
33 + path: string;
34 + handle(req: IncomingMessage, res: ServerResponse, ctx: RouteContext): Promise<void> | void;
35 +};
37 +const REVIEW_CATEGORIES = new Set<ReviewCategory>(["bug", "style", "perf", "question"]);
38 +const REVIEW_SEVERITIES = new Set<ReviewSeverity>(["high", "medium", "low"]);
39 +const REVIEW_SIDES = new Set<ReviewSide>(["additions", "deletions"]);
40 +const ROUTES: readonly Route[] = [
41 + { method: "GET", path: "/api/review", handle: getReview },
42 + { method: "POST", path: "/api/heartbeat", handle: heartbeat },
43 + { method: "POST", path: "/api/cancel", handle: cancel },
44 + { method: "POST", path: "/api/finding/validate", handle: validateFinding },
45 + { method: "POST", path: "/api/submit", handle: submitReview },
46 +];
26 48 export async function startReviewServer(options: StartServerOptions): Promise<ReviewServer> {
27 49 const token = randomBytes(32).toString("base64url");
29 51 let finished = false;
30 52 let lastHeartbeatAt = Date.now();
31 53 let heartbeatWarned = false;
32 - let resolveResult!: (result: BrowserResult) => void;
33 - const result = new Promise<BrowserResult>((resolve) => { resolveResult = resolve; });
54 + let resolveResult!: (result: Extract<BrowserResult, { type: "cancel" }>) => void;
55 + const result = new Promise<Extract<BrowserResult, { type: "cancel" }>>((resolve) => { resolveResult = resolve; });
35 - const finish = (next: BrowserResult) => {
57 + const finish = (event: ServerEvent) => {
58 + if (event === "heartbeat") {
59 + lastHeartbeatAt = Date.now();
60 + heartbeatWarned = false;
61 + return;
62 + }
36 63 if (finished) return;
37 64 finished = true;
38 65 clearInterval(heartbeatTimer);
39 - clearTimeout(timeoutTimer);
66 + if (timeoutTimer) clearTimeout(timeoutTimer);
40 67 server.close();
41 - resolveResult(next);
68 + resolveResult(event);
70 + const ctx: RouteContext = { ...options, token, finish };
44 72 const heartbeatTimer = setInterval(() => {
45 - if (!heartbeatWarned && Date.now() - lastHeartbeatAt > HEARTBEAT_LOST_MS) {
46 - heartbeatWarned = true;
47 - options.onHeartbeatLost?.();
48 - }
49 - }, 10_000);
73 + if (heartbeatWarned || Date.now() - lastHeartbeatAt <= HEARTBEAT_LOST_MS) return;
74 + heartbeatWarned = true;
75 + options.onHeartbeatLost?.();
76 + finish({ type: "cancel", reason: "browser" });
77 + }, HEARTBEAT_CHECK_INTERVAL_MS);
50 78 heartbeatTimer.unref();
52 - const timeoutTimer = setTimeout(() => finish({ type: "cancel", reason: "timeout" }), options.timeoutMs ?? DEFAULT_TIMEOUT_MS);
53 - timeoutTimer.unref();
80 + const timeoutTimer = options.timeoutMs === undefined ? undefined : setTimeout(() => finish({ type: "cancel", reason: "timeout" }), options.timeoutMs);
81 + timeoutTimer?.unref();
55 - server = createServer(async (req, res) => {
56 - try {
57 - await handleRequest(req, res, token, options, (result) => {
58 - if (result.type === "heartbeat") {
59 - lastHeartbeatAt = Date.now();
60 - heartbeatWarned = false;
61 - return;
62 - }
63 - finish(result.result);
64 - });
65 - } catch (err) {
66 - json(res, 500, { error: (err as Error).message });
67 - }
68 - });
83 + server = createServer((req, res) => void dispatch(req, res, ctx));
84 + try {
85 + await listen(server);
86 + } catch (err) {
87 + clearInterval(heartbeatTimer);
88 + if (timeoutTimer) clearTimeout(timeoutTimer);
89 + server.close();
90 + throw err;
91 + }
70 - await new Promise<void>((resolve, reject) => {
71 - server.once("error", reject);
72 - server.listen(0, "127.0.0.1", () => resolve());
73 - });
74 93 const address = server.address();
75 94 if (!address || typeof address === "string") throw new Error("Failed to bind review server");
76 - const url = `http://127.0.0.1:${address.port}/?token=${encodeURIComponent(token)}`;
77 - return { id, url, result, close: (reason) => finish({ type: "cancel", reason }) };
95 + return { id, url: `http://127.0.0.1:${address.port}/?token=${encodeURIComponent(token)}`, result, close: (reason) => finish({ type: "cancel", reason }) };
80 -async function handleRequest(
81 - req: IncomingMessage,
82 - res: ServerResponse,
83 - token: string,
84 - options: StartServerOptions,
85 - finish: (result: { type: "heartbeat" } | { type: "submit"; result: BrowserResult } | { type: "cancel"; result: BrowserResult }) => void,
86 -) {
87 - const url = new URL(req.url ?? "/", "http://127.0.0.1");
88 - if (req.method === "GET" && url.pathname === "/") return serveIndex(req, res, token, url);
89 - if (req.method === "GET" && url.pathname.startsWith("/static/")) return serveStatic(req, res, token, url.pathname.slice("/static/".length));
98 +async function dispatch(req: IncomingMessage, res: ServerResponse, ctx: RouteContext) {
99 + try {
100 + const url = new URL(req.url ?? "/", "http://127.0.0.1");
101 + if (req.method === "GET" && url.pathname === "/") return serveIndex(res, ctx.token, url);
102 + if (req.method === "GET" && url.pathname.startsWith("/static/")) return serveStatic(req, res, ctx.token, url.pathname.slice("/static/".length));
103 + if (!authorized(req, ctx.token)) return json(res, 401, { error: "unauthorized" });
91 - if (!authorized(req, token)) return json(res, 401, { error: "unauthorized" });
92 - if (req.method === "GET" && url.pathname === "/api/review") {
93 - const payload: ReviewPayload = {
94 - round: options.round,
95 - source: options.diff.source,
96 - diffText: options.diff.diffText,
97 - files: options.diff.files,
98 - carriedFindings: options.state.findings.filter((finding) => finding.status === "open"),
99 - };
100 - return json(res, 200, payload);
105 + const route = ROUTES.find((candidate) => candidate.method === req.method && candidate.path === url.pathname);
106 + if (!route) return json(res, 404, { error: "not found" });
107 + await route.handle(req, res, ctx);
108 + } catch (err) {
109 + const status = err instanceof HttpError ? err.status : 500;
110 + json(res, status, { error: errorMessage(err) });
102 - if (req.method === "POST" && url.pathname === "/api/heartbeat") {
103 - finish({ type: "heartbeat" });
104 - return json(res, 200, { ok: true });
105 - }
106 - if (req.method === "POST" && url.pathname === "/api/cancel") {
107 - json(res, 200, { ok: true });
108 - finish({ type: "cancel", result: { type: "cancel", reason: "browser" } });
109 - return;
110 - }
111 - if (req.method === "POST" && url.pathname === "/api/finding/validate") {
112 - const draft = await readJson<FindingDraft>(req);
113 - const anchor = anchorForDraft(options.diff, draft);
114 - return json(res, 200, { ok: true, anchor });
115 - }
116 - if (req.method === "POST" && url.pathname === "/api/submit") {
117 - const body = await readJson<{ notes?: string; findings?: FindingDraft[] }>(req);
118 - const findings = (body.findings ?? []).map((draft) => findingFromDraft(options.round, options.diff, draft));
119 - json(res, 200, { ok: true });
120 - finish({ type: "submit", result: { type: "submit", notes: body.notes, findings } });
121 - return;
122 - }
123 - json(res, 404, { error: "not found" });
126 -function serveIndex(_req: IncomingMessage, res: ServerResponse, token: string, url: URL) {
114 +async function getReview(_req: IncomingMessage, res: ServerResponse, ctx: RouteContext) {
115 + if (ctx.refreshDiff) ctx.diff = await ctx.refreshDiff();
116 + json(res, 200, reviewPayload(ctx));
119 +function reviewPayload(ctx: RouteContext): ReviewPayload {
120 + return {
121 + round: ctx.round,
122 + source: ctx.diff.source,
123 + diffText: ctx.diff.diffText,
124 + files: ctx.diff.files,
125 + skippedFiles: ctx.diff.skippedFiles,
126 + carriedFindings: ctx.state.findings.filter((finding) => finding.status === "open"),
127 + };
130 +function heartbeat(_req: IncomingMessage, res: ServerResponse, ctx: RouteContext) {
131 + ctx.finish("heartbeat");
132 + json(res, 200, { ok: true });
135 +function cancel(_req: IncomingMessage, res: ServerResponse, ctx: RouteContext) {
136 + json(res, 200, { ok: true });
137 + ctx.finish({ type: "cancel", reason: "browser" });
140 +async function validateFinding(req: IncomingMessage, res: ServerResponse, ctx: RouteContext) {
141 + const draft = await readJson<FindingDraft>(req, parseFindingDraft);
142 + json(res, 200, { ok: true, anchor: anchorForDraft(ctx.diff, draft) });
145 +async function submitReview(req: IncomingMessage, res: ServerResponse, ctx: RouteContext) {
146 + if (ctx.refreshDiff) ctx.diff = await ctx.refreshDiff();
147 + const body = await readJson<{ notes?: string; findings: FindingDraft[] }>(req, parseSubmitBody);
148 + const result: Extract<BrowserResult, { type: "submit" }> = { type: "submit", notes: body.notes, findings: body.findings.map((draft) => findingFromDraft(ctx.round, ctx.diff, draft)) };
149 + await ctx.onSubmit?.(result, ctx.diff);
150 + json(res, 200, { ok: true });
153 +function serveIndex(res: ServerResponse, token: string, url: URL) {
127 154 if (url.searchParams.get("token") !== token) return json(res, 401, { error: "unauthorized" });
128 155 res.setHeader("Set-Cookie", `${TOKEN_COOKIE}=${token}; SameSite=Strict; Path=/`);
129 - serveFile(res, join(staticDir(), "index.html"));
156 + serveFile(res, resolve(staticDir(), "index.html"));
132 159 function serveStatic(req: IncomingMessage, res: ServerResponse, token: string, path: string) {
133 160 if (!cookieAuthorized(req, token)) return json(res, 401, { error: "unauthorized" });
134 - const clean = normalize(path).replace(/^(\.\.(\/|\\|$))+/, "");
135 - serveFile(res, join(staticDir(), clean));
161 + const file = staticFilePath(path);
162 + if (!file) return json(res, 404, { error: "not found" });
163 + serveFile(res, file);
166 +function staticFilePath(rawPath: string) {
167 + try {
168 + const root = resolve(staticDir());
169 + const file = resolve(root, decodeURIComponent(rawPath));
170 + return file === root || file.startsWith(root + sep) ? file : undefined;
171 + } catch {
172 + return undefined;
138 176 async function serveFile(res: ServerResponse, path: string) {
151 189 function authorized(req: IncomingMessage, token: string) {
152 - return req.headers.authorization === `Bearer ${token}`;
190 + return req.headers.authorization === `Bearer ${token}` || cookieAuthorized(req, token);
155 193 function cookieAuthorized(req: IncomingMessage, token: string) {
159 197 function json(res: ServerResponse, status: number, data: unknown) {
198 + if (res.writableEnded) return;
160 199 res.statusCode = status;
161 200 res.setHeader("Content-Type", "application/json; charset=utf-8");
162 201 res.end(JSON.stringify(data));
169 208 case ".css": return "text/css; charset=utf-8";
170 209 case ".json": return "application/json; charset=utf-8";
171 210 case ".svg": return "image/svg+xml";
211 + case ".woff2": return "font/woff2";
172 212 default: return "application/octet-stream";
176 -function readJson<T>(req: IncomingMessage): Promise<T> {
177 - return new Promise((resolve, reject) => {
178 - let body = "";
179 - req.setEncoding("utf8");
180 - req.on("data", (chunk) => {
181 - body += chunk;
182 - if (body.length > 1024 * 1024) reject(new Error("request body too large"));
183 - });
184 - req.on("end", () => {
185 - try { resolve(body ? JSON.parse(body) as T : {} as T); }
186 - catch { reject(new Error("invalid JSON")); }
187 - });
188 - req.on("error", reject);
189 - });
216 +async function readJson<T>(req: IncomingMessage, parse: (value: unknown) => T): Promise<T> {
217 + const body = await readBody(req);
218 + try {
219 + return parse(body ? JSON.parse(body) : {});
220 + } catch (err) {
221 + if (err instanceof HttpError) throw err;
222 + throw new HttpError(400, err instanceof SyntaxError ? "invalid JSON" : errorMessage(err));
226 +async function readBody(req: IncomingMessage) {
227 + let body = "";
228 + for await (const chunk of req) {
229 + body += String(chunk);
230 + if (Buffer.byteLength(body, "utf8") > REQUEST_BODY_MAX_BYTES) throw new HttpError(413, "request body too large");
232 + return body;
235 +function parseSubmitBody(value: unknown): { notes?: string; findings: FindingDraft[] } {
236 + if (!isRecord(value)) throw new Error("request body must be an object");
237 + const notes = optionalString(value.notes, "notes")?.trim();
238 + const rawFindings = value.findings ?? [];
239 + if (!Array.isArray(rawFindings)) throw new Error("findings must be an array");
240 + return { ...(notes && { notes }), findings: rawFindings.map(parseFindingDraft) };
243 +function parseFindingDraft(value: unknown): FindingDraft {
244 + if (!isRecord(value)) throw new Error("finding must be an object");
245 + const startLine = positiveInteger(value.startLine, "startLine");
246 + const endLine = positiveInteger(value.endLine, "endLine");
247 + if (endLine < startLine) throw new Error("endLine must be >= startLine");
248 + const comment = requiredString(value.comment, "comment").trim();
249 + if (!comment) throw new Error("comment required");
250 + const notes = optionalString(value.notes, "notes")?.trim();
251 + const prevFile = optionalString(value.prevFile, "prevFile");
252 + return {
253 + file: requiredString(value.file, "file"),
254 + ...(prevFile && { prevFile }),
255 + side: enumValue(value.side, REVIEW_SIDES, "side"),
256 + startLine,
257 + endLine,
258 + category: enumValue(value.category, REVIEW_CATEGORIES, "category"),
259 + severity: enumValue(value.severity, REVIEW_SEVERITIES, "severity"),
260 + comment,
261 + ...(notes && { notes }),
262 + };
192 265 function findingFromDraft(round: number, diff: CollectedDiff, draft: FindingDraft): Finding {
200 273 endLine: draft.endLine,
201 274 category: draft.category,
202 275 severity: draft.severity,
203 - comment: draft.comment.trim(),
204 - ...(draft.notes?.trim() && { notes: draft.notes.trim() }),
276 + comment: draft.comment,
277 + ...(draft.notes && { notes: draft.notes }),
205 278 status: "open",
206 279 anchor: anchorForDraft(diff, draft),
210 283 function anchorForDraft(diff: CollectedDiff, draft: FindingDraft) {
211 284 const file = diff.diffIndex.get(draft.file);
212 - if (!file) throw new Error(`Unknown file: ${draft.file}`);
213 - const lines = draft.side === "additions" ? file.additions : file.deletions;
285 + if (!file) throw new HttpError(400, `Unknown file: ${draft.file}`);
286 + const lines = draft.side === "additions" ? file.newLines : file.oldLines;
287 + return {
288 + before: nearby(lines, draft.startLine - ANCHOR_CONTEXT_LINES, draft.startLine - 1),
289 + selected: selectedLines(lines, draft),
290 + after: nearby(lines, draft.endLine + 1, draft.endLine + ANCHOR_CONTEXT_LINES),
291 + };
294 +function selectedLines(lines: Map<number, string>, draft: FindingDraft) {
214 295 const selected: string[] = [];
215 296 for (let line = draft.startLine; line <= draft.endLine; line++) {
216 297 const text = lines.get(line);
217 - if (text === undefined) throw new Error(`Selected ${draft.side} line not found: ${draft.file}:${line}`);
298 + if (text === undefined) throw new HttpError(400, `Selected line is not in rendered diff context: ${draft.file}:${line}`);
218 299 selected.push(text);
220 - return {
221 - before: nearby(lines, draft.startLine - 3, draft.startLine - 1),
222 - selected: selected.join("\n"),
223 - after: nearby(lines, draft.endLine + 1, draft.endLine + 3),
224 - };
301 + return selected.join("\n");
227 304 function nearby(lines: Map<number, string>, start: number, end: number) {
233 310 return out.join("\n");
313 +function requiredString(value: unknown, name: string) {
314 + if (typeof value !== "string") throw new Error(`${name} must be a string`);
315 + return value;
318 +function optionalString(value: unknown, name: string) {
319 + if (value === undefined) return undefined;
320 + return requiredString(value, name);
323 +function positiveInteger(value: unknown, name: string) {
324 + if (!Number.isInteger(value) || (value as number) < 1) throw new Error(`${name} must be a positive integer`);
325 + return value as number;
328 +function enumValue<T extends string>(value: unknown, choices: ReadonlySet<T>, name: string): T {
329 + if (typeof value === "string" && choices.has(value as T)) return value as T;
330 + throw new Error(`invalid ${name}`);
333 +function isRecord(value: unknown): value is Record<string, unknown> {
334 + return !!value && typeof value === "object" && !Array.isArray(value);
337 +function listen(server: Server) {
338 + return new Promise<void>((resolveListen, reject) => {
339 + server.once("error", reject);
340 + server.listen(0, "127.0.0.1", () => resolveListen());
341 + });
344 +function errorMessage(err: unknown) {
345 + return err instanceof Error ? err.message : String(err);
348 +class HttpError extends Error {
349 + constructor(readonly status: number, message: string) {
350 + super(message);

pi/agent/extensions/diff-review/static/app.css

Modified
1 -@font-face{font-family:Nugu Code Nerd;src:url(./assets/JetBrainsMonoNuguCode-e77247bx.woff2)format(woff2);font-weight:400;font-style:normal;font-display:swap}:root{--buncss-light:initial;--buncss-dark: ;color-scheme:light dark;--nugu-debug:#ed5eed;--nugu-error:#e46479;--nugu-warning:#9e9a69;--nugu-info:#3ec5dd;--nugu-content-normal:#ededed;--nugu-content-backdrop:#121212;--nugu-content-accent:#d151d1;--nugu-content-minor:#8b8b8b;--nugu-content-focus:#7ba1aa;--nugu-content-unfocus:#5d5d5d;--nugu-content-important-local:#b59ae4;--nugu-content-important-global:#dfd3f3;--nugu-ui-normal:#dbdbdb;--nugu-ui-backdrop:#242424;--nugu-ui-accent:#d86dd8;--nugu-ui-minor:#9d9d9d;--nugu-ui-focus:#9aabae;--nugu-ui-unfocus:#6f6f6f;--nugu-ui-important-local:#c9b6eb;--nugu-ui-important-global:#f3effb;--bg:var(--nugu-content-backdrop);--panel:color-mix(in srgb,var(--nugu-ui-backdrop)86%,var(--nugu-content-backdrop));--panel-2:var(--nugu-ui-backdrop);--panel-3:color-mix(in srgb,var(--nugu-ui-backdrop)72%,var(--nugu-content-backdrop));--fg:var(--nugu-content-normal);--fg-soft:var(--nugu-ui-normal);--muted:var(--nugu-ui-minor);--faint:var(--nugu-ui-unfocus);--accent:var(--nugu-ui-accent);--accent-2:var(--nugu-info);--focus:var(--nugu-ui-focus);--border:color-mix(in srgb,var(--nugu-ui-normal)14%,transparent);--shadow:0 18px 60px #00000073;--radius:12px;background:var(--bg);color:var(--fg);font-family:Inter,ui-sans-serif,system-ui,-apple-system,BlinkMacSystemFont,Segoe UI,Roboto,Noto Sans,Ubuntu,Cantarell,Helvetica Neue,sans-serif}@media (prefers-color-scheme:dark){:root{--buncss-light: ;--buncss-dark:initial}}:root[data-theme=light]{--buncss-light:initial;--buncss-dark: ;color-scheme:light;--nugu-debug:#a112a1;--nugu-error:#c0223c;--nugu-warning:#242317;--nugu-info:#13616e;--nugu-content-normal:#121212;--nugu-content-backdrop:#ededed;--nugu-content-accent:#ae2eae;--nugu-content-minor:#3b3b3b;--nugu-content-focus:#184e5b;--nugu-content-unfocus:#6f6f6f;--nugu-content-important-local:#715696;--nugu-content-important-global:#4f3c69;--nugu-ui-normal:#242424;--nugu-ui-backdrop:#dbdbdb;--nugu-ui-accent:#922792;--nugu-ui-minor:#292929;--nugu-ui-focus:#15333b;--nugu-ui-unfocus:#5d5d5d;--nugu-ui-important-local:#604980;--nugu-ui-important-global:#3e2f53;--panel:color-mix(in srgb,var(--nugu-ui-backdrop)72%,white);--panel-2:color-mix(in srgb,var(--nugu-ui-backdrop)88%,white);--panel-3:color-mix(in srgb,var(--nugu-ui-backdrop)55%,white);--border:color-mix(in srgb,var(--nugu-ui-normal)16%,transparent);--shadow:0 18px 60px #00000024}@media (prefers-color-scheme:light){:root[data-theme=system]{--buncss-light:initial;--buncss-dark: ;color-scheme:light;--nugu-debug:#a112a1;--nugu-error:#c0223c;--nugu-warning:#242317;--nugu-info:#13616e;--nugu-content-normal:#121212;--nugu-content-backdrop:#ededed;--nugu-content-accent:#ae2eae;--nugu-content-minor:#3b3b3b;--nugu-content-focus:#184e5b;--nugu-content-unfocus:#6f6f6f;--nugu-content-important-local:#715696;--nugu-content-important-global:#4f3c69;--nugu-ui-normal:#242424;--nugu-ui-backdrop:#dbdbdb;--nugu-ui-accent:#922792;--nugu-ui-minor:#292929;--nugu-ui-focus:#15333b;--nugu-ui-unfocus:#5d5d5d;--nugu-ui-important-local:#604980;--nugu-ui-important-global:#3e2f53;--panel:color-mix(in srgb,var(--nugu-ui-backdrop)72%,white);--panel-2:color-mix(in srgb,var(--nugu-ui-backdrop)88%,white);--panel-3:color-mix(in srgb,var(--nugu-ui-backdrop)55%,white);--border:color-mix(in srgb,var(--nugu-ui-normal)16%,transparent);--shadow:0 18px 60px #00000024}}*{box-sizing:border-box}html,body{height:100%}body{background:radial-gradient(circle at top left,color-mix(in srgb,var(--accent)12%,transparent),transparent 28rem),var(--bg);margin:0}button,select,textarea{font:inherit}button{cursor:pointer}button:disabled{cursor:not-allowed;opacity:.48}#app{display:grid;grid-template-columns:288px minmax(0,1fr)382px;overflow:hidden;height:100vh}#sidebar,#drawer,#main{min-height:0}#sidebar,#drawer{background:color-mix(in srgb,var(--panel)95%,transparent);border-color:var(--border);overflow:hidden;padding:14px 12px}#sidebar{border-inline-end:1px solid var(--border)}#drawer{border-inline-start:1px solid var(--border);overflow-y:auto}#main{display:grid;grid-template-rows:auto minmax(0,1fr);overflow:hidden}#topbar{display:flex;border-bottom:1px solid var(--border);background:color-mix(in srgb,var(--bg)82%,transparent);backdrop-filter:blur(8px);justify-content:space-between;align-items: center;gap:14px;padding:14px 14px 10px}#diffs{overflow:auto;padding:16px 14px 40px}.brand{display:grid;grid-template-columns:1fr auto;align-items: start;gap:10px;margin-bottom:14px}h1{letter-spacing:-.03em;color:var(--nugu-content-important-global);margin:0;font-size:20px;line-height:1}.subtitle,.eyebrow{color:var(--muted);margin-top:6px;font-size:12px}.eyebrow{text-transform:uppercase;letter-spacing:.08em;color:var(--accent-2);margin:0 0 3px;font-weight:750}#summary{color:var(--fg-soft);font-size:13px}.card-title,.file-title{color:var(--nugu-content-important-global);font-weight:800}.card-title{margin-bottom:8px;font-size:13px}#meta,#status,#selection{color:var(--muted);font-size:12px;line-height:1.5}#meta{margin-bottom:8px}#tree{border-radius:var(--radius);background:color-mix(in srgb,var(--bg)65%,var(--panel));overflow:hidden;height:calc(100vh - 116px)}.count-pill{border:1px solid color-mix(in srgb,var(--accent)35%,var(--border));background:color-mix(in srgb,var(--accent)16%,transparent);color:var(--nugu-content-important-global);white-space:nowrap;border-radius:999px;padding:6px 10px;font-size:12px;font-weight:750}.card{border:1px solid var(--border);border-radius:var(--radius);background:color-mix(in srgb,var(--panel-3)72%,transparent);margin-bottom:12px;padding:12px}.selection-card{border-color:color-mix(in srgb,var(--focus)26%,var(--border))}.selection-empty{color:var(--muted)}.selection-active{color:var(--fg);font-weight:800}.field-row{display:grid;grid-template-columns:1fr 1fr;gap:10px}.theme-label{min-width:102px;margin:0}.theme-label select{padding:7px 28px 7px 8px;font-size:12px}label{display:grid;color:var(--fg-soft);gap:6px;margin-block-start:10px;margin-block-end:10px;font-size:12px;font-weight:700}textarea,select{border:1px solid var(--border);background:color-mix(in srgb,var(--bg)74%,var(--panel-2));color:var(--fg);outline:none;border-radius:8px;width:100%;padding:9px 10px}textarea:focus,select:focus{border-color:var(--focus);box-shadow:0 0 0 3px color-mix(in srgb,var(--focus)28%,transparent)}button:focus-visible{border-color:var(--focus);box-shadow:0 0 0 3px color-mix(in srgb,var(--focus)28%,transparent)}textarea{resize:vertical;min-height:68px}.actions{position:sticky;display:grid;grid-template-columns:1fr 1fr;background:linear-gradient(transparent,var(--panel)20%);gap:8px;padding-top:4px;bottom:0}.actions button,#add,.remove-finding{border:1px solid var(--border);background:linear-gradient(180deg,color-mix(in srgb,var(--fg)8%,var(--panel-2)),color-mix(in srgb,var(--fg)3%,var(--panel-2)));color:var(--fg);border-radius:8px;padding:9px 10px;font-weight:750}#submit{background:linear-gradient(180deg,color-mix(in srgb,var(--accent)34%,var(--panel-2)),color-mix(in srgb,var(--accent)18%,var(--panel-2)));border-color:color-mix(in srgb,var(--accent)45%,var(--border))}#add{width:100%;margin-top:2px}.file-section{border-radius:var(--radius);margin-bottom:22px;scroll-margin-top:16px}.file-title{position:sticky;z-index:2;background:linear-gradient(var(--bg),color-mix(in srgb,var(--bg)78%,transparent));margin:0 0 8px;padding:8px 0;font-size:13px;top:-16px}diffs-container{border-radius:var(--radius);overflow:hidden;box-shadow:0 0 0 1px var(--border)}.empty-list{color:var(--muted);font-size:12px}.finding-item{display:grid;border:1px solid var(--border);border-left:3px solid var(--accent);background:color-mix(in srgb,var(--panel-2)72%,transparent);border-radius:8px;gap:6px;margin-block-start:7px;margin-block-end:7px;padding:8px;font-size:12px}.finding-chip{background:color-mix(in srgb,var(--accent)28%,var(--panel-2));color:var(--fg);border:1px solid color-mix(in srgb,var(--accent)42%,transparent);border-radius:5px;padding:4px 6px;font-size:11px}.remove-finding{color:var(--nugu-error);justify-self:start;padding:4px 8px;font-size:11px}.error{color:var(--nugu-error)}.ok{color:var(--nugu-info)}#tree file-tree-container,#tree{--trees-fg-override:var(--fg);--trees-muted-fg-override:var(--muted);--trees-bg-override:transparent;--trees-selected-bg-override:color-mix(in srgb,var(--accent)18%,transparent);--trees-hover-bg-override:color-mix(in srgb,var(--focus)14%,transparent);--trees-border-color-override:var(--border)}@media (max-width:1180px){#app{grid-template-columns:248px minmax(0,1fr);grid-template-rows:minmax(0,1fr)minmax(280px,40vh)}#drawer{grid-column:1/-1;grid-row:2;border-top:1px solid var(--border);border-inline-start:0}}
1 +@font-face{font-family:Nugu Code Nerd;src:url(./assets/JetBrainsMonoNuguCode-e77247bx.woff2)format(woff2);font-weight:400;font-style:normal;font-display:swap}:root{--buncss-light:initial;--buncss-dark: ;color-scheme:light dark;--nugu-debug:#ed5eed;--nugu-error:#e46479;--nugu-warning:#9e9a69;--nugu-info:#3ec5dd;--nugu-content-normal:#ededed;--nugu-content-backdrop:#121212;--nugu-content-accent:#d151d1;--nugu-content-minor:#8b8b8b;--nugu-content-focus:#7ba1aa;--nugu-content-unfocus:#5d5d5d;--nugu-content-important-local:#b59ae4;--nugu-content-important-global:#dfd3f3;--nugu-ui-normal:#dbdbdb;--nugu-ui-backdrop:#242424;--nugu-ui-accent:#d86dd8;--nugu-ui-minor:#9d9d9d;--nugu-ui-focus:#9aabae;--nugu-ui-unfocus:#6f6f6f;--nugu-ui-important-local:#c9b6eb;--nugu-ui-important-global:#f3effb;--bg:var(--nugu-content-backdrop);--panel:color-mix(in srgb,var(--nugu-ui-backdrop)86%,var(--nugu-content-backdrop));--panel-2:var(--nugu-ui-backdrop);--panel-3:color-mix(in srgb,var(--nugu-ui-backdrop)72%,var(--nugu-content-backdrop));--fg:var(--nugu-content-normal);--fg-soft:var(--nugu-ui-normal);--muted:var(--nugu-ui-minor);--faint:var(--nugu-ui-unfocus);--accent:var(--nugu-ui-accent);--accent-2:var(--nugu-info);--focus:var(--nugu-ui-focus);--border:color-mix(in srgb,var(--nugu-ui-normal)14%,transparent);--shadow:0 18px 60px #00000073;--radius:12px;background:var(--bg);color:var(--fg);font-family:Inter,ui-sans-serif,system-ui,-apple-system,BlinkMacSystemFont,Segoe UI,Roboto,Noto Sans,Ubuntu,Cantarell,Helvetica Neue,sans-serif}@media (prefers-color-scheme:dark){:root{--buncss-light: ;--buncss-dark:initial}}:root[data-theme=light]{--buncss-light:initial;--buncss-dark: ;color-scheme:light;--nugu-debug:#a112a1;--nugu-error:#c0223c;--nugu-warning:#242317;--nugu-info:#13616e;--nugu-content-normal:#121212;--nugu-content-backdrop:#ededed;--nugu-content-accent:#ae2eae;--nugu-content-minor:#3b3b3b;--nugu-content-focus:#184e5b;--nugu-content-unfocus:#6f6f6f;--nugu-content-important-local:#715696;--nugu-content-important-global:#4f3c69;--nugu-ui-normal:#242424;--nugu-ui-backdrop:#dbdbdb;--nugu-ui-accent:#922792;--nugu-ui-minor:#292929;--nugu-ui-focus:#15333b;--nugu-ui-unfocus:#5d5d5d;--nugu-ui-important-local:#604980;--nugu-ui-important-global:#3e2f53;--panel:color-mix(in srgb,var(--nugu-ui-backdrop)72%,white);--panel-2:color-mix(in srgb,var(--nugu-ui-backdrop)88%,white);--panel-3:color-mix(in srgb,var(--nugu-ui-backdrop)55%,white);--border:color-mix(in srgb,var(--nugu-ui-normal)16%,transparent);--shadow:0 18px 60px #00000024}*{box-sizing:border-box}html,body{height:100%}body{background:radial-gradient(circle at top left,color-mix(in srgb,var(--accent)12%,transparent),transparent 28rem),var(--bg);margin:0}button,select,textarea{font:inherit}button{cursor:pointer}button:disabled{cursor:not-allowed;opacity:.48}#app{display:grid;grid-template-columns:288px minmax(0,1fr)382px;overflow:hidden;height:100vh}#sidebar,#drawer,#main{min-height:0}#sidebar,#drawer{background:color-mix(in srgb,var(--panel)95%,transparent);border-color:var(--border);overflow:hidden;padding:14px 12px}#sidebar{border-inline-end:1px solid var(--border)}#drawer{border-inline-start:1px solid var(--border);overflow-y:auto;contain:layout paint}#main{display:grid;grid-template-rows:auto minmax(0,1fr);overflow:hidden}#topbar{display:flex;border-bottom:1px solid var(--border);background:color-mix(in srgb,var(--bg)92%,var(--panel));justify-content:space-between;align-items: center;gap:14px;padding:14px 14px 10px}#diffs{overflow:auto;padding:16px 14px 40px}.brand{display:grid;grid-template-columns:1fr auto;align-items: start;gap:10px;margin-bottom:14px}h1{letter-spacing:-.03em;color:var(--nugu-content-important-global);margin:0;font-size:22px;line-height:1}.subtitle{color:var(--muted);margin-top:6px;font-size:14px}.topbar-title{color:var(--nugu-content-important-global);margin:0 0 3px;font-size:16px;font-weight:800}#summary{color:var(--fg-soft);font-size:14px}.card-title,.file-title{color:var(--nugu-content-important-global);font-weight:800}.card-title{margin-bottom:8px;font-size:15px}#meta,#status,#selection{color:var(--muted);font-size:14px;line-height:1.5}#meta{margin-bottom:8px}#tree{border-radius:var(--radius);background:color-mix(in srgb,var(--bg)65%,var(--panel));overflow:hidden;height:calc(100vh - 116px)}.count-pill{border:1px solid color-mix(in srgb,var(--accent)35%,var(--border));background:color-mix(in srgb,var(--accent)16%,transparent);color:var(--nugu-content-important-global);white-space:nowrap;border-radius:999px;padding:6px 10px;font-size:14px;font-weight:750}.card{border:1px solid var(--border);border-radius:var(--radius);background:color-mix(in srgb,var(--panel-3)72%,transparent);margin-bottom:12px;padding:12px}.selection-card{border-color:color-mix(in srgb,var(--focus)26%,var(--border))}.selection-empty{color:var(--muted)}.selection-active{color:var(--fg);font-weight:800}.field-row{display:grid;grid-template-columns:1fr 1fr;gap:10px}.theme-label{min-width:102px;margin:0}.theme-label select{padding:7px 28px 7px 8px;font-size:14px}label{display:grid;color:var(--fg-soft);gap:6px;margin-block-start:10px;margin-block-end:10px;font-size:14px;font-weight:700}textarea,select{border:1px solid var(--border);background:color-mix(in srgb,var(--bg)74%,var(--panel-2));color:var(--fg);outline:none;border-radius:8px;width:100%;padding:9px 10px}textarea:focus,select:focus{border-color:var(--focus);box-shadow:0 0 0 3px color-mix(in srgb,var(--focus)28%,transparent)}button:focus-visible{border-color:var(--focus);box-shadow:0 0 0 3px color-mix(in srgb,var(--focus)28%,transparent)}textarea{resize:vertical;min-height:68px}.actions{position:sticky;display:grid;grid-template-columns:1fr 1fr;background:linear-gradient(transparent,var(--panel)20%);gap:8px;padding-top:4px;bottom:0}.actions button,#add,.remove-finding{border:1px solid var(--border);background:linear-gradient(180deg,color-mix(in srgb,var(--fg)8%,var(--panel-2)),color-mix(in srgb,var(--fg)3%,var(--panel-2)));color:var(--fg);border-radius:8px;padding:9px 10px;font-weight:750}#submit{background:linear-gradient(180deg,color-mix(in srgb,var(--accent)34%,var(--panel-2)),color-mix(in srgb,var(--accent)18%,var(--panel-2)));border-color:color-mix(in srgb,var(--accent)45%,var(--border))}#add{width:100%;margin-top:2px}.file-section{border-radius:var(--radius);margin-bottom:22px;scroll-margin-top:16px}.file-title{position:sticky;z-index:2;background:linear-gradient(var(--bg),color-mix(in srgb,var(--bg)78%,transparent));margin:0 0 8px;padding:8px 0;font-size:14px;top:-16px}diffs-container{border-radius:var(--radius);overflow:hidden;box-shadow:0 0 0 1px var(--border)}.empty-list{color:var(--muted);font-size:14px}.finding-item{display:grid;border:1px solid var(--border);border-left:3px solid var(--accent);background:color-mix(in srgb,var(--panel-2)72%,transparent);border-radius:8px;gap:6px;margin-block-start:7px;margin-block-end:7px;padding:8px;font-size:14px}.finding-chip{background:color-mix(in srgb,var(--accent)28%,var(--panel-2));color:var(--fg);border:1px solid color-mix(in srgb,var(--accent)42%,transparent);border-radius:5px;padding:4px 6px;font-size:11px}.remove-finding{color:var(--nugu-error);justify-self:start;padding:4px 8px;font-size:13px}.error{color:var(--nugu-error)}.ok{color:var(--nugu-info)}#tree file-tree-container,#tree{--trees-fg-override:var(--fg);--trees-muted-fg-override:var(--muted);--trees-bg-override:transparent;--trees-selected-bg-override:color-mix(in srgb,var(--accent)18%,transparent);--trees-hover-bg-override:color-mix(in srgb,var(--focus)14%,transparent);--trees-border-color-override:var(--border)}@media (max-width:1180px){#app{grid-template-columns:248px minmax(0,1fr);grid-template-rows:minmax(0,1fr)minmax(280px,40vh)}#drawer{grid-column:1/-1;grid-row:2;border-top:1px solid var(--border);border-inline-start:0}}

pi/agent/extensions/diff-review/static/index.html

Modified
30 30 <main id="main">
31 31 <header id="topbar">
32 32 <div>
33 - <div class="eyebrow">Review changed lines</div>
33 + <div class="topbar-title">Review changed lines</div>
34 34 <div id="summary">Select a changed line to add a finding.</div>
35 35 </div>
36 36 <div id="finding-count" class="count-pill">0 findings</div>
63 63 </select>
64 64 </label>
65 65 </div>
66 - <label>Comment
67 - <textarea id="comment" rows="5" placeholder="What should the agent inspect?"></textarea>
68 - </label>
69 - <label>Finding notes
70 - <textarea id="finding-notes" rows="3" placeholder="Optional context for this finding"></textarea>
66 + <label>Finding
67 + <textarea id="comment" rows="6" placeholder="Describe the issue or question for the selected line"></textarea>
71 68 </label>
72 69 <button id="add" disabled>Add finding</button>
73 70 </section>
78 75 </section>
80 77 <section class="card">
81 - <div class="card-title">Round notes</div>
82 - <textarea id="notes" rows="4" placeholder="Optional notes for the agent"></textarea>
78 + <div class="card-title">Review notes</div>
79 + <textarea id="notes" rows="4" placeholder="Optional context for the whole review"></textarea>
83 80 </section>
85 82 <footer class="actions">
86 83 <button id="cancel">Cancel</button>
87 - <button id="submit">Submit review</button>
84 + <button id="submit">Send to Pi</button>
88 85 </footer>
89 86 <div id="status" role="status"></div>
90 87 </aside>

pi/agent/extensions/diff-review/static/manifest.json

Modified
9 9 "sha256": "dc73d827bd8ee4b269745ea7ed084335e492d29f79c688db92e380dcb9c30bae"
11 11 "browser/index.html": {
12 - "sha256": "fd612bc0636ac42caabe4a53dc9d6d3240bb8e6f2ef7baacac1dce8cfc9a44ea"
12 + "sha256": "69a3bd1992e445408587f8e6e867cd2ad9178ee7e4d7a94bd4b09a73754ec474"
14 14 "browser/index.ts": {
15 - "sha256": "b916145303a601d5b4f2b80aa679c3cca07154907718f3f4d225835fafa3bdbd"
15 + "sha256": "936106f521b4eafc71248c2956dad825b414f3710fb5325b3e91f1da33df1242"
17 17 "browser/style.css": {
18 - "sha256": "6097978399286d3eee84f6326586f834f725b5884e1f5f72503ebdcc6a943ab3"
18 + "sha256": "272212b8a509d8506d5bf977b6cd49f5c72c10251b1d1b849ea41513d003e5e9"

pi/agent/extensions/diff-review/types.ts

Modified
67 67 source: ReviewSource;
68 68 diffText: string;
69 69 files: DiffFileSummary[];
70 + skippedFiles: string[];
70 71 carriedFindings: Finding[];
94 95 status: DiffFileStatus;
95 96 additions: DiffLineMap;
96 97 deletions: DiffLineMap;
98 + oldLines: DiffLineMap;
99 + newLines: DiffLineMap;
99 102 export type DiffIndex = Map<string, IndexedFileDiff>;