repositories / dotfiles

dotfiles

bugabingas dorkfiles

owned by bugabinga

rework diff-review browser session

115fb9df34fa2755fd7032d49a5117eed035f47a

Oliver Jan Krylow <oliver@bugabinga.net> ·

unsigned

Browse filesCompare with HEAD

Changed files (23)

+2092 / −265 text lines (partial) · 1 binary (striped old/new sizes in 64-byte units, not churn) · lines and sizes scale separately · 1 unavailable

Diff layout

pi/agent/extensions/diff-review/.gitignore

Added
new file mode 100644

+2 / −0 text lines

1node_modules/
2static/

pi/agent/extensions/diff-review/browser/assets/JetBrainsMonoNuguCode.LICENSE

Added
new file mode 100644

+96 / −0 text lines

1JetBrains Mono Nugu Code Font
2Copyright 2020 The JetBrains Mono Project Authors (https://github.com/JetBrains/JetBrainsMono)
3Portions Copyright 2014-2024 Ryan L McIntyre (Nerd Fonts, https://github.com/ryanoasis/nerd-fonts)
4
5This font is a patched derivative of JetBrains Mono with Nerd Font icon glyphs
6added, then subset to only the glyphs needed for code review display ("Nugu Code").
7
8Licensed under the SIL Open Font License, Version 1.1.
9See the full license text below.
11-----------------------------------------------------------
12SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007
13-----------------------------------------------------------
15PREAMBLE
16The goals of the Open Font License (OFL) are to stimulate worldwide
17development of collaborative font projects, to support the font creation
18efforts of academic and linguistic communities, and to provide a free and
19open framework in which fonts may be shared and improved in partnership
20with others.
22The OFL allows the licensed fonts to be used, studied, modified and
23redistributed freely as long as they are not sold by themselves. The
24fonts, including any derivative works, can be bundled, embedded,
25redistributed and/or sold with any software provided that any reserved
26names are not used by derivative works. The fonts and derivatives,
27however, cannot be released under any other type of license. The
28requirement for fonts to remain under this license does not apply
29to any document created using the fonts or their derivatives.
31DEFINITIONS
32"Font Software" refers to the set of files released by the Copyright
33Holder(s) under this license and clearly marked as such. This may
34include source files, build scripts and documentation.
36"Reserved Font Name" refers to any names specified as such after the
37copyright statement(s).
39"Original Version" refers to the collection of Font Software components as
40distributed by the Copyright Holder(s).
42"Modified Version" refers to any derivative made by adding to, deleting,
43or substituting -- in part or in whole -- any of the components of the
44Original Version, by changing formats or by porting the Font Software to
45a new environment.
47"Author" refers to any designer, engineer, programmer, technical
48writer or other person who contributed to the Font Software.
50PERMISSION & CONDITIONS
51Permission is hereby granted, free of charge, to any person obtaining
52a copy of the Font Software, to use, study, copy, merge, embed, modify,
53redistribute, and sell modified and unmodified copies of the Font
54Software, subject to the following conditions:
561) Neither the Font Software nor any of its individual components,
57in Original or Modified Versions, may be sold by itself.
592) Original or Modified Versions of the Font Software may be bundled,
60redistributed and/or sold with any software, provided that each copy
61contains the above copyright notice and this license. These can be
62included either as stand-alone text files, human-readable headers or
63in the appropriate machine-readable metadata fields within text or
64binary files as long as those fields can be easily viewed by the user.
663) No Modified Version of the Font Software may use the Reserved Font
67Name(s) unless explicit written permission is granted by the corresponding
68Copyright Holder. This restriction only applies to the primary font name
69as presented to the users.
714) The name(s) of the Copyright Holder(s) or the Author(s) of the
72Font Software shall not be used to promote, endorse or advertise any
73Modified Version, except to acknowledge the contribution(s) of the
74Copyright Holder(s) and the Author(s) or with their explicit written
75permission.
775) The Font Software, modified or unmodified, in part or in whole,
78must be distributed entirely under this license, and must not be
79distributed under any other license. The requirement for fonts to
80remain under this license does not apply to any document created
81using the fonts or their derivatives.
83TERMINATION
84This license becomes null and void if any of the above conditions are
85not met.
87DISCLAIMER
88THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
89EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF
90MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
91OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE
92COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
93INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL
94DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
95FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM
96OTHER DEALINGS IN THE FONT SOFTWARE.

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

Modified

+50 / −22 text lines

55 <meta name="viewport" content="width=device-width, initial-scale=1" />
66 <title>Pi Diff Review</title>
77 <link rel="icon" href="data:," />
8 <script>
9 (() => {
10 const mode = localStorage.getItem("diff-review-theme") || "system";
11 const systemLight = matchMedia("(prefers-color-scheme: light)").matches;
12 document.documentElement.dataset.themeMode = mode;
13 document.documentElement.dataset.theme = mode === "system" ? (systemLight ? "light" : "dark") : mode;
14 })();
15 </script>
816 <link rel="stylesheet" href="/static/app.css" />
917</head>
1018<body>
1523 <h1>Diff Review</h1>
1624 <div class="subtitle">Pi × Pierre</div>
1725 </div>
18 <label class="theme-label">Theme
26 <label class="theme-label" aria-label="Theme mode">
27 <span class="theme-icon" aria-hidden="true">◐</span>
1928 <select id="theme-mode" aria-label="Theme mode">
2029 <option value="system" selected>system</option>
2130 <option value="dark">dark</option>
2736 <div id="tree"></div>
2837 </aside>
39 <div id="left-splitter" class="splitter" role="separator" aria-label="Resize file tree" aria-orientation="vertical">
40 <button id="toggle-left" class="pane-toggle" type="button" aria-label="Collapse file tree">‹</button>
41 </div>
3043 <main id="main">
3144 <header id="topbar">
3245 <div>
3346 <div class="topbar-title">Review changed lines</div>
3447 <div id="summary">Select a changed line to add a finding.</div>
3548 </div>
36 <div id="finding-count" class="count-pill">0 findings</div>
49 <div class="topbar-actions">
50 <div id="search-wrap" class="search-wrap">
51 <input id="search" type="text" role="searchbox" placeholder="Search code…" autocomplete="off" spellcheck="false" aria-label="Search code in diff" />
52 <button id="search-clear" class="search-clear" type="button" aria-label="Clear code search">×</button>
53 <span id="search-badge" class="search-badge" hidden></span>
54 <div id="search-results" class="search-results" hidden></div>
55 </div>
56 <div id="finding-count" class="count-pill">0 findings</div>
57 </div>
3758 </header>
3859 <div id="diffs"></div>
39 </main>
41 <aside id="drawer">
42 <section class="card selection-card">
43 <div class="card-title">Selection</div>
44 <div id="selection" class="selection-empty">Click an added or deleted line.</div>
45 </section>
47 <section class="card">
48 <div class="card-title">New finding</div>
60 <section id="inline-finding" class="inline-finding" aria-label="New finding" hidden>
61 <div class="inline-head">
62 <div>
63 <div class="inline-title">New finding</div>
64 <div id="selection" class="selection-empty">Click an added or deleted line.</div>
65 </div>
66 <button id="inline-cancel" class="inline-close" type="button" aria-label="Close finding input">×</button>
67 </div>
4968 <div class="field-row">
5069 <label>Severity
5170 <select id="severity">
52 <option value="high">high</option>
53 <option value="medium" selected>medium</option>
54 <option value="low">low</option>
71 <option value="high">🔥 high</option>
72 <option value="medium" selected>😒 medium</option>
73 <option value="low">🦟 low</option>
5574 </select>
75 <div class="field-subtitle" id="severity-sub">suspicious little gremlin</div>
5676 </label>
5777 <label>Category
5878 <select id="category">
59 <option value="bug" selected>bug</option>
60 <option value="style">style</option>
61 <option value="perf">perf</option>
62 <option value="question">question</option>
79 <option value="bug" selected>🐛 bug</option>
80 <option value="style">💅 style</option>
81 <option value="perf">🐌 perf</option>
82 <option value="question">🤨 question</option>
6383 </select>
84 <div class="field-subtitle" id="category-sub">exquisite disaster</div>
6485 </label>
6586 </div>
6687 <label>Finding
67 <textarea id="comment" rows="6" placeholder="Describe the issue or question for the selected line"></textarea>
88 <textarea id="comment" rows="5" placeholder="Describe the issue or question for this line"></textarea>
6889 </label>
6990 <button id="add" disabled>Add finding</button>
7091 </section>
92 </main>
94 <div id="right-splitter" class="splitter" role="separator" aria-label="Resize review panel" aria-orientation="vertical">
95 <button id="toggle-right" class="pane-toggle" type="button" aria-label="Collapse review panel">›</button>
96 </div>
98 <aside id="drawer">
7299 <section class="card findings-card">
73 <div class="card-title">Findings</div>
100 <div class="card-title findings-title"><span>Collected findings</span><span id="drawer-count">0</span></div>
74101 <div id="findings" class="empty-list">No findings yet.</div>
75102 </section>
83110 <button id="cancel">Cancel</button>
84111 <button id="submit">Send to Pi</button>
85112 </footer>
86 <div id="status" role="status"></div>
87113 </aside>
115 <div id="status" role="status" aria-live="polite">Ready</div>
88116 </div>
89117 <script type="module" src="/static/app.js"></script>
90118</body>

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

Modified

+760 / −47 text lines

11import "./style.css";
2import { FileDiff, parsePatchFiles, type DiffLineAnnotation, type FileDiffMetadata, type SelectedLineRange } from "@pierre/diffs";
3import { FileTree, type GitStatusEntry } from "@pierre/trees";
2import type { DiffLineAnnotation, FileDiff, FileDiffMetadata, SelectedLineRange } from "@pierre/diffs";
3import type { FileTree, FileTreeRowDecorationRenderer, GitStatusEntry } from "@pierre/trees";
4import { DIFF_FONT_CSS, TREE_CSS } from "./shadow-css.js";
5import { NUGU_CODE_THEME, registerNuguCodeTheme } from "./theme.js";
46import { HEARTBEAT_INTERVAL_MS, REVIEW_POLL_INTERVAL_MS } from "../constants.js";
57import type { FindingDraft, ReviewCategory, ReviewPayload, ReviewSeverity, ReviewSide } from "../types.js";
79type FindingMeta = { findingId: string; severity: ReviewSeverity; category: ReviewCategory; comment: string };
810type ThemeMode = "system" | "dark" | "light";
11type PaneSide = "left" | "right";
912type ReviewSelection = { file: string; side: ReviewSide; startLine: number; endLine: number };
13type ViewPoint = { x: number; y: number };
14type SearchEntry = { file: string; side: "additions" | "deletions"; line: number; text: string };
15type SearchMatch = SearchEntry & { matchStart: number; matchEnd: number };
1117type Elements = {
18 app: HTMLElement;
1219 meta: HTMLElement;
1320 summary: HTMLElement;
1421 findingCount: HTMLElement;
22 drawerCount: HTMLElement;
1523 tree: HTMLElement;
1624 diffs: HTMLElement;
25 inlineFinding: HTMLElement;
1726 selection: HTMLElement;
1827 severity: HTMLSelectElement;
28 severitySub: HTMLElement;
1929 category: HTMLSelectElement;
30 categorySub: HTMLElement;
2031 comment: HTMLTextAreaElement;
2132 add: HTMLButtonElement;
33 inlineCancel: HTMLButtonElement;
2234 findings: HTMLElement;
2335 notes: HTMLTextAreaElement;
36 search: HTMLInputElement;
37 searchClear: HTMLButtonElement;
38 searchResults: HTMLElement;
2439 cancel: HTMLButtonElement;
2540 submit: HTMLButtonElement;
2641 status: HTMLElement;
2742 themeMode: HTMLSelectElement;
43 leftSplitter: HTMLElement;
44 rightSplitter: HTMLElement;
45 toggleLeft: HTMLButtonElement;
46 toggleRight: HTMLButtonElement;
2847};
3049const ROUTES = {
3554 submit: "/api/submit",
3655} as const;
3756const THEME_STORAGE_KEY = "diff-review-theme";
38const 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`;
57const LAYOUT_STORAGE_KEY = "diff-review-layout";
4558const REVIEW_CATEGORIES = ["bug", "style", "perf", "question"] as const satisfies readonly ReviewCategory[];
4659const REVIEW_SEVERITIES = ["high", "medium", "low"] as const satisfies readonly ReviewSeverity[];
4760const THEME_MODES = ["system", "dark", "light"] as const satisfies readonly ThemeMode[];
61const SEVERITY_SUBS: Record<string, string> = { high: "ship it to prod, coward", medium: "suspicious little gremlin", low: "tiny crime, still crime" };
62const CATEGORY_SUBS: Record<string, string> = { bug: "exquisite disaster", style: "crimes against taste", perf: "artisanal slowness", question: "explain yourself" };
63const PANE_LIMITS = {
64 left: { min: 180, max: 560, fallback: 288 },
65 right: { min: 280, max: 680, fallback: 382 },
66} as const;
68type LayoutState = {
69 left: number;
70 right: number;
71 leftCollapsed: boolean;
72 rightCollapsed: boolean;
73};
4975const token = new URLSearchParams(location.search).get("token") ?? "";
5076const els: Elements = {
77 app: must("app"),
5178 meta: must("meta"),
5279 summary: must("summary"),
5380 findingCount: must("finding-count"),
81 drawerCount: must("drawer-count"),
5482 tree: must("tree"),
5583 diffs: must("diffs"),
84 inlineFinding: must("inline-finding"),
5685 selection: must("selection"),
5786 severity: mustSelect("severity"),
87 severitySub: must("severity-sub"),
5888 category: mustSelect("category"),
89 categorySub: must("category-sub"),
5990 comment: mustText("comment"),
6091 add: mustButton("add"),
92 inlineCancel: mustButton("inline-cancel"),
6193 findings: must("findings"),
6294 notes: mustText("notes"),
95 search: must("search") as HTMLInputElement,
96 searchClear: mustButton("search-clear"),
97 searchResults: must("search-results"),
6398 cancel: mustButton("cancel"),
6499 submit: mustButton("submit"),
65100 status: must("status"),
66101 themeMode: mustSelect("theme-mode"),
102 leftSplitter: must("left-splitter"),
103 rightSplitter: must("right-splitter"),
104 toggleLeft: mustButton("toggle-left"),
105 toggleRight: mustButton("toggle-right"),
67106};
69108const findings: FindingDraft[] = [];
70109const diffViews = new Map<string, FileDiff<FindingMeta>>();
71110const systemTheme = window.matchMedia("(prefers-color-scheme: light)");
72111let fileTree: FileTree | undefined;
112let selectedFile: string | undefined;
73113let selected: ReviewSelection | undefined;
114let lastDiffPointer: ViewPoint | undefined;
115let searchIndex: SearchEntry[] = [];
116let searchResults: SearchMatch[] = [];
117let searchActiveIndex = -1;
118let searchDebounce: number | undefined;
119let diffsModule: typeof import("@pierre/diffs") | undefined;
120let treesModule: typeof import("@pierre/trees") | undefined;
74121let heartbeat: number | undefined;
75122let reviewPoll: number | undefined;
76123let reviewHash = "";
124let renderGeneration = 0;
125let searchIndexing = false;
126let notesGrowFrame: number | undefined;
77127let closing = false;
78128let themeMode: ThemeMode = readThemeMode();
80130applyThemeMode(themeMode);
81131els.themeMode.value = themeMode;
132applyLayout(readLayout());
83main().catch((err) => setStatus(errorMessage(err), "error"));
134main().catch((err) => setDisconnectedStatus(err));
84135window.addEventListener("pagehide", closeFromBrowser);
85136systemTheme.addEventListener("change", () => {
86137 if (themeMode === "system") applyThemeMode(themeMode);
89140async function main() {
90141 if (!token) throw new Error("Missing review token");
91 const review = await api<ReviewPayload>(ROUTES.review);
142 setStatus("Loading review…");
143 const reviewPromise = api<ReviewPayload>(ROUTES.review);
144 setStatus("Loading diff renderer…");
145 await loadRendererModules();
146 const review = await reviewPromise;
92147 startHeartbeat();
93148 startReviewPolling();
94 renderReview(review);
95149 wireActions();
150 await renderReview(review);
96151 setStatus("Ready");
99function renderReview(review: ReviewPayload) {
154async function loadRendererModules() {
155 if (diffsModule && treesModule) return;
156 const [diffs, trees] = await Promise.all([import("@pierre/diffs"), import("@pierre/trees")]);
157 diffsModule = diffs;
158 treesModule = trees;
159 registerNuguCodeTheme(diffs.registerCustomCSSVariableTheme);
160}
162function diffs() {
163 if (!diffsModule) throw new Error("Diff renderer not loaded");
164 return diffsModule;
165}
167function trees() {
168 if (!treesModule) throw new Error("File tree renderer not loaded");
169 return treesModule;
170}
172async function renderReview(review: ReviewPayload) {
173 const generation = ++renderGeneration;
100174 reviewHash = hashReview(review);
101175 renderMeta(review);
102176 renderTree(review);
103 renderDiffs(review);
177 const fileDiffs = await renderDiffs(review, generation);
178 if (!fileDiffs || generation !== renderGeneration) return;
104179 renderAnnotations();
180 void buildSearchIndex(fileDiffs, generation);
107183function renderMeta(review: ReviewPayload) {
108184 const totals = review.files.reduce((sum, file) => ({ additions: sum.additions + file.additions, deletions: sum.deletions + file.deletions }), { additions: 0, deletions: 0 });
109 els.meta.textContent = `round ${review.round} · ${review.source.kind} · ${review.files.length} files`;
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.`;
185 els.meta.replaceChildren(metaChip("round", String(review.round)), metaChip("reviewing", sourceLabel(review.source)));
187 els.summary.replaceChildren();
188 const stats = document.createElement("span");
189 stats.className = "summary-stats";
190 stats.textContent = `${review.files.length} files · +${totals.additions} −${totals.deletions}`;
191 els.summary.appendChild(stats);
192 if (review.skippedFiles.length > 0) {
193 const skipped = document.createElement("span");
194 skipped.className = "summary-skipped";
195 skipped.textContent = `skipped ${review.skippedFiles.length} oversized/binary file${review.skippedFiles.length === 1 ? "" : "s"}`;
196 els.summary.appendChild(skipped);
197 }
198 const hint = document.createElement("span");
199 hint.className = "summary-hint";
200 hint.textContent = "Click a changed line, describe issue, send findings to Pi.";
201 els.summary.appendChild(hint);
112202 updateFindingCount();
205function sourceLabel(source: ReviewPayload["source"]): string {
206 const scope = source.files?.length ? ` · ${source.files.length} path${source.files.length === 1 ? "" : "s"}` : "";
207 if (source.kind === "working-tree") return `unstaged changes${scope}`;
208 if (source.kind === "staged") return `staged changes${scope}`;
209 return `changes vs ${source.base}${scope}`;
210}
212function metaChip(label: string, value: string) {
213 const chip = document.createElement("span");
214 chip.className = `meta-chip meta-${label}`;
215 const labelNode = document.createElement("span");
216 labelNode.className = "meta-label";
217 labelNode.textContent = label;
218 const valueNode = document.createElement("span");
219 valueNode.className = "meta-value";
220 valueNode.textContent = value;
221 chip.append(labelNode, valueNode);
222 return chip;
223}
115225function renderTree(review: ReviewPayload) {
116226 fileTree?.cleanUp();
117 fileTree = new FileTree({
118 paths: review.files.map((file) => file.path),
227 const skipped = skippedFilesByPath(review);
228 const reviewPaths = review.files.flatMap((file) => file.prevPath && file.prevPath !== file.path ? [file.prevPath, file.path] : [file.path]);
229 const paths = [...reviewPaths, ...[...skipped.keys()].filter((path) => !reviewPaths.includes(path))];
230 fileTree = new (trees().FileTree)({
231 paths,
119232 search: true,
233 unsafeCSS: TREE_CSS,
120234 initialExpansion: "open",
121 gitStatus: review.files.map((file) => ({ path: file.path, status: toGitStatus(file.status) })) satisfies GitStatusEntry[],
122 onSelectionChange: ([path]) => scrollToFile(path),
235 initialSelectedPaths: selectedFile && review.files.some((file) => file.path === selectedFile) ? [selectedFile] : [],
236 gitStatus: [
237 ...review.files.flatMap((file) => treeGitStatusEntries(file)),
238 ...[...skipped.keys()].map((path) => ({ path, status: "ignored" as const })),
239 ] satisfies GitStatusEntry[],
240 renderRowDecoration: treeRowDecoration(review, skipped),
241 onSelectionChange: ([path]) => {
242 const renamedTarget = path ? renamedTargetForPrevPath(review, path) : undefined;
243 if (renamedTarget) {
244 fileTree?.getItem(path)?.deselect();
245 fileTree?.getItem(renamedTarget)?.select();
246 selectFile(renamedTarget, true);
247 return;
248 }
249 if (path && skipped.has(path)) {
250 fileTree?.getItem(path)?.deselect();
251 if (selectedFile) fileTree?.getItem(selectedFile)?.select();
252 setStatus(`Skipped ${path}: ${skipped.get(path)}`);
253 return;
254 }
255 selectFile(path, true);
256 },
123257 });
124258 fileTree.render({ fileTreeContainer: els.tree });
259 wireTreeSearchClear(fileTree);
127function renderDiffs(review: ReviewPayload) {
262function treeGitStatusEntries(file: ReviewPayload["files"][number]): GitStatusEntry[] {
263 if (file.status === "renamed" && file.prevPath && file.prevPath !== file.path) return [
264 { path: file.prevPath, status: "deleted" },
265 { path: file.path, status: "renamed" },
266 ];
267 return [{ path: file.path, status: toGitStatus(file.status) }];
268}
270function renamedTargetForPrevPath(review: ReviewPayload, path: string) {
271 return review.files.find((file) => file.status === "renamed" && file.prevPath === path)?.path;
272}
274function treeRowDecoration(review: ReviewPayload, skipped: ReadonlyMap<string, string>): FileTreeRowDecorationRenderer {
275 return ({ row }) => {
276 if (row.kind !== "file") return null;
277 const reason = skipped.get(row.path);
278 if (reason) return { text: "skip", title: reason };
279 const renameSource = review.files.find((file) => file.status === "renamed" && file.prevPath === row.path);
280 if (renameSource) return { text: "from", title: `renamed to ${renameSource.path}` };
281 const renameTarget = review.files.find((file) => file.status === "renamed" && file.path === row.path && file.prevPath);
282 if (renameTarget?.prevPath) return { text: "to", title: `renamed from ${renameTarget.prevPath}` };
283 return null;
284 };
285}
287function wireTreeSearchClear(tree: FileTree) {
288 const root = els.tree.shadowRoot;
289 if (!root) return;
291 const sync = () => {
292 const container = root.querySelector<HTMLElement>("[data-file-tree-search-container]");
293 const input = root.querySelector<HTMLInputElement>("[data-file-tree-search-input]");
294 if (!container || !input || container.querySelector(".tree-search-clear")) return;
295 const clear = document.createElement("button");
296 clear.type = "button";
297 clear.className = "tree-search-clear";
298 clear.textContent = "×";
299 clear.setAttribute("aria-label", "Clear file search");
300 clear.addEventListener("pointerdown", (event) => event.preventDefault());
301 clear.addEventListener("click", (event) => {
302 event.preventDefault();
303 tree.setSearch("");
304 input.value = "";
305 input.focus();
306 });
307 container.appendChild(clear);
308 };
310 sync();
311 const observer = new MutationObserver(sync);
312 observer.observe(root, { childList: true, subtree: true });
313 const cleanup = tree.cleanUp.bind(tree);
314 tree.cleanUp = () => {
315 observer.disconnect();
316 cleanup();
317 };
318}
320function skippedFilesByPath(review: ReviewPayload): Map<string, string> {
321 const skipped = new Map<string, string>();
322 for (const entry of review.skippedFiles) {
323 const { path, reason } = parseSkippedFile(entry);
324 skipped.set(path, reason);
325 }
326 return skipped;
327}
329function parseSkippedFile(entry: string): { path: string; reason: string } {
330 const match = /^(.*) \(([^()]*)\)$/.exec(entry);
331 if (!match) return { path: entry, reason: "oversized/binary" };
332 return { path: match[1], reason: match[2] };
333}
335async function renderDiffs(review: ReviewPayload, generation: number): Promise<FileDiffMetadata[] | undefined> {
128336 for (const view of diffViews.values()) view.cleanUp();
129337 diffViews.clear();
130338 els.diffs.replaceChildren();
131 selected = undefined;
132 setSelection("", null);
133 for (const patch of parsePatchFiles(review.diffText, `diff-review-${review.round}`, true)) {
134 for (const fileDiff of patch.files) renderFileDiff(fileDiff);
339 clearSelection(false);
341 const files = diffs().parsePatchFiles(review.diffText, `diff-review-${review.round}`, true).flatMap((patch) => patch.files);
342 for (let index = 0; index < files.length; index++) {
343 if (generation !== renderGeneration) return undefined;
344 renderFileDiff(files[index]);
345 if (files.length > 1) setStatus(`Rendering ${index + 1}/${files.length} files…`);
346 await yieldToBrowser();
135347 }
348 return files;
138351function renderFileDiff(fileDiff: FileDiffMetadata) {
139352 const section = fileSection(fileDiff);
140 const view = new FileDiff<FindingMeta>({
141 theme: { dark: "pierre-dark", light: "pierre-light" },
353 const view = new (diffs().FileDiff)<FindingMeta>({
354 theme: { dark: NUGU_CODE_THEME, light: NUGU_CODE_THEME },
142355 diffStyle: "split",
143356 overflow: "scroll",
144357 enableLineSelection: true,
146359 lineHoverHighlight: "both",
147360 themeType: themeMode,
148361 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)),
362 onLineSelected: (range) => setSelection(fileDiff.name, range, lastDiffPointer),
363 onGutterUtilityClick: (range) => setSelection(fileDiff.name, range, lastDiffPointer),
364 onLineClick: ({ lineNumber, annotationSide, event }) => setSelection(fileDiff.name, singleLineRange(lineNumber, annotationSide), eventPoint(event)),
365 onLineNumberClick: ({ lineNumber, annotationSide, event }) => setSelection(fileDiff.name, singleLineRange(lineNumber, annotationSide), eventPoint(event)),
153366 renderAnnotation: renderAnnotation,
154367 });
155368 view.render({ fileDiff, containerWrapper: section, lineAnnotations: [] });
160373 const section = document.createElement("section");
161374 section.className = "file-section";
162375 section.dataset.fileSection = fileDiff.name;
376 if (fileDiff.name === selectedFile) section.dataset.selectedFile = "true";
164378 const title = document.createElement("h2");
165379 title.className = "file-title";
180394 return chip;
183function setSelection(file: string, range: SelectedLineRange | null) {
397function setSelection(file: string, range: SelectedLineRange | null, point?: ViewPoint) {
184398 const next = normalizeSelection(file, range);
399 if (!next) {
400 clearSelection(false);
401 return;
402 }
185403 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.";
404 els.add.disabled = false;
405 els.selection.className = "selection-active";
406 els.selection.textContent = selectionLabel(next);
407 showFindingForm(next, point);
408}
410function showFindingForm(selection: ReviewSelection, point?: ViewPoint) {
411 const anchor = point ?? lineAnchor(selection) ?? centerPoint();
412 els.inlineFinding.hidden = false;
413 els.inlineFinding.dataset.open = "true";
414 positionFindingForm(anchor);
415 requestAnimationFrame(() => {
416 positionFindingForm(anchor);
417 els.comment.focus();
418 });
419}
421function hideFindingForm() {
422 els.inlineFinding.hidden = true;
423 delete els.inlineFinding.dataset.open;
424}
426function positionFindingForm(point: ViewPoint) {
427 const margin = 12;
428 const gap = 14;
429 const rect = els.inlineFinding.getBoundingClientRect();
430 const width = rect.width || 360;
431 const height = rect.height || 280;
432 let left = point.x + gap;
433 let top = point.y - 22;
434 if (left + width + margin > window.innerWidth) left = point.x - width - gap;
435 left = Math.max(margin, Math.min(left, window.innerWidth - width - margin));
436 top = Math.max(margin, Math.min(top, window.innerHeight - height - margin));
437 els.inlineFinding.style.left = `${Math.round(left)}px`;
438 els.inlineFinding.style.top = `${Math.round(top)}px`;
439}
441function lineAnchor(selection: ReviewSelection): ViewPoint | undefined {
442 const section = document.querySelector<HTMLElement>(`[data-file-section="${cssEscape(selection.file)}"]`);
443 const container = section?.querySelector("diffs-container") as HTMLElement | null;
444 const root = container?.shadowRoot;
445 const line = root?.querySelector<HTMLElement>(`[data-${selection.side}] [data-line="${selection.startLine}"]`);
446 if (!line) return undefined;
447 const rect = line.getBoundingClientRect();
448 return { x: rect.left + 24, y: rect.top + rect.height / 2 };
449}
451function centerPoint(): ViewPoint {
452 return { x: window.innerWidth / 2, y: window.innerHeight / 2 };
453}
455function eventPoint(event: MouseEvent | PointerEvent): ViewPoint {
456 return { x: event.clientX, y: event.clientY };
191459function normalizeSelection(file: string, range: SelectedLineRange | null): ReviewSelection | undefined {
208476function wireActions() {
209477 els.themeMode.addEventListener("change", updateThemeMode);
478 els.severity.addEventListener("change", () => { els.severitySub.textContent = SEVERITY_SUBS[els.severity.value] ?? ""; });
479 els.category.addEventListener("change", () => { els.categorySub.textContent = CATEGORY_SUBS[els.category.value] ?? ""; });
210480 els.add.addEventListener("click", addFinding);
211481 els.submit.addEventListener("click", submitReview);
212482 els.cancel.addEventListener("click", cancelReview);
483 els.toggleLeft.addEventListener("click", () => togglePane("left"));
484 els.toggleRight.addEventListener("click", () => togglePane("right"));
485 els.leftSplitter.addEventListener("pointerdown", (event) => startPaneResize("left", event));
486 els.rightSplitter.addEventListener("pointerdown", (event) => startPaneResize("right", event));
487 els.diffs.addEventListener("pointerdown", (event) => { lastDiffPointer = eventPoint(event); }, true);
488 els.diffs.addEventListener("pointerup", (event) => { lastDiffPointer = eventPoint(event); }, true);
489 els.inlineCancel.addEventListener("click", () => {
490 clearFindingForm();
491 clearSelection(true);
492 });
493 els.comment.addEventListener("keydown", (event) => {
494 if ((event.metaKey || event.ctrlKey) && event.key === "Enter") void addFinding();
495 if (event.key === "Escape") clearSelection(true);
496 });
497 els.notes.addEventListener("input", () => scheduleNotesAutoGrow());
498 scheduleNotesAutoGrow();
499 els.search.addEventListener("input", () => {
500 window.clearTimeout(searchDebounce);
501 searchDebounce = window.setTimeout(runSearch, 120);
502 });
503 els.searchClear.addEventListener("click", () => clearCodeSearch(true));
504 els.search.addEventListener("search", () => {
505 if (!els.search.value.trim()) clearCodeSearch(false);
506 });
507 els.search.addEventListener("keydown", (event) => {
508 if (isEscapeKey(event)) {
509 event.preventDefault();
510 event.stopPropagation();
511 closeCodeSearchPopup();
512 return;
513 }
514 if (event.key === "ArrowDown" || event.key === "ArrowUp") {
515 event.preventDefault();
516 navigateSearch(event.key === "ArrowDown" ? 1 : -1);
517 return;
518 }
519 if (event.key === "Enter") {
520 event.preventDefault();
521 if (searchResults.length === 0) return;
522 const idx = searchActiveIndex >= 0 ? searchActiveIndex : 0;
523 jumpToMatch(searchResults[idx], idx);
524 hideSearch();
525 }
526 });
527 document.addEventListener("keydown", (event) => {
528 if (!isEscapeKey(event) || els.searchResults.hidden) return;
529 event.preventDefault();
530 event.stopPropagation();
531 closeCodeSearchPopup();
532 }, true);
533 document.addEventListener("click", (event) => {
534 if (!els.searchResults.contains(event.target as Node) && event.target !== els.search) hideSearch();
535 });
536}
538function scheduleNotesAutoGrow() {
539 if (notesGrowFrame !== undefined) return;
540 notesGrowFrame = requestAnimationFrame(() => {
541 notesGrowFrame = undefined;
542 autoGrowTextarea(els.notes);
543 });
544}
546function autoGrowTextarea(textarea: HTMLTextAreaElement) {
547 textarea.style.height = "auto";
548 textarea.style.height = `${textarea.scrollHeight}px`;
549}
551function yieldToBrowser() {
552 return new Promise<void>((resolve) => {
553 const requestIdle = window.requestIdleCallback as ((callback: () => void, options?: { timeout: number }) => number) | undefined;
554 if (requestIdle) requestIdle(() => resolve(), { timeout: 80 });
555 else requestAnimationFrame(() => resolve());
556 });
215559function updateThemeMode() {
219563 for (const view of diffViews.values()) view.setThemeType(themeMode);
566function togglePane(side: PaneSide) {
567 const layout = readLayout();
568 if (side === "left") layout.leftCollapsed = !layout.leftCollapsed;
569 else layout.rightCollapsed = !layout.rightCollapsed;
570 applyLayout(layout);
571 writeLayout(layout);
572}
574function startPaneResize(side: PaneSide, event: PointerEvent) {
575 if ((event.target as HTMLElement).closest("button")) return;
576 event.preventDefault();
577 const layout = readLayout();
578 if (side === "left") layout.leftCollapsed = false;
579 else layout.rightCollapsed = false;
580 els.app.dataset.resizing = side;
581 try { els.app.setPointerCapture?.(event.pointerId); } catch {}
583 const move = (moveEvent: PointerEvent) => {
584 const next = { ...layout };
585 if (side === "left") next.left = clampPane("left", moveEvent.clientX);
586 else next.right = clampPane("right", window.innerWidth - moveEvent.clientX);
587 applyLayout(next);
588 writeLayout(next);
589 };
590 const stop = () => {
591 delete els.app.dataset.resizing;
592 window.removeEventListener("pointermove", move);
593 window.removeEventListener("pointerup", stop);
594 window.removeEventListener("pointercancel", stop);
595 };
597 window.addEventListener("pointermove", move);
598 window.addEventListener("pointerup", stop, { once: true });
599 window.addEventListener("pointercancel", stop, { once: true });
600}
602function readLayout(): LayoutState {
603 const stored = localStorage.getItem(LAYOUT_STORAGE_KEY);
604 if (!stored) return defaultLayout();
605 try {
606 const value = JSON.parse(stored) as Partial<LayoutState>;
607 return {
608 left: clampPane("left", value.left),
609 right: clampPane("right", value.right),
610 leftCollapsed: value.leftCollapsed === true,
611 rightCollapsed: value.rightCollapsed === true,
612 };
613 } catch {
614 return defaultLayout();
615 }
616}
618function writeLayout(layout: LayoutState) {
619 localStorage.setItem(LAYOUT_STORAGE_KEY, JSON.stringify(layout));
620}
622function defaultLayout(): LayoutState {
623 return { left: PANE_LIMITS.left.fallback, right: PANE_LIMITS.right.fallback, leftCollapsed: false, rightCollapsed: false };
624}
626function applyLayout(layout: LayoutState) {
627 els.app.style.setProperty("--left-pane", `${layout.leftCollapsed ? 0 : layout.left}px`);
628 els.app.style.setProperty("--right-pane", `${layout.rightCollapsed ? 0 : layout.right}px`);
629 els.app.dataset.leftCollapsed = String(layout.leftCollapsed);
630 els.app.dataset.rightCollapsed = String(layout.rightCollapsed);
631 els.toggleLeft.textContent = layout.leftCollapsed ? "›" : "‹";
632 els.toggleRight.textContent = layout.rightCollapsed ? "‹" : "›";
633 els.toggleLeft.setAttribute("aria-label", layout.leftCollapsed ? "Expand file tree" : "Collapse file tree");
634 els.toggleRight.setAttribute("aria-label", layout.rightCollapsed ? "Expand review panel" : "Collapse review panel");
635}
637function clampPane(side: PaneSide, value: unknown) {
638 const limits = PANE_LIMITS[side];
639 const width = typeof value === "number" && Number.isFinite(value) ? value : limits.fallback;
640 return Math.min(limits.max, Math.max(limits.min, Math.round(width)));
641}
222643async function addFinding() {
223644 const draft = draftFromSelection();
224645 if (!draft) return;
227648 await api(ROUTES.validateFinding, postJson(draft));
228649 findings.push(draft);
229650 clearFindingForm();
651 clearSelection(true);
230652 renderFindings();
231653 renderAnnotations();
232654 setStatus("Finding added");
233655 } catch (err) {
234656 setStatus(errorMessage(err), "error");
235657 } finally {
236 els.add.disabled = false;
658 els.add.disabled = !selected;
237659 }
286708 els.comment.value = "";
711function clearSelection(clearViews: boolean) {
712 selected = undefined;
713 els.add.disabled = true;
714 els.selection.className = "selection-empty";
715 els.selection.textContent = "Click an added or deleted line.";
716 hideFindingForm();
717 if (clearViews) for (const view of diffViews.values()) view.setSelectedLines(null);
718}
289720function renderFindings() {
290721 els.findings.replaceChildren();
291722 els.findings.className = findings.length === 0 ? "empty-list" : "";
301732function findingItem(finding: FindingDraft, index: number) {
302733 const item = document.createElement("div");
303 item.className = "finding-item";
734 item.className = `finding-item severity-${finding.severity}`;
735 item.tabIndex = 0;
736 item.addEventListener("click", () => selectFile(finding.file, true));
737 item.addEventListener("keydown", (event) => {
738 if (event.key === "Enter") selectFile(finding.file, true);
739 });
305 const text = document.createElement("div");
306 text.textContent = `${index + 1}. [${finding.severity}][${finding.category}] ${selectionLabel(finding)} — ${finding.comment}`;
741 const head = document.createElement("div");
742 head.className = "finding-item-head";
744 const number = document.createElement("span");
745 number.className = "finding-number";
746 number.textContent = String(index + 1);
748 const severity = document.createElement("span");
749 severity.className = `finding-pill ${finding.severity}`;
750 severity.textContent = finding.severity;
752 const category = document.createElement("span");
753 category.className = "finding-pill category";
754 category.textContent = finding.category;
308756 const remove = document.createElement("button");
309757 remove.className = "remove-finding";
310758 remove.type = "button";
311 remove.textContent = "Remove";
312 remove.addEventListener("click", () => removeFinding(index));
759 remove.textContent = "×";
760 remove.title = "Remove finding";
761 remove.addEventListener("click", (event) => {
762 event.stopPropagation();
763 removeFinding(index);
764 });
314 item.append(text, remove);
766 const location = document.createElement("div");
767 location.className = "finding-location";
768 location.textContent = selectionLabel(finding);
770 const text = document.createElement("div");
771 text.className = "finding-comment";
772 text.textContent = finding.comment;
774 head.append(number, severity, category, remove);
775 item.append(head, location, text);
315776 return item;
324785function updateFindingCount() {
325786 els.findingCount.textContent = `${findings.length} finding${findings.length === 1 ? "" : "s"}`;
787 els.drawerCount.textContent = String(findings.length);
328790function renderAnnotations() {
329 for (const [file, view] of diffViews) view.setLineAnnotations(annotationsFor(file));
791 for (const [file, view] of diffViews) {
792 view.setLineAnnotations(annotationsFor(file));
793 view.rerender();
794 }
795}
797async function buildSearchIndex(fileDiffs: FileDiffMetadata[], generation: number) {
798 searchIndexing = true;
799 searchIndex = [];
800 const restoreStatus = els.status.textContent === "Ready" ? "Ready" : undefined;
801 const entries: SearchEntry[] = [];
802 for (let index = 0; index < fileDiffs.length; index++) {
803 if (generation !== renderGeneration) { searchIndexing = false; return; }
804 entries.push(...searchEntriesForFile(fileDiffs[index]));
805 if (fileDiffs.length > 1) setStatus(`Indexing search ${index + 1}/${fileDiffs.length} files…`);
806 await yieldToBrowser();
807 }
808 if (generation !== renderGeneration) { searchIndexing = false; return; }
809 searchIndex = entries;
810 searchIndexing = false;
811 if (els.search.value.trim()) runSearch();
812 if (restoreStatus && els.status.textContent.startsWith("Indexing search")) setStatus(restoreStatus);
813}
815function searchEntriesForFile(fileDiff: FileDiffMetadata): SearchEntry[] {
816 const entries: SearchEntry[] = [];
817 for (const hunk of fileDiff.hunks) {
818 let additionLine = hunk.additionStart;
819 let deletionLine = hunk.deletionStart;
820 for (const content of hunk.hunkContent) {
821 if (content.type === "context") {
822 for (let i = 0; i < content.lines; i++) {
823 const text = fileDiff.additionLines[content.additionLineIndex + i];
824 if (text !== undefined) entries.push({ file: fileDiff.name, side: "additions", line: additionLine + i, text });
825 }
826 additionLine += content.lines;
827 deletionLine += content.lines;
828 } else {
829 for (let i = 0; i < content.deletions; i++) {
830 const text = fileDiff.deletionLines[content.deletionLineIndex + i];
831 if (text !== undefined) entries.push({ file: fileDiff.name, side: "deletions", line: deletionLine + i, text });
832 }
833 for (let i = 0; i < content.additions; i++) {
834 const text = fileDiff.additionLines[content.additionLineIndex + i];
835 if (text !== undefined) entries.push({ file: fileDiff.name, side: "additions", line: additionLine + i, text });
836 }
837 deletionLine += content.deletions;
838 additionLine += content.additions;
839 }
840 }
841 }
842 return entries;
843}
845function runSearch() {
846 const query = els.search.value.trim();
847 if (!query) { searchResults = []; searchActiveIndex = -1; hideSearch(); return; }
848 if (searchIndexing) {
849 els.searchResults.hidden = false;
850 els.searchResults.replaceChildren();
851 const empty = document.createElement("div");
852 empty.className = "search-empty";
853 empty.textContent = "Indexing search…";
854 els.searchResults.appendChild(empty);
855 return;
856 }
857 searchResults = searchCode(query);
858 searchActiveIndex = -1;
859 if (searchResults.length === 0) {
860 els.searchResults.hidden = false;
861 els.searchResults.replaceChildren();
862 const empty = document.createElement("div");
863 empty.className = "search-empty";
864 empty.textContent = "No matches.";
865 els.searchResults.appendChild(empty);
866 updateSearchBadge();
867 return;
868 }
869 renderSearchResults();
870 updateSearchBadge();
871}
873function renderSearchResults() {
874 els.searchResults.hidden = false;
875 els.searchResults.replaceChildren();
876 const max = Math.min(searchResults.length, 200);
877 for (let i = 0; i < max; i++) els.searchResults.appendChild(searchResultItem(searchResults[i], i));
878 if (searchResults.length > max) {
879 const more = document.createElement("div");
880 more.className = "search-more";
881 more.textContent = `${searchResults.length - max} more matches`;
882 els.searchResults.appendChild(more);
883 }
884}
886function navigateSearch(delta: 1 | -1) {
887 if (searchResults.length === 0) return;
888 searchActiveIndex = searchActiveIndex < 0 ? 0 : Math.max(0, Math.min(searchResults.length - 1, searchActiveIndex + delta));
889 const items = els.searchResults.querySelectorAll<HTMLElement>(".search-result");
890 items.forEach((el, i) => el.classList.toggle("search-result-active", i === searchActiveIndex));
891 const active = items[searchActiveIndex];
892 active?.scrollIntoView({ block: "nearest" });
893 jumpToMatch(searchResults[searchActiveIndex], searchActiveIndex);
894 updateSearchBadge();
895}
897function updateSearchBadge() {
898 const badge = document.querySelector<HTMLElement>("#search-badge");
899 if (!badge) return;
900 if (searchResults.length === 0) { badge.hidden = true; return; }
901 badge.hidden = false;
902 badge.textContent = searchActiveIndex >= 0 ? `${searchActiveIndex + 1}/${searchResults.length}` : `${searchResults.length}`;
903}
905function searchCode(query: string): SearchMatch[] {
906 const hits: SearchMatch[] = [];
907 const isRegex = query.startsWith("/") && query.endsWith("/");
908 const pattern = isRegex ? query.slice(1, -1) : query.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
909 let re: RegExp;
910 try { re = new RegExp(pattern, "i"); } catch { return hits; }
911 for (const entry of searchIndex) {
912 const m = re.exec(entry.text);
913 if (m && m.index >= 0) {
914 hits.push({ ...entry, matchStart: m.index, matchEnd: m.index + m[0].length });
915 if (hits.length >= 500) break;
916 }
917 }
918 return hits;
919}
921function searchResultItem(match: SearchMatch, index: number) {
922 const item = document.createElement("div");
923 item.className = "search-result";
924 item.tabIndex = -1;
925 item.addEventListener("click", () => {
926 searchActiveIndex = index;
927 jumpToMatch(match, index);
928 renderSearchResults();
929 updateSearchBadge();
930 });
932 const file = document.createElement("span");
933 file.className = "search-result-file";
934 file.textContent = match.file;
936 const loc = document.createElement("span");
937 loc.className = "search-result-loc";
938 loc.textContent = `:${match.line} ${match.side === "additions" ? "+" : "-"}`;
940 const preview = document.createElement("div");
941 preview.className = "search-result-preview";
942 const before = match.text.slice(Math.max(0, match.matchStart - 20), match.matchStart);
943 const matched = match.text.slice(match.matchStart, match.matchEnd);
944 const after = match.text.slice(match.matchEnd, match.matchEnd + 40);
945 preview.textContent = before;
946 const mark = document.createElement("mark");
947 mark.textContent = matched;
948 preview.appendChild(mark);
949 preview.append(after);
951 item.append(file, loc, preview);
952 return item;
953}
955function jumpToMatch(match: SearchMatch, index: number) {
956 selectFile(match.file, false);
957 requestAnimationFrame(() => {
958 const section = document.querySelector<HTMLElement>(`[data-file-section="${cssEscape(match.file)}"]`);
959 const container = section?.querySelector("diffs-container") as HTMLElement | null;
960 const root = container?.shadowRoot;
961 const sideRoot = root?.querySelector<HTMLElement>(match.side === "additions" ? "[data-additions]" : "[data-deletions]");
962 const line = sideRoot?.querySelector<HTMLElement>(`[data-line="${match.line}"]`);
963 if (line) {
964 const lineIndex = line.getAttribute("data-line-index");
965 const gutter = lineIndex
966 ? sideRoot?.querySelector<HTMLElement>(`[data-column-number][data-line-index="${cssEscape(lineIndex)}"]`)
967 : sideRoot?.querySelector<HTMLElement>(`[data-column-number="${match.line}"]`);
968 scrollDiffLineIntoView(line);
969 flashSearchHighlight([line, gutter]);
970 }
971 });
972}
974function scrollDiffLineIntoView(line: HTMLElement) {
975 const scroller = els.diffs;
976 const lineRect = line.getBoundingClientRect();
977 const scrollerRect = scroller.getBoundingClientRect();
978 const nextTop = scroller.scrollTop + lineRect.top - scrollerRect.top - (scrollerRect.height / 2) + (lineRect.height / 2);
979 scroller.scrollTo({ top: Math.max(0, nextTop), behavior: "smooth" });
980}
982function flashSearchHighlight(elements: Array<HTMLElement | undefined | null>) {
983 const targets = elements.filter((element): element is HTMLElement => Boolean(element));
984 for (const target of targets) target.classList.remove("search-highlight");
985 if (targets[0]) void targets[0].offsetWidth;
986 for (const target of targets) target.classList.add("search-highlight");
987}
989function isEscapeKey(event: KeyboardEvent) {
990 return event.key === "Escape" || event.key === "Esc";
991}
993function cancelPendingSearch() {
994 window.clearTimeout(searchDebounce);
995 searchDebounce = undefined;
996}
998function closeCodeSearchPopup() {
999 cancelPendingSearch();
1000 searchActiveIndex = -1;
1001 hideSearch();
1004function clearCodeSearch(refocus: boolean) {
1005 cancelPendingSearch();
1006 els.search.value = "";
1007 searchResults = [];
1008 searchActiveIndex = -1;
1009 hideSearch();
1010 updateSearchBadge();
1011 if (refocus) els.search.focus();
1014function hideSearch() {
1015 els.searchResults.hidden = true;
1016 updateSearchBadge();
3321019function annotationsFor(file: string): DiffLineAnnotation<FindingMeta>[] {
3711058 const review = await api<ReviewPayload>(ROUTES.review);
3721059 const nextHash = hashReview(review);
3731060 if (nextHash === reviewHash) return;
374 renderReview(review);
1061 await renderReview(review);
3751062 setStatus("Diff updated", "ok");
3761063 } catch (err) {
377 setStatus(errorMessage(err), "error");
1064 setDisconnectedStatus(err);
4111098 els.status.className = tone === "neutral" ? "" : tone;
1101function setDisconnectedStatus(err: unknown) {
1102 const message = errorMessage(err);
1103 const disconnected = /networkerror|failed to fetch|load failed|fetch resource/i.test(message);
1104 setStatus(disconnected ? "Disconnected. Run /diff-review, then refresh." : message, "error");
4141107function readThemeMode(): ThemeMode {
4151108 return themeModeFromValue(localStorage.getItem(THEME_STORAGE_KEY));
4181111function applyThemeMode(mode: ThemeMode) {
4191112 document.documentElement.dataset.theme = mode === "system" ? (systemTheme.matches ? "light" : "dark") : mode;
4201113 document.documentElement.dataset.themeMode = mode;
1114 const icon = document.querySelector<HTMLElement>(".theme-icon");
1115 if (icon) icon.textContent = mode === "dark" ? "☾" : mode === "light" ? "☼" : "◐";
1118function selectFile(path: string | undefined, scroll: boolean) {
1119 selectedFile = path;
1120 applySelectedFileEmphasis();
1121 if (scroll) scrollToFile(path);
1124function applySelectedFileEmphasis() {
1125 for (const section of els.diffs.querySelectorAll<HTMLElement>("[data-file-section]")) {
1126 const active = section.dataset.fileSection === selectedFile;
1127 if (active) section.dataset.selectedFile = "true";
1128 else delete section.dataset.selectedFile;
1129 }
4231132function scrollToFile(path: string | undefined) {
4241133 if (!path) return;
425 document.querySelector<HTMLElement>(`[data-file-section="${cssEscape(path)}"]`)?.scrollIntoView({ block: "start" });
1134 const section = document.querySelector<HTMLElement>(`[data-file-section="${cssEscape(path)}"]`);
1135 if (!section) return;
1136 const scroller = els.diffs;
1137 const top = section.getBoundingClientRect().top - scroller.getBoundingClientRect().top + scroller.scrollTop;
1138 scroller.scrollTo({ top: Math.max(0, top - 2), behavior: "smooth" });
4281141function toGitStatus(status: ReviewPayload["files"][number]["status"]): GitStatusEntry["status"] {

pi/agent/extensions/diff-review/browser/shadow-css.ts

Added
new file mode 100644

+179 / −0 text lines

1import { CODE_FONT, NUGU_DARK, NUGU_LIGHT } from "./theme.js";
2
3export const DIFF_FONT_CSS = `
4 :host {
5 --diffs-font-family: ${CODE_FONT};
6 --diffs-header-font-family: Inter, ui-sans-serif, system-ui, sans-serif;
7 --diffs-light: ${NUGU_LIGHT.fg};
8 --diffs-dark: ${NUGU_DARK.fg};
9 --diffs-light-bg: ${NUGU_LIGHT.bg};
10 --diffs-dark-bg: ${NUGU_DARK.bg};
11 --diffs-light-addition-color: ${NUGU_LIGHT.info};
12 --diffs-dark-addition-color: ${NUGU_DARK.info};
13 --diffs-light-deletion-color: ${NUGU_LIGHT.error};
14 --diffs-dark-deletion-color: ${NUGU_DARK.error};
15 --diffs-light-modified-color: ${NUGU_LIGHT.accent};
16 --diffs-dark-modified-color: ${NUGU_DARK.accent};
17 --diffs-bg-context-override: light-dark(color-mix(in srgb, ${NUGU_LIGHT.bg} 88%, white), color-mix(in srgb, ${NUGU_DARK.bg} 82%, ${NUGU_DARK.panel}));
18 --diffs-bg-context-gutter-override: light-dark(color-mix(in srgb, ${NUGU_LIGHT.panel} 80%, white), color-mix(in srgb, ${NUGU_DARK.panel} 80%, ${NUGU_DARK.bg}));
19 --diffs-bg-separator-override: light-dark(${NUGU_LIGHT.panel}, ${NUGU_DARK.panel});
20 --diffs-fg-number-override: light-dark(${NUGU_LIGHT.muted}, ${NUGU_DARK.muted});
21 --diffs-foreground: light-dark(${NUGU_LIGHT.fg}, ${NUGU_DARK.fg});
22 --diffs-background: light-dark(${NUGU_LIGHT.bg}, ${NUGU_DARK.bg});
23 --diffs-token-string: light-dark(${NUGU_LIGHT.focus}, ${NUGU_DARK.focus});
24 --diffs-token-string-expression: light-dark(${NUGU_LIGHT.focus}, ${NUGU_DARK.focus});
25 --diffs-token-comment: light-dark(${NUGU_LIGHT.important}, ${NUGU_DARK.important});
26 --diffs-token-constant: light-dark(${NUGU_LIGHT.focus}, ${NUGU_DARK.focus});
27 --diffs-token-keyword: light-dark(${NUGU_LIGHT.muted}, ${NUGU_DARK.muted});
28 --diffs-token-parameter: light-dark(${NUGU_LIGHT.warning}, ${NUGU_DARK.warning});
29 --diffs-token-function: light-dark(${NUGU_LIGHT.fg}, ${NUGU_DARK.fg});
30 --diffs-token-punctuation: light-dark(${NUGU_LIGHT.muted}, ${NUGU_DARK.muted});
31 --diffs-token-link: light-dark(${NUGU_LIGHT.info}, ${NUGU_DARK.info});
32 --diffs-token-inserted: light-dark(${NUGU_LIGHT.info}, ${NUGU_DARK.info});
33 --diffs-token-deleted: light-dark(${NUGU_LIGHT.error}, ${NUGU_DARK.error});
34 --diffs-token-changed: light-dark(${NUGU_LIGHT.accent}, ${NUGU_DARK.accent});
35 }
36 pre, code, [data-line], [data-code], [data-content], [data-line-number] {
37 font-family: ${CODE_FONT} !important;
38 font-size: 12px;
39 line-height: 1.55;
40 }
41 @keyframes diff-review-search-highlight {
42 0%, 72% {
43 background-color: #c026d3;
44 color: #fff;
45 box-shadow: inset 0 0 0 2px #f0abfc, 0 0 0 2px #c026d3;
46 outline-color: #f0abfc;
47 }
48 100% {
49 background-color: transparent;
50 box-shadow: none;
51 outline-color: transparent;
52 }
53 }
54 [data-line].search-highlight,
55 [data-column-number].search-highlight {
56 animation: diff-review-search-highlight 2.4s ease-out;
57 outline: 2px solid transparent;
58 outline-offset: -2px;
59 }
60 [data-line].search-highlight *,
61 [data-column-number].search-highlight * {
62 color: inherit !important;
63 }
64`;
66export const TREE_CSS = `
67 :host {
68 --trees-fg-override: var(--fg);
69 --trees-fg-muted-override: var(--muted);
70 --trees-bg-override: transparent;
71 --trees-bg-muted-override: color-mix(in srgb, var(--focus) 14%, transparent);
72 --trees-input-bg-override: color-mix(in srgb, var(--bg) 74%, var(--panel-2));
73 --trees-search-bg-override: color-mix(in srgb, var(--bg) 74%, var(--panel-2));
74 --trees-search-fg-override: var(--fg);
75 --trees-search-font-weight-override: 500;
76 --trees-density-override: .82;
77 --trees-font-size-override: 12px;
78 --trees-level-gap-override: 5px;
79 --trees-item-padding-x-override: 4px;
80 --trees-item-margin-x-override: 1px;
81 --trees-item-row-gap-override: 3px;
82 --trees-icon-width-override: 13px;
83 --trees-git-lane-width-override: 8px;
84 --trees-action-lane-width-override: 8px;
85 --trees-padding-inline-override: 4px;
86 --trees-accent-override: var(--accent);
87 --trees-selected-bg-override: color-mix(in srgb, var(--accent) 18%, transparent);
88 --trees-selected-fg-override: var(--fg);
89 --trees-focus-ring-color-override: var(--focus);
90 --trees-border-color-override: var(--border);
91 --trees-status-added-override: var(--nugu-info);
92 --trees-status-modified-override: var(--nugu-warning);
93 --trees-status-renamed-override: var(--nugu-content-important-local);
94 --trees-status-deleted-override: var(--nugu-error);
95 --trees-git-added-color-override: var(--nugu-info);
96 --trees-git-modified-color-override: var(--nugu-warning);
97 --trees-git-renamed-color-override: var(--nugu-content-important-local);
98 --trees-git-deleted-color-override: var(--nugu-error);
99 --trees-font-family-override: ${CODE_FONT};
100 }
101 [data-file-tree-virtualized-scroll='true'] {
102 overflow-x: auto;
103 }
104 [data-item-git-status='renamed'] [data-item-section='decoration'] {
105 color: var(--trees-git-renamed-color);
106 font-size: 10px;
107 letter-spacing: .04em;
108 text-transform: uppercase;
109 }
110 [data-item-git-status='ignored'] {
111 opacity: .58;
112 cursor: not-allowed;
113 }
114 [data-item-git-status='ignored'] [data-item-section='content'] {
115 color: var(--trees-fg-muted);
116 text-decoration: line-through;
117 text-decoration-thickness: 1px;
118 }
119 [data-item-git-status='ignored'] [data-item-section='decoration'] {
120 color: var(--trees-fg-muted);
121 font-size: 10px;
122 letter-spacing: .04em;
123 text-transform: uppercase;
124 }
125 [data-file-tree-search-container] {
126 position: relative;
127 display: block !important;
128 padding-inline: var(--trees-padding-inline) !important;
129 }
130 [data-file-tree-search-input] {
131 box-sizing: border-box !important;
132 width: 100% !important;
133 height: 30px !important;
134 min-height: 30px !important;
135 max-height: 30px !important;
136 margin: 0 !important;
137 appearance: none !important;
138 background: color-mix(in srgb, var(--bg) 60%, var(--panel-2)) !important;
139 color: var(--trees-search-fg) !important;
140 caret-color: var(--trees-accent) !important;
141 border-color: color-mix(in srgb, var(--trees-border-color) 70%, transparent) !important;
142 border-radius: 999px !important;
143 box-shadow: inset 0 1px 0 color-mix(in srgb, var(--fg) 7%, transparent) !important;
144 padding: 6px 30px 6px 11px !important;
145 font-size: 12px !important;
146 line-height: 18px !important;
147 font-family: ${CODE_FONT} !important;
148 }
149 [data-file-tree-search-input]:focus,
150 [data-file-tree-search-input-fake-focus='true'] {
151 border-color: var(--trees-focus-ring-color) !important;
152 box-shadow: 0 0 0 3px color-mix(in srgb, var(--trees-focus-ring-color) 22%, transparent) !important;
153 outline: none !important;
154 }
155 .tree-search-clear {
156 position: absolute;
157 right: calc(var(--trees-padding-inline) + 9px);
158 top: 15px;
159 transform: translateY(-50%);
160 display: grid;
161 place-items: center;
162 width: 18px;
163 height: 18px;
164 padding: 0;
165 border: 0;
166 border-radius: 999px;
167 background: color-mix(in srgb, var(--trees-fg-muted) 20%, transparent);
168 color: var(--trees-fg-muted);
169 font: 800 14px/1 system-ui, sans-serif;
170 cursor: pointer;
171 }
172 [data-file-tree-search-input]:placeholder-shown + .tree-search-clear {
173 display: none;
174 }
175 .tree-search-clear:hover {
176 background: color-mix(in srgb, var(--trees-accent) 24%, transparent);
177 color: var(--trees-fg);
178 }
179`;

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

Modified

+563 / −27 text lines

11@font-face {
2 font-family: "Nugu Code Nerd";
2 font-family: "JetBrains Mono Nerd";
33 src: url("./assets/JetBrainsMonoNuguCode.woff2") format("woff2");
44 font-weight: 400;
55 font-style: normal;
8888 background: radial-gradient(circle at top left, color-mix(in srgb, var(--accent) 12%, transparent), transparent 28rem), var(--bg);
9090button, select, textarea { font: inherit; }
91code, pre { font-family: "JetBrains Mono Nerd", "JetBrains Mono", "Fira Code", ui-monospace, SFMono-Regular, Menlo, Consolas, monospace; }
9192button { cursor: pointer; }
9293button:disabled { cursor: not-allowed; opacity: .48; }
9495#app {
96 --left-pane: 288px;
97 --right-pane: 382px;
9598 display: grid;
96 grid-template-columns: 288px minmax(0, 1fr) 382px;
99 grid-template-columns: var(--left-pane) 8px minmax(0, 1fr) 8px var(--right-pane);
97100 height: 100vh;
98101 overflow: hidden;
103#app[data-left-collapsed="true"] { --left-pane: 0px; }
104#app[data-right-collapsed="true"] { --right-pane: 0px; }
105#app[data-resizing="true"] { cursor: col-resize; user-select: none; }
106#app[data-left-collapsed="true"] #sidebar,
107#app[data-right-collapsed="true"] #drawer { padding-inline: 0; border: 0; }
101109#sidebar, #drawer, #main {
102110 min-height: 0;
111119#sidebar { border-inline-end: 1px solid var(--border); }
112120#drawer { border-inline-start: 1px solid var(--border); overflow-y: auto; contain: layout paint; }
113#main { display: grid; grid-template-rows: auto minmax(0, 1fr); overflow: hidden; }
121#main { position: relative; display: grid; grid-template-rows: auto minmax(0, 1fr); overflow: hidden; }
122.splitter {
123 position: relative;
124 z-index: 4;
125 display: flex;
126 align-items: center;
127 justify-content: center;
128 background: color-mix(in srgb, var(--panel) 72%, transparent);
129 cursor: col-resize;
130 border-inline: 1px solid color-mix(in srgb, var(--border) 70%, transparent);
131}
132.splitter::before {
133 content: "";
134 width: 2px;
135 height: 42px;
136 border-radius: 999px;
137 background: color-mix(in srgb, var(--muted) 42%, transparent);
138}
139.splitter:hover,
140#app[data-resizing="true"] .splitter {
141 background: color-mix(in srgb, var(--focus) 16%, var(--panel));
142}
143.pane-toggle {
144 position: absolute;
145 top: 12px;
146 width: 24px;
147 height: 24px;
148 padding: 0;
149 border-radius: 999px;
150 border: 1px solid var(--border);
151 background: color-mix(in srgb, var(--panel-2) 92%, var(--bg));
152 color: var(--fg);
153 font-weight: 900;
154 line-height: 1;
155}
156#left-splitter .pane-toggle { left: -12px; }
157#right-splitter .pane-toggle { right: -12px; }
158#app[data-left-collapsed="true"] #toggle-left,
159#app[data-right-collapsed="true"] #toggle-right {
160 width: 32px;
161 height: 32px;
162 color: var(--fg);
163 background: linear-gradient(180deg, color-mix(in srgb, var(--accent) 38%, var(--panel-2)), color-mix(in srgb, var(--accent) 20%, var(--panel-2)));
164 border-color: color-mix(in srgb, var(--accent) 58%, var(--border));
165 box-shadow: 0 8px 26px color-mix(in srgb, #000 32%, transparent), 0 0 0 3px color-mix(in srgb, var(--accent) 16%, transparent);
166}
167#app[data-left-collapsed="true"] #toggle-left { left: 50%; transform: translateX(-50%); }
168#app[data-right-collapsed="true"] #toggle-right { right: 50%; transform: translateX(50%); }
115170#topbar {
116171 display: flex;
121176 border-bottom: 1px solid var(--border);
122177 background: color-mix(in srgb, var(--bg) 92%, var(--panel));
124#diffs { overflow: auto; padding: 16px 14px 40px; }
179.topbar-actions {
180 display: flex;
181 align-items: center;
182 gap: 10px;
183 flex-shrink: 0;
184}
185.search-wrap {
186 position: relative;
187}
188.search-wrap input {
189 width: 200px;
190 padding: 6px 58px 6px 11px;
191 border: 1px solid color-mix(in srgb, var(--border) 70%, transparent);
192 border-radius: 999px;
193 background: color-mix(in srgb, var(--bg) 60%, var(--panel-2));
194 color: var(--fg);
195 font-size: 12px;
196 outline: none;
197 box-shadow: inset 0 1px 0 color-mix(in srgb, var(--fg) 7%, transparent);
198 transition: width 160ms ease, border-color 160ms ease, box-shadow 160ms ease;
199}
200.search-clear {
201 position: absolute;
202 right: 9px;
203 top: 50%;
204 transform: translateY(-50%);
205 display: grid;
206 place-items: center;
207 width: 18px;
208 height: 18px;
209 padding: 0;
210 border: 0;
211 border-radius: 999px;
212 background: color-mix(in srgb, var(--muted) 20%, transparent);
213 color: var(--muted);
214 font: 800 14px/1 system-ui, sans-serif;
215}
216.search-clear:hover {
217 background: color-mix(in srgb, var(--accent) 24%, transparent);
218 color: var(--fg);
219}
220.search-wrap input:placeholder-shown + .search-clear { display: none; }
221.search-badge {
222 position: absolute;
223 right: 34px;
224 top: 50%;
225 transform: translateY(-50%);
226 padding: 1px 6px;
227 border-radius: 999px;
228 background: color-mix(in srgb, var(--accent) 22%, transparent);
229 color: var(--muted);
230 font-size: 11px;
231 font-weight: 700;
232 pointer-events: none;
233}
234.search-wrap input:focus {
235 border-color: var(--focus);
236 box-shadow: 0 0 0 3px color-mix(in srgb, var(--focus) 22%, transparent);
237 width: 280px;
238}
239.search-wrap input::placeholder { color: var(--muted); }
240.search-results {
241 position: absolute;
242 top: calc(100% + 6px);
243 right: 0;
244 width: min(460px, 60vw);
245 max-height: 60vh;
246 overflow-y: auto;
247 border: 1px solid var(--border);
248 border-radius: 14px;
249 background: color-mix(in srgb, var(--panel-2) 96%, var(--bg));
250 box-shadow: var(--shadow);
251 backdrop-filter: blur(14px);
252 z-index: 40;
253 padding: 6px;
254}
255.search-result {
256 padding: 8px 10px;
257 border-radius: 10px;
258 cursor: pointer;
259 font-size: 12px;
260 line-height: 1.4;
261}
262.search-result:hover,
263.search-result:focus-visible {
264 background: color-mix(in srgb, var(--focus) 14%, transparent);
265 outline: none;
266}
267.search-result-active {
268 background: color-mix(in srgb, var(--accent) 22%, transparent) !important;
269 border-left: 3px solid var(--accent);
270 padding-left: 7px;
271}
272.search-result-file {
273 color: var(--fg);
274 font-family: "JetBrains Mono Nerd", "JetBrains Mono", ui-monospace, monospace;
275 font-weight: 750;
276 font-size: 11px;
277}
278.search-result-loc {
279 color: var(--muted);
280 font-family: "JetBrains Mono Nerd", "JetBrains Mono", ui-monospace, monospace;
281 font-size: 11px;
282 margin-left: 4px;
283}
284.search-result-preview {
285 color: var(--fg-soft);
286 font-family: "JetBrains Mono Nerd", "JetBrains Mono", ui-monospace, monospace;
287 font-size: 11px;
288 overflow: hidden;
289 text-overflow: ellipsis;
290 white-space: nowrap;
291 margin-top: 2px;
292}
293.search-result-preview mark {
294 color: #fff;
295 background: #c026d3;
296 border-radius: 3px;
297 padding: 1px 3px;
298 font-weight: 700;
299}
300:root[data-theme="light"] .search-result-preview mark {
301 color: #fff;
302 background: #a21caf;
303}
304.search-result-active .search-result-preview mark {
305 background: #e879f9;
306 color: #1e1e2e;
307}
308.search-empty {
309 padding: 14px;
310 color: var(--muted);
311 font-size: 13px;
312 text-align: center;
313}
314.search-more {
315 padding: 8px 10px;
316 color: var(--muted);
317 font-size: 11px;
318 text-align: center;
319}
320#diffs {
321 overflow: auto;
322 padding: 16px 14px 72vh;
323 scroll-padding-top: 16px;
324}
126326.brand { display: grid; grid-template-columns: 1fr auto; gap: 10px; align-items: start; margin-bottom: 14px; }
127327h1 { 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; }
328.subtitle {
329 display: inline-flex;
330 align-items: center;
331 width: fit-content;
332 margin-top: 7px;
333 padding: 3px 8px;
334 border: 1px solid color-mix(in srgb, var(--accent) 24%, transparent);
335 border-radius: 999px;
336 background: linear-gradient(135deg, color-mix(in srgb, var(--accent) 14%, transparent), color-mix(in srgb, var(--accent-2) 10%, transparent));
337 color: color-mix(in srgb, var(--fg-soft) 72%, var(--muted));
338 font-size: 12px;
339 font-weight: 700;
340 letter-spacing: .01em;
341}
342.topbar-title { margin: 0 0 5px; font-size: 16px; font-weight: 800; color: var(--nugu-content-important-global); }
343#summary {
344 display: flex;
345 flex-wrap: wrap;
346 align-items: center;
347 gap: 6px 8px;
348 color: var(--muted);
349 font-size: 12px;
350 line-height: 1.35;
351}
352.summary-stats,
353.summary-skipped {
354 display: inline-flex;
355 align-items: center;
356 border-radius: 999px;
357 border: 1px solid var(--border);
358 padding: 2px 7px;
359 background: color-mix(in srgb, var(--panel-2) 54%, transparent);
360 font-weight: 700;
361}
362.summary-stats { color: color-mix(in srgb, var(--fg-soft) 78%, var(--muted)); }
363.summary-skipped {
364 color: color-mix(in srgb, var(--nugu-warning) 72%, var(--fg-soft));
365 border-color: color-mix(in srgb, var(--nugu-warning) 28%, var(--border));
366 background: color-mix(in srgb, var(--nugu-warning) 10%, transparent);
367}
368.summary-hint {
369 color: var(--faint);
370 font-weight: 500;
371}
131372.card-title, .file-title { color: var(--nugu-content-important-global); font-weight: 800; }
132373.card-title { font-size: 15px; margin-bottom: 8px; }
133#meta, #status, #selection { color: var(--muted); font-size: 14px; line-height: 1.5; }
134#meta { margin-bottom: 8px; }
374.findings-title { display: flex; align-items: center; justify-content: space-between; gap: 10px; }
375#drawer-count {
376 min-width: 24px;
377 padding: 2px 8px;
378 border-radius: 999px;
379 border: 1px solid color-mix(in srgb, var(--accent) 35%, var(--border));
380 background: color-mix(in srgb, var(--accent) 16%, transparent);
381 color: var(--nugu-content-important-global);
382 text-align: center;
383 font-size: 12px;
384}
385#selection { color: var(--muted); font-size: 14px; line-height: 1.5; }
386#meta {
387 display: flex;
388 flex-wrap: wrap;
389 align-items: center;
390 gap: 5px;
391 margin: 10px 0 10px;
392}
393.meta-chip {
394 display: inline-flex;
395 align-items: center;
396 gap: 5px;
397 min-width: 0;
398 padding: 3px 7px;
399 border: 1px solid color-mix(in srgb, var(--border) 78%, transparent);
400 border-radius: 999px;
401 background: color-mix(in srgb, var(--bg) 48%, var(--panel-2));
402 color: var(--muted);
403 font-size: 11px;
404 line-height: 1.2;
405 white-space: nowrap;
406}
407.meta-label {
408 color: var(--faint);
409 font-weight: 600;
410 text-transform: uppercase;
411 letter-spacing: .04em;
412}
413.meta-value {
414 color: color-mix(in srgb, var(--fg-soft) 76%, var(--muted));
415 font-weight: 800;
416}
417.meta-round .meta-value { color: var(--accent); }
418#status {
419 position: fixed;
420 right: 16px;
421 bottom: 14px;
422 z-index: 20;
423 max-width: min(420px, calc(100vw - 32px));
424 padding: 9px 12px;
425 border: 1px solid color-mix(in srgb, var(--border) 78%, transparent);
426 border-radius: 999px;
427 background: color-mix(in srgb, var(--panel-2) 92%, var(--bg));
428 color: var(--fg-soft);
429 box-shadow: 0 10px 36px color-mix(in srgb, #000 28%, transparent), inset 0 1px 0 color-mix(in srgb, var(--fg) 8%, transparent);
430 font-size: 13px;
431 font-weight: 750;
432 line-height: 1.35;
433 white-space: nowrap;
434 overflow: hidden;
435 text-overflow: ellipsis;
436 pointer-events: none;
437}
438#status::before {
439 content: "";
440 display: inline-block;
441 width: 7px;
442 height: 7px;
443 margin-right: 8px;
444 border-radius: 999px;
445 background: var(--muted);
446 vertical-align: 1px;
447}
448#status.ok { color: var(--nugu-info); border-color: color-mix(in srgb, var(--nugu-info) 34%, var(--border)); }
449#status.ok::before { background: var(--nugu-info); box-shadow: 0 0 14px var(--nugu-info); }
450#status.error { color: var(--nugu-error); border-color: color-mix(in srgb, var(--nugu-error) 40%, var(--border)); }
451#status.error::before { background: var(--nugu-error); box-shadow: 0 0 14px var(--nugu-error); }
135452#tree { height: calc(100vh - 116px); border-radius: var(--radius); background: color-mix(in srgb, var(--bg) 65%, var(--panel)); overflow: hidden; }
136453.count-pill {
137454 padding: 6px 10px;
144461 white-space: nowrap;
464.inline-finding {
465 position: fixed;
466 z-index: 30;
467 width: min(380px, calc(100vw - 24px));
468 padding: 12px;
469 border: 1px solid color-mix(in srgb, var(--accent) 42%, var(--border));
470 border-radius: 14px;
471 background: color-mix(in srgb, var(--panel-2) 94%, var(--bg));
472 box-shadow: var(--shadow), 0 0 0 3px color-mix(in srgb, var(--accent) 12%, transparent), inset 0 1px 0 color-mix(in srgb, var(--fg) 8%, transparent);
473 backdrop-filter: blur(14px);
474}
475.inline-finding[hidden] { display: none; }
476.inline-finding::before {
477 content: "";
478 position: absolute;
479 left: -7px;
480 top: 24px;
481 width: 12px;
482 height: 12px;
483 transform: rotate(45deg);
484 border-left: 1px solid color-mix(in srgb, var(--accent) 42%, var(--border));
485 border-bottom: 1px solid color-mix(in srgb, var(--accent) 42%, var(--border));
486 background: inherit;
487}
488.inline-head { display: grid; grid-template-columns: 1fr auto; gap: 10px; align-items: start; }
489.inline-title { color: var(--nugu-content-important-global); font-weight: 850; }
490.inline-close {
491 width: 28px;
492 height: 28px;
493 padding: 0;
494 border-radius: 999px;
495 border: 1px solid var(--border);
496 background: color-mix(in srgb, var(--bg) 60%, var(--panel-2));
497 color: var(--fg);
498 font-size: 18px;
499 line-height: 1;
500}
501.inline-finding label { margin-block: 8px; }
502.inline-finding textarea { min-height: 96px; }
147504.card {
148505 padding: 12px;
149506 margin-bottom: 12px;
155512.selection-empty { color: var(--muted); }
156513.selection-active { color: var(--fg); font-weight: 800; }
157514.field-row { display: grid; grid-template-columns: 1fr 1fr; gap: 10px; }
158.theme-label { margin: 0; min-width: 102px; }
159.theme-label select { padding: 7px 28px 7px 8px; font-size: 14px; }
515.field-subtitle { color: var(--muted); font-size: 12px; font-weight: 400; font-style: italic; line-height: 1.3; margin-top: -2px; }
516.theme-label {
517 position: relative;
518 display: inline-grid;
519 place-items: center;
520 width: 30px;
521 height: 30px;
522 min-width: 0;
523 margin: 0;
524 padding: 0;
525 border: 1px solid color-mix(in srgb, var(--border) 78%, transparent);
526 border-radius: 999px;
527 background: color-mix(in srgb, var(--panel-2) 56%, transparent);
528 box-shadow: inset 0 1px 0 color-mix(in srgb, var(--fg) 5%, transparent);
529 opacity: .72;
530}
531.theme-label:hover,
532.theme-label:focus-within { opacity: 1; }
533.theme-icon {
534 display: grid;
535 place-items: center;
536 width: 100%;
537 height: 100%;
538 color: color-mix(in srgb, var(--fg-soft) 70%, var(--muted));
539 font-size: 14px;
540 font-weight: 800;
541 line-height: 1;
542 pointer-events: none;
543}
544.theme-label select {
545 position: absolute;
546 inset: 0;
547 width: 100%;
548 height: 100%;
549 min-width: 0;
550 padding: 0;
551 border: 0;
552 border-radius: 999px;
553 background: transparent;
554 color: transparent;
555 opacity: 0;
556 cursor: pointer;
557}
558.theme-label:focus-within {
559 border-color: color-mix(in srgb, var(--focus) 52%, var(--border));
560 box-shadow: 0 0 0 3px color-mix(in srgb, var(--focus) 18%, transparent);
561}
562.theme-label select:focus { box-shadow: none; }
161564label { display: grid; gap: 6px; margin-block: 10px; font-size: 14px; color: var(--fg-soft); font-weight: 700; }
162565textarea, select {
173576 box-shadow: 0 0 0 3px color-mix(in srgb, var(--focus) 28%, transparent);
175578textarea { resize: vertical; min-height: 68px; }
579#notes {
580 min-height: 150px;
581 max-height: none;
582 overflow: hidden;
583 resize: none;
584 font-size: 15px;
585 line-height: 1.45;
586 padding: 12px;
587}
177589.actions { position: sticky; bottom: 0; display: grid; grid-template-columns: 1fr 1fr; gap: 8px; padding-top: 4px; background: linear-gradient(transparent, var(--panel) 20%); }
178590.actions button, #add, .remove-finding {
186598#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)); }
187599#add { width: 100%; margin-top: 2px; }
189.file-section { margin-bottom: 22px; scroll-margin-top: 16px; border-radius: var(--radius); }
601.file-section {
602 position: relative;
603 isolation: isolate;
604 content-visibility: auto;
605 contain-intrinsic-size: 260px;
606 margin-bottom: 22px;
607 scroll-margin-top: 16px;
608 border-radius: var(--radius);
609 transition: background-color 160ms ease, box-shadow 160ms ease, outline-color 160ms ease;
610}
611.file-section[data-selected-file="true"] {
612 background: linear-gradient(90deg, color-mix(in srgb, var(--accent) 10%, transparent), transparent 28rem);
613}
614.file-section[data-selected-file="true"]::before {
615 content: "";
616 position: absolute;
617 inset: 0 auto 0 -9px;
618 width: 4px;
619 border-radius: 999px;
620 background: linear-gradient(180deg, var(--accent), var(--accent-2));
621 box-shadow: 0 0 0 3px color-mix(in srgb, var(--accent) 14%, transparent), 0 0 24px color-mix(in srgb, var(--accent) 42%, transparent);
622 z-index: 1;
623 pointer-events: none;
624}
625.file-section[data-selected-file="true"] .file-title {
626 color: var(--fg);
627 background: linear-gradient(90deg, color-mix(in srgb, var(--accent) 18%, var(--bg)) 0%, color-mix(in srgb, var(--bg) 84%, transparent) 72%);
628 border: 1px solid color-mix(in srgb, var(--accent) 36%, var(--border));
629 border-left: 4px solid var(--accent);
630 box-shadow: 0 8px 28px color-mix(in srgb, var(--accent) 14%, transparent);
631}
632.file-section[data-selected-file="true"] .file-title::before {
633 content: "selected";
634 display: inline-flex;
635 align-items: center;
636 margin-right: 8px;
637 padding: 2px 7px;
638 border-radius: 999px;
639 background: color-mix(in srgb, var(--accent) 24%, transparent);
640 color: var(--fg);
641 font-size: 10px;
642 font-weight: 850;
643 letter-spacing: .05em;
644 text-transform: uppercase;
645}
190646.file-title {
191647 position: sticky;
192 top: -16px;
193 z-index: 2;
648 top: 0;
649 z-index: 5;
194650 margin: 0 0 8px;
195 padding: 8px 0;
651 padding: 8px 10px;
652 border: 1px solid color-mix(in srgb, var(--border) 72%, transparent);
653 border-left: 3px solid color-mix(in srgb, var(--muted) 34%, transparent);
654 border-radius: 10px;
196655 font-size: 14px;
197 background: linear-gradient(var(--bg), color-mix(in srgb, var(--bg) 78%, transparent));
656 background: linear-gradient(180deg, color-mix(in srgb, var(--bg) 94%, var(--panel)), color-mix(in srgb, var(--bg) 78%, transparent));
657 box-shadow: 0 1px 0 color-mix(in srgb, var(--fg) 4%, transparent);
658 transition: background-color 160ms ease, border-color 160ms ease, box-shadow 160ms ease, color 160ms ease;
199diffs-container { border-radius: var(--radius); overflow: hidden; box-shadow: 0 0 0 1px var(--border); }
660diffs-container { position: relative; z-index: 2; border-radius: var(--radius); overflow: hidden; box-shadow: 0 0 0 1px var(--border); }
200661.empty-list { color: var(--muted); font-size: 14px; }
201662.finding-item {
202663 display: grid;
203 gap: 6px;
664 gap: 8px;
204665 border: 1px solid var(--border);
205666 border-left: 3px solid var(--accent);
206 border-radius: 8px;
207 padding: 8px;
208 margin-block: 7px;
667 border-radius: 12px;
668 padding: 10px;
669 margin-block: 9px;
209670 font-size: 14px;
210 background: color-mix(in srgb, var(--panel-2) 72%, transparent);
671 background: linear-gradient(180deg, color-mix(in srgb, var(--panel-2) 78%, transparent), color-mix(in srgb, var(--panel-3) 62%, transparent));
672 box-shadow: inset 0 1px 0 color-mix(in srgb, var(--fg) 5%, transparent);
673 cursor: pointer;
675.finding-item:hover,
676.finding-item:focus-visible {
677 border-color: color-mix(in srgb, var(--focus) 42%, var(--border));
678 box-shadow: 0 0 0 3px color-mix(in srgb, var(--focus) 16%, transparent), inset 0 1px 0 color-mix(in srgb, var(--fg) 5%, transparent);
679 outline: none;
680}
681.finding-item.severity-high { border-left-color: var(--nugu-error); }
682.finding-item.severity-medium { border-left-color: var(--nugu-warning); }
683.finding-item.severity-low { border-left-color: var(--nugu-info); }
684.finding-item-head { display: flex; align-items: center; gap: 6px; }
685.finding-number {
686 display: inline-grid;
687 place-items: center;
688 width: 22px;
689 height: 22px;
690 border-radius: 999px;
691 background: color-mix(in srgb, var(--accent) 18%, transparent);
692 color: var(--nugu-content-important-global);
693 font-size: 12px;
694 font-weight: 850;
695}
696.finding-pill {
697 padding: 3px 7px;
698 border-radius: 999px;
699 border: 1px solid var(--border);
700 font-size: 11px;
701 font-weight: 850;
702 text-transform: uppercase;
703 letter-spacing: .02em;
704}
705.finding-pill.high { color: var(--nugu-error); border-color: color-mix(in srgb, var(--nugu-error) 36%, var(--border)); background: color-mix(in srgb, var(--nugu-error) 10%, transparent); }
706.finding-pill.medium { color: var(--nugu-warning); border-color: color-mix(in srgb, var(--nugu-warning) 36%, var(--border)); background: color-mix(in srgb, var(--nugu-warning) 10%, transparent); }
707.finding-pill.low { color: var(--nugu-info); border-color: color-mix(in srgb, var(--nugu-info) 36%, var(--border)); background: color-mix(in srgb, var(--nugu-info) 10%, transparent); }
708.finding-pill.category { color: var(--fg-soft); background: color-mix(in srgb, var(--fg) 5%, transparent); }
709.finding-location {
710 color: var(--muted);
711 font-family: "JetBrains Mono Nerd", "JetBrains Mono", ui-monospace, monospace;
712 font-size: 12px;
713 overflow-wrap: anywhere;
714}
715.finding-comment { color: var(--fg); line-height: 1.45; white-space: pre-wrap; }
212716.finding-chip {
213717 font-size: 11px;
214718 padding: 4px 6px;
217721 color: var(--fg);
218722 border: 1px solid color-mix(in srgb, var(--accent) 42%, transparent);
220.remove-finding { justify-self: start; padding: 4px 8px; font-size: 13px; color: var(--nugu-error); }
724.remove-finding {
725 margin-left: auto;
726 width: 24px;
727 height: 24px;
728 padding: 0;
729 border-radius: 999px;
730 font-size: 16px;
731 color: var(--nugu-error);
732}
221733.error { color: var(--nugu-error); }
222734.ok { color: var(--nugu-info); }
224736#tree file-tree-container,
225737#tree {
226738 --trees-fg-override: var(--fg);
227 --trees-muted-fg-override: var(--muted);
739 --trees-fg-muted-override: var(--muted);
228740 --trees-bg-override: transparent;
741 --trees-bg-muted-override: color-mix(in srgb, var(--focus) 14%, transparent);
742 --trees-input-bg-override: color-mix(in srgb, var(--bg) 74%, var(--panel-2));
743 --trees-search-bg-override: color-mix(in srgb, var(--bg) 74%, var(--panel-2));
744 --trees-search-fg-override: var(--fg);
745 --trees-density-override: .82;
746 --trees-font-size-override: 12px;
747 --trees-level-gap-override: 5px;
748 --trees-item-padding-x-override: 4px;
749 --trees-item-margin-x-override: 1px;
750 --trees-item-row-gap-override: 3px;
751 --trees-icon-width-override: 13px;
752 --trees-git-lane-width-override: 8px;
753 --trees-action-lane-width-override: 8px;
754 --trees-padding-inline-override: 4px;
755 --trees-accent-override: var(--accent);
229756 --trees-selected-bg-override: color-mix(in srgb, var(--accent) 18%, transparent);
230 --trees-hover-bg-override: color-mix(in srgb, var(--focus) 14%, transparent);
757 --trees-selected-fg-override: var(--fg);
758 --trees-focus-ring-color-override: var(--focus);
231759 --trees-border-color-override: var(--border);
760 --trees-status-added-override: var(--nugu-info);
761 --trees-status-modified-override: var(--nugu-warning);
762 --trees-status-renamed-override: var(--nugu-content-important-local);
763 --trees-status-deleted-override: var(--nugu-error);
764 --trees-font-family-override: "JetBrains Mono Nerd", "JetBrains Mono", ui-monospace, monospace;
234767@media (max-width: 1180px) {
235 #app { grid-template-columns: 248px minmax(0, 1fr); grid-template-rows: minmax(0, 1fr) minmax(280px, 40vh); }
236 #drawer { grid-column: 1 / -1; grid-row: 2; border-top: 1px solid var(--border); border-inline-start: 0; }
768 #app { grid-template-columns: minmax(0, 1fr); grid-template-rows: auto minmax(0, 1fr) minmax(280px, 40vh); }
769 #sidebar { display: none; }
770 #left-splitter, #right-splitter { display: none; }
771 #drawer { grid-row: 3; border-top: 1px solid var(--border); border-inline-start: 0; }

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

Added
new file mode 100644

+49 / −0 text lines

1export const NUGU_DARK = {
2 bg: "#121212",
3 panel: "#242424",
4 fg: "#ededed",
5 muted: "#9d9d9d",
6 accent: "#d86dd8",
7 focus: "#9aabae",
8 info: "#3ec5dd",
9 warning: "#9e9a69",
10 error: "#e46479",
11 important: "#dfd3f3",
12};
14export const NUGU_LIGHT = {
15 bg: "#ededed",
16 panel: "#dbdbdb",
17 fg: "#121212",
18 muted: "#292929",
19 accent: "#922792",
20 focus: "#15333b",
21 info: "#13616e",
22 warning: "#242317",
23 error: "#c0223c",
24 important: "#4f3c69",
25};
27export const CODE_FONT = "'JetBrains Mono Nerd', 'JetBrains Mono', 'Fira Code', ui-monospace, SFMono-Regular, Menlo, Consolas, monospace";
28export const NUGU_CODE_THEME = "nugu-code";
30type RegisterCustomCSSVariableTheme = (name: string, theme: Record<string, string>, isDark?: boolean) => void;
32export function registerNuguCodeTheme(registerCustomCSSVariableTheme: RegisterCustomCSSVariableTheme) {
33 registerCustomCSSVariableTheme(NUGU_CODE_THEME, {
34 foreground: NUGU_DARK.fg,
35 background: NUGU_DARK.bg,
36 "token-string": NUGU_DARK.focus,
37 "token-string-expression": NUGU_DARK.focus,
38 "token-comment": NUGU_DARK.important,
39 "token-constant": NUGU_DARK.focus,
40 "token-keyword": NUGU_DARK.muted,
41 "token-parameter": NUGU_DARK.warning,
42 "token-function": NUGU_DARK.fg,
43 "token-punctuation": NUGU_DARK.muted,
44 "token-link": NUGU_DARK.info,
45 "token-inserted": NUGU_DARK.info,
46 "token-deleted": NUGU_DARK.error,
47 "token-changed": NUGU_DARK.accent,
48 }, true);
49}

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

Modified

+9 / −2 text lines

1414export function extensionDir() { return EXT_DIR; }
1515export function staticDir() { return STATIC_DIR; }
17export async function ensureBrowserBundle(): Promise<void> {
17export async function ensureBrowserBundle(onStatus?: (message: string) => void): Promise<void> {
18 onStatus?.("checking browser bundle");
1819 const problem = await bundleProblem();
19 if (!problem) return;
20 if (!problem) {
21 onStatus?.("browser bundle ready");
22 return;
23 }
24 onStatus?.(`${problem}; building browser bundle`);
2025 try {
2126 await execFileAsync("bun", ["run", "build"], { cwd: EXT_DIR, maxBuffer: 1024 * 1024 * 5 });
2227 } catch (err) {
2429 const stderr = anyErr.stderr ? String(anyErr.stderr).trim() : "";
2530 throw new Error(`${problem}. Build failed. Run: cd ${EXT_DIR} && bun install && bun run build${stderr ? `\n${stderr}` : ""}`);
2631 }
32 onStatus?.("verifying browser bundle");
2733 const after = await bundleProblem();
2834 if (after) throw new Error(`${after}. Run: cd ${EXT_DIR} && bun install && bun run build`);
35 onStatus?.("browser bundle ready");
3138async function bundleProblem(): Promise<string | undefined> {

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

Modified

+4 / −3 text lines

22export const REVIEW_COMMAND = "diff-review";
33export const CANCEL_COMMAND = "diff-review-cancel";
44export const STATUS_ID = "diff-review";
5export const REVIEW_PORT = 47717;
56export const HEARTBEAT_INTERVAL_MS = 5 * 1000;
67export const REVIEW_POLL_INTERVAL_MS = 2 * 1000;
78export const HEARTBEAT_CHECK_INTERVAL_MS = 10 * 1000;
89export const HEARTBEAT_LOST_MS = 30 * 1000;
9export const MAX_DIFF_BYTES = 5 * 1024 * 1024;
10export const MAX_FILE_DIFF_BYTES = 1024 * 1024;
11export const REQUEST_BODY_MAX_BYTES = 1024 * 1024;
10export const MAX_DIFF_BYTES = 50 * 1024 * 1024;
11export const MAX_FILE_DIFF_BYTES = 10 * 1024 * 1024;
12export const REQUEST_BODY_MAX_BYTES = 10 * 1024 * 1024;
1213export const ANCHOR_CONTEXT_LINES = 3;
1314export const TOKEN_COOKIE = "diff_review_token";

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

Modified

+38 / −3 text lines

99 }
1111 lines.push("## Findings");
12 for (const finding of round.findings) lines.push(`- ${formatFinding(finding)}`);
12 for (const [index, finding] of round.findings.entries()) lines.push(formatFinding(finding, index + 1));
1313 if (round.notes?.trim()) lines.push("", "## Notes", round.notes.trim());
1414 lines.push("", "Use this review to propose and discuss a fix plan first. Do not edit files yet.");
1515 return lines.join("\n");
3333 };
36function formatFinding(finding: Finding): string {
36function formatFinding(finding: Finding, index: number): string {
3737 const range = finding.startLine === finding.endLine ? `${finding.startLine}` : `${finding.startLine}-${finding.endLine}`;
38 return `[${finding.severity}][${finding.category}] ${finding.file}:${range} ${finding.side} — ${finding.comment}`;
38 const location = `${finding.file}:${range}`;
39 const lineSemantics =
40 finding.side === "additions"
41 ? "file line number on new/additions side (current file)"
42 : "file line number on old/deletions side (preimage; may not exist in working tree)";
43 const context = [finding.anchor.before, finding.anchor.selected, finding.anchor.after].filter(Boolean).join("\n");
44 const lines = [
45 `### Finding ${index}: [${finding.severity}][${finding.category}] ${location} ${finding.side}`,
46 "",
47 `- Location: \`${location}\``,
48 `- Side: \`${finding.side}\``,
49 `- Line semantics: ${lineSemantics}`,
50 `- Comment: ${finding.comment}`,
51 ];
52 if (finding.notes?.trim()) lines.push(`- Notes: ${finding.notes.trim()}`);
53 lines.push("", "Selected code:", fencedText(finding.anchor.selected));
54 if (context.trim()) lines.push("", "Nearby context:", fencedText(context));
55 return lines.join("\n");
56}
58function fencedText(text: string): string {
59 const fence = longestBacktickRun(text) >= 3 ? "`".repeat(longestBacktickRun(text) + 1) : "```";
60 return `${fence}text\n${text}\n${fence}`;
61}
63function longestBacktickRun(text: string): number {
64 let longest = 0;
65 let current = 0;
66 for (const char of text) {
67 if (char === "`") current++;
68 else {
69 longest = Math.max(longest, current);
70 current = 0;
71 }
72 }
73 return Math.max(longest, current);

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

Modified

+82 / −29 text lines

1import type { ExtensionAPI } from "@mariozechner/pi-coding-agent";
1import { randomBytes, randomUUID } from "node:crypto";
2import type { ExtensionAPI, ExtensionContext } from "@mariozechner/pi-coding-agent";
23import { CANCEL_COMMAND, REVIEW_COMMAND, STATUS_ID } from "./constants.js";
3import { parseArgs } from "./args.js";
4import { parseArgs, type DiffReviewArgs } from "./args.js";
45import { ensureBrowserBundle } from "./bundle.js";
56import { collectDiff } from "./git.js";
67import { openBrowser } from "./open-browser.js";
78import { formatReviewMarkdown, makeReviewRound } from "./format.js";
8import { appendReviewRound, openFindings, restoreReviewState } from "./session-state.js";
9import { appendLiveReview, appendReviewRound, openFindings, restoreReviewState } from "./session-state.js";
910import { startReviewServer, type ReviewServer } from "./server.js";
10import type { ReviewState } from "./types.js";
11import type { ReviewLiveEntry, ReviewState } from "./types.js";
1213export default function diffReviewExtension(pi: ExtensionAPI) {
1314 let state: ReviewState = { round: 0, findings: [], rounds: [] };
1415 let active: ReviewServer | undefined;
16 let restoring: Promise<void> | undefined;
1618 pi.on("session_start", async (_event, ctx) => {
1719 state = restoreReviewState(ctx);
1820 const open = openFindings(state).length;
1921 if (open > 0 && ctx.hasUI) ctx.ui.setStatus(STATUS_ID, `${open} open review finding${open === 1 ? "" : "s"}`);
22 if (state.live && ctx.hasUI) restoring = restoreLiveReview(ctx, state.live).finally(() => { restoring = undefined; });
2023 });
2225 pi.on("session_shutdown", async () => {
2326 active?.close("shutdown");
2427 active = undefined;
28 restoring = undefined;
2529 });
2731 pi.registerCommand(REVIEW_COMMAND, {
2832 description: "Open browser UI to review current git diff and send findings back to Pi",
2933 handler: async (rawArgs, ctx) => {
3034 if (!ctx.hasUI) return ctx.ui.notify("/diff-review requires interactive mode", "error");
35 if (restoring) await restoring;
36 state = restoreReviewState(ctx);
3137 if (active) {
32 ctx.ui.notify(`diff-review already active: ${active.url}`, "warning");
38 ctx.ui.notify(`diff-review already active. Refresh existing browser tab. URL: ${active.url}`, "info");
39 ctx.ui.setStatus(STATUS_ID, `active ${active.url}`);
3340 return;
3441 }
42 if (state.live) {
43 restoring = restoreLiveReview(ctx, state.live).finally(() => { restoring = undefined; });
44 await restoring;
45 if (active) {
46 ctx.ui.notify(`diff-review restored. Refresh existing browser tab. URL: ${active.url}`, "info");
47 return;
48 }
49 }
3651 await ctx.waitForIdle();
38 let args: ReturnType<typeof parseArgs>;
53 let args: DiffReviewArgs;
3954 try {
4055 args = parseArgs(rawArgs);
4156 } catch (err) {
4459 }
4661 try {
47 ctx.ui.setStatus(STATUS_ID, "building review UI");
48 await ensureBrowserBundle();
62 await ensureBrowserBundle((message) => ctx.ui.setStatus(STATUS_ID, message));
5064 ctx.ui.setStatus(STATUS_ID, "collecting diff");
5165 const diff = await collectDiff(ctx.cwd, args);
5569 return;
5670 }
58 const round = state.round + 1;
59 const server = await startReviewServer({
60 diff,
61 state,
62 round,
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"),
73 });
72 const live = makeLiveEntry(state.round + 1, args);
73 appendLiveReview(ctx, live);
74 state = restoreReviewState(ctx);
75 const server = await launchReviewServer(pi, ctx, live, state, false);
7476 active = server;
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 });
8077 ctx.ui.setStatus(STATUS_ID, `live ${server.url}`);
8178 ctx.ui.notify(`Diff review live: ${server.url}`, "info");
9794 if (!active) return ctx.ui.notify("No active diff-review", "info");
9895 active.close("command");
9996 active = undefined;
97 if (state.live) appendLiveReview(ctx, { ...state.live, status: "closed", reason: "command" });
98 state = restoreReviewState(ctx);
10099 ctx.ui.setStatus(STATUS_ID, undefined);
101100 ctx.ui.notify("diff-review cancelled", "info");
102101 },
103102 });
104 async function restoreLiveReview(ctx: ExtensionContext, live: ReviewLiveEntry) {
105 if (active) return;
106 try {
107 ctx.ui.setStatus(STATUS_ID, "restoring browser review");
108 await ensureBrowserBundle((message) => ctx.ui.setStatus(STATUS_ID, message));
109 active = await launchReviewServer(pi, ctx, live, state, true);
110 ctx.ui.setStatus(STATUS_ID, `restored ${active.url}`);
111 ctx.ui.notify(`diff-review restored. Refresh existing tab or run /${REVIEW_COMMAND} to reopen.`, "info");
112 } catch (err) {
113 ctx.ui.notify(`diff-review reconnect failed: ${(err as Error).message}`, "warning");
114 }
115 }
117 async function launchReviewServer(pi: ExtensionAPI, ctx: ExtensionContext, live: ReviewLiveEntry, currentState: ReviewState, restored: boolean) {
118 const args = live.args;
119 const diff = await collectDiff(ctx.cwd, args);
120 const server = await startReviewServer({
121 diff,
122 state: currentState,
123 round: live.round,
124 token: live.token,
125 refreshDiff: () => collectDiff(ctx.cwd, args),
126 onSubmit: (result, latestDiff) => {
127 const entry = makeReviewRound(live.round, latestDiff, result.findings, result.notes);
128 appendReviewRound(ctx, entry);
129 state = restoreReviewState(ctx);
130 const markdown = formatReviewMarkdown(entry);
131 ctx.ui.notify(`diff review sent to Pi: ${result.findings.length} finding${result.findings.length === 1 ? "" : "s"}`, "info");
132 pi.sendUserMessage([{ type: "text", text: markdown }]);
133 },
134 onHeartbeatLost: () => ctx.ui.notify(restored ? "diff-review browser still disconnected" : "diff-review browser closed", "info"),
135 });
136 server.result.then((result) => {
137 if (active?.id === server.id) active = undefined;
138 ctx.ui.setStatus(STATUS_ID, undefined);
139 if (result.reason !== "shutdown") appendLiveReview(ctx, { ...live, status: "closed", reason: result.reason });
140 ctx.ui.notify(`/diff-review ended (${result.reason})`, result.reason === "timeout" ? "warning" : "info");
141 });
142 return server;
143 }
144}
146function makeLiveEntry(round: number, args: DiffReviewArgs): ReviewLiveEntry {
147 return {
148 version: 1,
149 kind: "live",
150 id: randomUUID(),
151 token: randomBytes(32).toString("base64url"),
152 round,
153 args,
154 status: "open",
155 createdAt: new Date().toISOString(),
156 };

pi/agent/extensions/diff-review/package.json

Modified

+2 / −1 text lines

66 "main": "index.ts",
77 "scripts": {
88 "build": "bun ./scripts/build-browser.ts",
9 "smoke:browser": "bun ./scripts/smoke-browser.ts"
9 "smoke:browser": "bun ./scripts/smoke-browser.ts",
10 "test:browser": "bun ./scripts/browser-regression.ts"
1011 },
1112 "dependencies": {
1213 "@pierre/diffs": "^1.1.22",

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

Added
new file mode 100644

+206 / −0 text lines

1import { execFile, spawn, type ChildProcess } from "node:child_process";
2import { mkdtemp, rm, stat, writeFile } from "node:fs/promises";
3import { tmpdir } from "node:os";
4import { dirname, join } from "node:path";
5import { fileURLToPath } from "node:url";
6import { promisify } from "node:util";
7import { collectDiff } from "../git.js";
8import { parseArgs } from "../args.js";
9import { startReviewServer, type ReviewServer } from "../server.js";
11const execFileAsync = promisify(execFile);
12const EXT_DIR = dirname(dirname(fileURLToPath(import.meta.url)));
13const CHROME_COMMANDS = ["google-chrome-stable", "google-chrome", "chromium", "chromium-browser"];
14const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));
16type CdpClient = Awaited<ReturnType<typeof cdp>>;
18async function main() {
19 await assertBundleSplit();
20 const chrome = process.env.CHROME ?? await findChrome();
21 if (!chrome) {
22 console.log("browser-regression: bundle checks ok; no Chrome/Chromium found, skipping CDP tests");
23 return;
24 }
25 await testSearchNavigationAndInputs(chrome);
26 console.log("browser-regression: bundle split, search navigation, Escape, notes autogrow, content-visibility ok");
27}
29async function assertBundleSplit() {
30 await execFileAsync("bun", ["run", "build"], { cwd: EXT_DIR, maxBuffer: 20 * 1024 * 1024 });
31 const app = await stat(join(EXT_DIR, "static", "app.js"));
32 if (app.size > 128 * 1024) throw new Error(`expected split app.js <=128 KiB, got ${app.size} bytes`);
33}
35async function testSearchNavigationAndInputs(chrome: string) {
36 const repo = await mkdtemp(join(tmpdir(), "diff-review-regression-repo-"));
37 const profile = await mkdtemp(join(tmpdir(), "diff-review-regression-chrome-"));
38 const port = 10_500 + Math.floor(Math.random() * 1000);
39 let browser: ChildProcess | undefined;
40 let server: ReviewServer | undefined;
41 try {
42 await prepareMultiHunkRepo(repo);
43 server = await startReviewServer({ diff: await collectDiff(repo, parseArgs("")), state: { round: 0, findings: [], rounds: [] }, round: 1, timeoutMs: 45_000 });
44 browser = spawn(chrome, ["--headless=new", "--no-sandbox", `--remote-debugging-port=${port}`, `--user-data-dir=${profile}`, "--window-size=1200,800", server.url], { stdio: "ignore" });
45 const tabInfo = await tab(port);
46 const client = await cdp(tabInfo.webSocketDebuggerUrl);
47 try {
48 await client.call("Runtime.enable");
49 await waitForReady(client);
50 await assertContentVisibility(client);
51 await assertNotesAutogrow(client);
52 await assertSearchLineMappingEscapeAndHorizontalScroll(client);
53 } finally {
54 client.close();
55 }
56 } finally {
57 browser?.kill();
58 server?.close("shutdown");
59 await rm(repo, { recursive: true, force: true });
60 await rm(profile, { recursive: true, force: true });
61 }
62}
64async function prepareMultiHunkRepo(repo: string) {
65 await git(repo, ["init", "-q"]);
66 await git(repo, ["config", "user.email", "regression@example.invalid"]);
67 await git(repo, ["config", "user.name", "Regression"]);
68 const lines = Array.from({ length: 220 }, (_, i) => `line ${i + 1}`);
69 lines[8] = `needle at nine ${"n".repeat(260)}`;
70 lines[191] = `needle at one ninety two ${"x".repeat(260)}`;
71 await writeFile(join(repo, "a.txt"), `${lines.join("\n")}\n`);
72 await git(repo, ["add", "a.txt"]);
73 await git(repo, ["commit", "-qm", "initial"]);
74 lines[8] = `needle at nine changed ${"m".repeat(260)}`;
75 lines[191] = `needle at one ninety two changed ${"y".repeat(260)}`;
76 await writeFile(join(repo, "a.txt"), `${lines.join("\n")}\n`);
77}
79async function waitForReady(client: CdpClient) {
80 for (let i = 0; i < 120; i++) {
81 const ready = await client.eval(`document.querySelector('#status')?.textContent === 'Ready' && !!document.querySelector('diffs-container')`);
82 if (ready) return;
83 await sleep(250);
84 }
85 throw new Error("browser did not reach Ready state");
86}
88async function assertContentVisibility(client: CdpClient) {
89 const value = await client.eval(`getComputedStyle(document.querySelector('.file-section')).contentVisibility`);
90 if (value !== "auto") throw new Error(`content-visibility not active: ${value}`);
91}
93async function assertNotesAutogrow(client: CdpClient) {
94 const result = await client.eval(`(async () => {
95 const wait = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
96 const notes = document.querySelector('#notes');
97 const before = notes.getBoundingClientRect().height;
98 notes.value = Array.from({ length: 22 }, (_, i) => 'note line ' + i).join('\\n');
99 notes.dispatchEvent(new Event('input', { bubbles: true }));
100 await wait(80);
101 const after = notes.getBoundingClientRect().height;
102 return { before, after, overflowY: getComputedStyle(notes).overflowY };
103 })()`);
104 if (!(result.after > result.before)) throw new Error(`notes did not grow: ${JSON.stringify(result)}`);
105 if (result.overflowY !== "hidden") throw new Error(`notes should avoid internal scrollbar: ${JSON.stringify(result)}`);
106}
108async function assertSearchLineMappingEscapeAndHorizontalScroll(client: CdpClient) {
109 const result = await client.eval(`(async () => {
110 const wait = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
111 const input = document.querySelector('#search');
112 input.focus();
113 input.value = 'needle';
114 input.dispatchEvent(new Event('input', { bubbles: true }));
115 for (let i = 0; i < 80; i++) {
116 await wait(100);
117 const results = [...document.querySelectorAll('.search-result')].map((node) => node.textContent || '');
118 if (results.some((text) => text.includes(':192 +'))) break;
119 }
120 const resultTexts = [...document.querySelectorAll('.search-result')].map((node) => node.textContent || '');
121 const target = [...document.querySelectorAll('.search-result')].find((node) => (node.textContent || '').includes(':192 +'));
122 const root = document.querySelector('[data-file-section="a.txt"] diffs-container').shadowRoot;
123 for (const code of root.querySelectorAll('code[data-code]')) code.scrollLeft = 420;
124 const beforeScrollLeft = [...root.querySelectorAll('code[data-code]')].map((code) => code.scrollLeft);
125 target?.click();
126 await wait(700);
127 const highlighted = [...root.querySelectorAll('.search-highlight[data-line]')].map((line) => line.getAttribute('data-line'));
128 const afterScrollLeft = [...root.querySelectorAll('code[data-code]')].map((code) => code.scrollLeft);
129 input.dispatchEvent(new KeyboardEvent('keydown', { key: 'Escape', bubbles: true, cancelable: true }));
130 await wait(100);
131 return {
132 resultTexts: resultTexts.slice(0, 8),
133 highlighted,
134 beforeScrollLeft,
135 afterScrollLeft,
136 popupHidden: document.querySelector('#search-results').hidden,
137 searchValue: input.value,
138 };
139 })()`);
140 if (!result.resultTexts.some((text: string) => text.includes(":9 +")) || !result.resultTexts.some((text: string) => text.includes(":192 +"))) {
141 throw new Error(`search results missing real file line numbers: ${JSON.stringify(result.resultTexts)}`);
142 }
143 if (!result.highlighted.includes("192")) throw new Error(`search did not highlight line 192: ${JSON.stringify(result)}`);
144 if (result.beforeScrollLeft.some((value: number, i: number) => result.afterScrollLeft[i] !== value)) {
145 throw new Error(`search jump changed horizontal scroll: ${JSON.stringify(result)}`);
146 }
147 if (!result.popupHidden || result.searchValue !== "needle") throw new Error(`Escape did not close popup and preserve value: ${JSON.stringify(result)}`);
148}
150async function git(cwd: string, args: string[]) {
151 await execFileAsync("git", args, { cwd, maxBuffer: 10 * 1024 * 1024 });
152}
154async function findChrome() {
155 for (const command of CHROME_COMMANDS) {
156 try {
157 await execFileAsync(command, ["--version"], { maxBuffer: 1024 * 1024 });
158 return command;
159 } catch {}
160 }
161 return undefined;
162}
164async function tab(port: number): Promise<{ webSocketDebuggerUrl: string }> {
165 for (let i = 0; i < 80; i++) {
166 try {
167 const tabs = await fetch(`http://127.0.0.1:${port}/json/list`).then((res) => res.json()) as Array<{ type: string; webSocketDebuggerUrl: string }>;
168 const page = tabs.find((entry) => entry.type === "page");
169 if (page) return page;
170 } catch {}
171 await sleep(250);
172 }
173 throw new Error("Chrome CDP tab not available");
174}
176async function cdp(url: string) {
177 let id = 0;
178 const ws = new WebSocket(url);
179 const pending = new Map<number, (message: any) => void>();
180 ws.onmessage = (event) => {
181 const message = JSON.parse(String(event.data));
182 pending.get(message.id)?.(message);
183 pending.delete(message.id);
184 };
185 await new Promise<void>((resolve) => { ws.onopen = () => resolve(); });
186 return {
187 call(method: string, params: Record<string, unknown> = {}) {
188 return new Promise<any>((resolve) => {
189 const callId = ++id;
190 pending.set(callId, resolve);
191 ws.send(JSON.stringify({ id: callId, method, params }));
192 });
193 },
194 async eval(expression: string) {
195 const result = await this.call("Runtime.evaluate", { expression, returnByValue: true, awaitPromise: true });
196 if (result.result?.exceptionDetails) throw new Error(JSON.stringify(result.result.exceptionDetails));
197 return result.result?.result?.value;
198 },
199 close() { ws.close(); },
200 };
201}
203main().catch((err) => {
204 console.error(err);
205 process.exit(1);
206});

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

Modified

+2 / −0 text lines

66 target: "browser";
77 minify: boolean;
88 sourcemap: "none";
9 splitting?: boolean;
910 naming: { entry: string; chunk: string; asset: string };
1011 }): Promise<{ success: boolean; logs: unknown[] }>;
1112};
3031 target: "browser",
3132 minify: true,
3233 sourcemap: "none",
34 splitting: true,
3335 naming: {
3436 entry: "app.[ext]",
3537 chunk: "assets/[name]-[hash].[ext]",

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

Modified

+7 / −9 text lines

129129 line.dispatchEvent(new MouseEvent('click', { bubbles: true, composed: true, clientX: 900, clientY: y }));
130130 await wait(200);
131131 };
132 const addFinding = async (line, commentText, y) => {
133 await clickLine(line, y);
132 const addFinding = async (selector, commentText, y) => {
133 const shadowRoot = must('diffs-container').shadowRoot;
134 await clickLine(must(selector, shadowRoot), y);
134135 const comment = must('#comment');
135136 comment.value = commentText;
136137 comment.dispatchEvent(new Event('input', { bubbles: true }));
139140 };
141142 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);
145143 const themeMode = must('#theme-mode');
146144 themeMode.value = 'light';
147145 themeMode.dispatchEvent(new Event('change', { bubbles: true }));
149 await addFinding(addLine1, 'remove me', 350);
150 await addFinding(addLine2, 'smoke finding', 370);
147 await addFinding('[data-additions] [data-line="1"]', 'remove me', 350);
148 await addFinding('[data-additions] [data-line="2"]', 'smoke finding', 370);
151149 must('.remove-finding').click();
152150 await wait(200);
157155 const result = {
158156 findingsText: must('#findings').innerText,
159157 failedResources,
160 fontLoaded: document.fonts.check('12px "Nugu Code Nerd"'),
158 fontLoaded: document.fonts.check('12px "JetBrains Mono Nerd"'),
161159 theme: document.documentElement.dataset.theme,
162160 };
163161 must('#submit').click();
175173 if (!isRecord(value)) throw new Error("browser smoke returned invalid result");
176174 if (typeof value.findingsText !== "string") throw new Error("browser smoke missing findings text");
177175 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");
176 if (value.fontLoaded !== true) throw new Error("JetBrains Mono Nerd font did not load");
179177 if (value.theme !== "light") throw new Error("theme selector did not apply light mode");
180178 if (Array.isArray(value.failedResources) && value.failedResources.length > 0) throw new Error(`resource failures: ${JSON.stringify(value.failedResources)}`);

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

Modified

+15 / −6 text lines

33import { stat } from "node:fs/promises";
44import { createServer, type IncomingMessage, type Server, type ServerResponse } from "node:http";
55import { extname, resolve, sep } from "node:path";
6import { ANCHOR_CONTEXT_LINES, HEARTBEAT_CHECK_INTERVAL_MS, HEARTBEAT_LOST_MS, REQUEST_BODY_MAX_BYTES, TOKEN_COOKIE } from "./constants.js";
6import { ANCHOR_CONTEXT_LINES, HEARTBEAT_CHECK_INTERVAL_MS, HEARTBEAT_LOST_MS, REQUEST_BODY_MAX_BYTES, REVIEW_PORT, TOKEN_COOKIE } from "./constants.js";
77import { staticDir } from "./bundle.js";
88import type { BrowserResult, CollectedDiff, Finding, FindingDraft, ReviewCategory, ReviewPayload, ReviewSeverity, ReviewSide, ReviewState } from "./types.js";
1919 diff: CollectedDiff;
2020 state: ReviewState;
2121 round: number;
22 token?: string;
2223 timeoutMs?: number;
2324 refreshDiff?: () => Promise<CollectedDiff>;
2425 onSubmit?: (result: Extract<BrowserResult, { type: "submit" }>, diff: CollectedDiff) => Promise<void> | void;
4546];
4748export async function startReviewServer(options: StartServerOptions): Promise<ReviewServer> {
48 const token = randomBytes(32).toString("base64url");
49 const token = options.token ?? randomBytes(32).toString("base64url");
4950 const id = randomUUID();
5051 let server: Server;
5152 let finished = false;
8384 server = createServer((req, res) => void dispatch(req, res, ctx));
8485 try {
85 await listen(server);
86 await listen(server, REVIEW_PORT);
8687 } catch (err) {
8788 clearInterval(heartbeatTimer);
8889 if (timeoutTimer) clearTimeout(timeoutTimer);
334335 return !!value && typeof value === "object" && !Array.isArray(value);
337function listen(server: Server) {
338function listen(server: Server, preferredPort: number) {
338339 return new Promise<void>((resolveListen, reject) => {
339 server.once("error", reject);
340 server.listen(0, "127.0.0.1", () => resolveListen());
340 const onError = (err: NodeJS.ErrnoException) => {
341 server.off("error", onError);
342 if (err.code !== "EADDRINUSE") return reject(err);
343 server.listen(0, "127.0.0.1", () => resolveListen());
344 };
345 server.once("error", onError);
346 server.listen(preferredPort, "127.0.0.1", () => {
347 server.off("error", onError);
348 resolveListen();
349 });
341350 });

pi/agent/extensions/diff-review/session-state.ts

Modified

+11 / −3 text lines

11import type { ExtensionContext } from "@mariozechner/pi-coding-agent";
22import { EXTENSION_ID } from "./constants.js";
3import type { ReviewRoundEntry, ReviewState } from "./types.js";
3import type { ReviewLiveEntry, ReviewRoundEntry, ReviewState } from "./types.js";
55type WritableSessionManager = ExtensionContext["sessionManager"] & {
66 appendCustomEntry(customType: string, data?: unknown): string;
1010 return (ctx.sessionManager as WritableSessionManager).appendCustomEntry(EXTENSION_ID, data);
13export function appendLiveReview(ctx: ExtensionContext, data: ReviewLiveEntry): string {
14 return (ctx.sessionManager as WritableSessionManager).appendCustomEntry(EXTENSION_ID, data);
15}
1317export function restoreReviewState(ctx: ExtensionContext): ReviewState {
1418 const rounds: ReviewRoundEntry[] = [];
19 let live: ReviewLiveEntry | undefined;
1520 for (const entry of ctx.sessionManager.getBranch()) {
1621 if (entry.type !== "custom" || entry.customType !== EXTENSION_ID) continue;
17 const data = entry.data as ReviewRoundEntry | undefined;
18 if (data?.version === 1 && data.kind === "round") rounds.push(data);
22 const data = entry.data as ReviewRoundEntry | ReviewLiveEntry | undefined;
23 if (data?.version !== 1) continue;
24 if (data.kind === "round") rounds.push(data);
25 if (data.kind === "live") live = data.status === "open" ? data : undefined;
1926 }
2027 return {
2128 round: Math.max(0, ...rounds.map((round) => round.round)),
2229 findings: rounds.flatMap((round) => round.findings),
2330 rounds,
31 ...(live && { live }),
2432 };

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

Deleted
deleted file mode 100644

+0 / −1 text lines

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/app.js

Deleted
deleted file mode 100644

Diff unavailable: object or read limit.

pi/agent/extensions/diff-review/static/assets/JetBrainsMonoNuguCode-e77247bx.woff2

Deleted
deleted file mode 100644

Binary size (old → new): 576420 → 0 bytes.

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

Deleted
deleted file mode 100644

+0 / −91 text lines

1<!doctype html>
2<html lang="en">
3<head>
4 <meta charset="utf-8" />
5 <meta name="viewport" content="width=device-width, initial-scale=1" />
6 <title>Pi Diff Review</title>
7 <link rel="icon" href="data:," />
8 <link rel="stylesheet" href="/static/app.css" />
9</head>
10<body>
11 <div id="app">
12 <aside id="sidebar">
13 <div class="brand">
14 <div>
15 <h1>Diff Review</h1>
16 <div class="subtitle">Pi × Pierre</div>
17 </div>
18 <label class="theme-label">Theme
19 <select id="theme-mode" aria-label="Theme mode">
20 <option value="system" selected>system</option>
21 <option value="dark">dark</option>
22 <option value="light">light</option>
23 </select>
24 </label>
25 </div>
26 <div id="meta"></div>
27 <div id="tree"></div>
28 </aside>
30 <main id="main">
31 <header id="topbar">
32 <div>
33 <div class="topbar-title">Review changed lines</div>
34 <div id="summary">Select a changed line to add a finding.</div>
35 </div>
36 <div id="finding-count" class="count-pill">0 findings</div>
37 </header>
38 <div id="diffs"></div>
39 </main>
41 <aside id="drawer">
42 <section class="card selection-card">
43 <div class="card-title">Selection</div>
44 <div id="selection" class="selection-empty">Click an added or deleted line.</div>
45 </section>
47 <section class="card">
48 <div class="card-title">New finding</div>
49 <div class="field-row">
50 <label>Severity
51 <select id="severity">
52 <option value="high">high</option>
53 <option value="medium" selected>medium</option>
54 <option value="low">low</option>
55 </select>
56 </label>
57 <label>Category
58 <select id="category">
59 <option value="bug" selected>bug</option>
60 <option value="style">style</option>
61 <option value="perf">perf</option>
62 <option value="question">question</option>
63 </select>
64 </label>
65 </div>
66 <label>Finding
67 <textarea id="comment" rows="6" placeholder="Describe the issue or question for the selected line"></textarea>
68 </label>
69 <button id="add" disabled>Add finding</button>
70 </section>
72 <section class="card findings-card">
73 <div class="card-title">Findings</div>
74 <div id="findings" class="empty-list">No findings yet.</div>
75 </section>
77 <section class="card">
78 <div class="card-title">Review notes</div>
79 <textarea id="notes" rows="4" placeholder="Optional context for the whole review"></textarea>
80 </section>
82 <footer class="actions">
83 <button id="cancel">Cancel</button>
84 <button id="submit">Send to Pi</button>
85 </footer>
86 <div id="status" role="status"></div>
87 </aside>
88 </div>
89 <script type="module" src="/static/app.js"></script>
90</body>
91</html>

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

Deleted
deleted file mode 100644

+0 / −21 text lines

1{
2 "bunVersion": "1.3.13",
3 "packageVersions": {
4 "@pierre/diffs": "^1.1.22",
5 "@pierre/trees": "^1.0.0-beta.4"
6 },
7 "sources": {
8 "browser/assets/JetBrainsMonoNuguCode.woff2": {
9 "sha256": "dc73d827bd8ee4b269745ea7ed084335e492d29f79c688db92e380dcb9c30bae"
10 },
11 "browser/index.html": {
12 "sha256": "69a3bd1992e445408587f8e6e867cd2ad9178ee7e4d7a94bd4b09a73754ec474"
13 },
14 "browser/index.ts": {
15 "sha256": "936106f521b4eafc71248c2956dad825b414f3710fb5325b3e91f1da33df1242"
16 },
17 "browser/style.css": {
18 "sha256": "272212b8a509d8506d5bf977b6cd49f5c72c10251b1d1b849ea41513d003e5e9"
19 }
20 }
21}No final newline

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

Modified

+17 / −0 text lines

4646 createdAt: string;
4747};
49export type ReviewLiveEntry = {
50 version: 1;
51 kind: "live";
52 id: string;
53 token: string;
54 round: number;
55 args: {
56 staged: boolean;
57 base?: string;
58 files?: string[];
59 };
60 status: "open" | "closed";
61 reason?: "browser" | "command" | "shutdown" | "timeout";
62 createdAt: string;
63};
4965export type ReviewState = {
5066 round: number;
5167 findings: Finding[];
5268 rounds: ReviewRoundEntry[];
69 live?: ReviewLiveEntry;
5370};
5572export type DiffFileStatus = "added" | "modified" | "deleted" | "renamed" | "binary";