repositories / dotfiles

dotfiles

bugabingas dorkfiles

owned by bugabinga

rework diff-review browser session

343880d7d7a08add8dfe971d30fcb32e75e30a7d

Oliver Jan Krylow <oliver@bugabinga.net> ·

unsigned

Browse filesCompare with HEAD

Changed files (22)

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

Added
new file mode 100644
1 +node_modules/
2 +static/

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

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

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

Modified
5 5 <meta name="viewport" content="width=device-width, initial-scale=1" />
6 6 <title>Pi Diff Review</title>
7 7 <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>
8 16 <link rel="stylesheet" href="/static/app.css" />
9 17 </head>
10 18 <body>
15 23 <h1>Diff Review</h1>
16 24 <div class="subtitle">Pi × Pierre</div>
17 25 </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>
19 28 <select id="theme-mode" aria-label="Theme mode">
20 29 <option value="system" selected>system</option>
21 30 <option value="dark">dark</option>
27 36 <div id="tree"></div>
28 37 </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>
30 43 <main id="main">
31 44 <header id="topbar">
32 45 <div>
33 46 <div class="topbar-title">Review changed lines</div>
34 47 <div id="summary">Select a changed line to add a finding.</div>
35 48 </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>
37 58 </header>
38 59 <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>
49 68 <div class="field-row">
50 69 <label>Severity
51 70 <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>
55 74 </select>
75 + <div class="field-subtitle" id="severity-sub">suspicious little gremlin</div>
56 76 </label>
57 77 <label>Category
58 78 <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>
63 83 </select>
84 + <div class="field-subtitle" id="category-sub">exquisite disaster</div>
64 85 </label>
65 86 </div>
66 87 <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>
68 89 </label>
69 90 <button id="add" disabled>Add finding</button>
70 91 </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">
72 99 <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>
74 101 <div id="findings" class="empty-list">No findings yet.</div>
75 102 </section>
83 110 <button id="cancel">Cancel</button>
84 111 <button id="submit">Send to Pi</button>
85 112 </footer>
86 - <div id="status" role="status"></div>
87 113 </aside>
115 + <div id="status" role="status" aria-live="polite">Ready</div>
88 116 </div>
89 117 <script type="module" src="/static/app.js"></script>
90 118 </body>

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

Modified
1 1 import "./style.css";
2 -import { FileDiff, parsePatchFiles, type DiffLineAnnotation, type FileDiffMetadata, type SelectedLineRange } from "@pierre/diffs";
3 -import { FileTree, type GitStatusEntry } from "@pierre/trees";
2 +import type { DiffLineAnnotation, FileDiff, FileDiffMetadata, SelectedLineRange } from "@pierre/diffs";
3 +import type { FileTree, FileTreeRowDecorationRenderer, GitStatusEntry } from "@pierre/trees";
4 +import { DIFF_FONT_CSS, TREE_CSS } from "./shadow-css.js";
5 +import { NUGU_CODE_THEME, registerNuguCodeTheme } from "./theme.js";
4 6 import { HEARTBEAT_INTERVAL_MS, REVIEW_POLL_INTERVAL_MS } from "../constants.js";
5 7 import type { FindingDraft, ReviewCategory, ReviewPayload, ReviewSeverity, ReviewSide } from "../types.js";
7 9 type FindingMeta = { findingId: string; severity: ReviewSeverity; category: ReviewCategory; comment: string };
8 10 type ThemeMode = "system" | "dark" | "light";
11 +type PaneSide = "left" | "right";
9 12 type ReviewSelection = { file: string; side: ReviewSide; startLine: number; endLine: number };
13 +type ViewPoint = { x: number; y: number };
14 +type SearchEntry = { file: string; side: "additions" | "deletions"; line: number; text: string };
15 +type SearchMatch = SearchEntry & { matchStart: number; matchEnd: number };
11 17 type Elements = {
18 + app: HTMLElement;
12 19 meta: HTMLElement;
13 20 summary: HTMLElement;
14 21 findingCount: HTMLElement;
22 + drawerCount: HTMLElement;
15 23 tree: HTMLElement;
16 24 diffs: HTMLElement;
25 + inlineFinding: HTMLElement;
17 26 selection: HTMLElement;
18 27 severity: HTMLSelectElement;
28 + severitySub: HTMLElement;
19 29 category: HTMLSelectElement;
30 + categorySub: HTMLElement;
20 31 comment: HTMLTextAreaElement;
21 32 add: HTMLButtonElement;
33 + inlineCancel: HTMLButtonElement;
22 34 findings: HTMLElement;
23 35 notes: HTMLTextAreaElement;
36 + search: HTMLInputElement;
37 + searchClear: HTMLButtonElement;
38 + searchResults: HTMLElement;
24 39 cancel: HTMLButtonElement;
25 40 submit: HTMLButtonElement;
26 41 status: HTMLElement;
27 42 themeMode: HTMLSelectElement;
43 + leftSplitter: HTMLElement;
44 + rightSplitter: HTMLElement;
45 + toggleLeft: HTMLButtonElement;
46 + toggleRight: HTMLButtonElement;
30 49 const ROUTES = {
35 54 submit: "/api/submit",
36 55 } as const;
37 56 const THEME_STORAGE_KEY = "diff-review-theme";
38 -const DIFF_FONT_CSS = `
39 - :host, pre, code, [data-line], [data-code], [data-content], [data-line-number] {
40 - font-family: 'Nugu Code Nerd', 'JetBrains Mono', 'Fira Code', ui-monospace, SFMono-Regular, Menlo, Consolas, monospace !important;
41 - font-size: 12px;
42 - line-height: 1.55;
43 - }
44 -`;
57 +const LAYOUT_STORAGE_KEY = "diff-review-layout";
45 58 const REVIEW_CATEGORIES = ["bug", "style", "perf", "question"] as const satisfies readonly ReviewCategory[];
46 59 const REVIEW_SEVERITIES = ["high", "medium", "low"] as const satisfies readonly ReviewSeverity[];
47 60 const THEME_MODES = ["system", "dark", "light"] as const satisfies readonly ThemeMode[];
61 +const SEVERITY_SUBS: Record<string, string> = { high: "ship it to prod, coward", medium: "suspicious little gremlin", low: "tiny crime, still crime" };
62 +const CATEGORY_SUBS: Record<string, string> = { bug: "exquisite disaster", style: "crimes against taste", perf: "artisanal slowness", question: "explain yourself" };
63 +const PANE_LIMITS = {
64 + left: { min: 180, max: 560, fallback: 288 },
65 + right: { min: 280, max: 680, fallback: 382 },
66 +} as const;
68 +type LayoutState = {
69 + left: number;
70 + right: number;
71 + leftCollapsed: boolean;
72 + rightCollapsed: boolean;
73 +};
49 75 const token = new URLSearchParams(location.search).get("token") ?? "";
50 76 const els: Elements = {
77 + app: must("app"),
51 78 meta: must("meta"),
52 79 summary: must("summary"),
53 80 findingCount: must("finding-count"),
81 + drawerCount: must("drawer-count"),
54 82 tree: must("tree"),
55 83 diffs: must("diffs"),
84 + inlineFinding: must("inline-finding"),
56 85 selection: must("selection"),
57 86 severity: mustSelect("severity"),
87 + severitySub: must("severity-sub"),
58 88 category: mustSelect("category"),
89 + categorySub: must("category-sub"),
59 90 comment: mustText("comment"),
60 91 add: mustButton("add"),
92 + inlineCancel: mustButton("inline-cancel"),
61 93 findings: must("findings"),
62 94 notes: mustText("notes"),
95 + search: must("search") as HTMLInputElement,
96 + searchClear: mustButton("search-clear"),
97 + searchResults: must("search-results"),
63 98 cancel: mustButton("cancel"),
64 99 submit: mustButton("submit"),
65 100 status: must("status"),
66 101 themeMode: mustSelect("theme-mode"),
102 + leftSplitter: must("left-splitter"),
103 + rightSplitter: must("right-splitter"),
104 + toggleLeft: mustButton("toggle-left"),
105 + toggleRight: mustButton("toggle-right"),
69 108 const findings: FindingDraft[] = [];
70 109 const diffViews = new Map<string, FileDiff<FindingMeta>>();
71 110 const systemTheme = window.matchMedia("(prefers-color-scheme: light)");
72 111 let fileTree: FileTree | undefined;
112 +let selectedFile: string | undefined;
73 113 let selected: ReviewSelection | undefined;
114 +let lastDiffPointer: ViewPoint | undefined;
115 +let searchIndex: SearchEntry[] = [];
116 +let searchResults: SearchMatch[] = [];
117 +let searchActiveIndex = -1;
118 +let searchDebounce: number | undefined;
119 +let diffsModule: typeof import("@pierre/diffs") | undefined;
120 +let treesModule: typeof import("@pierre/trees") | undefined;
74 121 let heartbeat: number | undefined;
75 122 let reviewPoll: number | undefined;
76 123 let reviewHash = "";
124 +let renderGeneration = 0;
125 +let searchIndexing = false;
126 +let notesGrowFrame: number | undefined;
77 127 let closing = false;
78 128 let themeMode: ThemeMode = readThemeMode();
80 130 applyThemeMode(themeMode);
81 131 els.themeMode.value = themeMode;
132 +applyLayout(readLayout());
83 -main().catch((err) => setStatus(errorMessage(err), "error"));
134 +main().catch((err) => setDisconnectedStatus(err));
84 135 window.addEventListener("pagehide", closeFromBrowser);
85 136 systemTheme.addEventListener("change", () => {
86 137 if (themeMode === "system") applyThemeMode(themeMode);
89 140 async function main() {
90 141 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;
92 147 startHeartbeat();
93 148 startReviewPolling();
94 - renderReview(review);
95 149 wireActions();
150 + await renderReview(review);
96 151 setStatus("Ready");
99 -function renderReview(review: ReviewPayload) {
154 +async 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);
162 +function diffs() {
163 + if (!diffsModule) throw new Error("Diff renderer not loaded");
164 + return diffsModule;
167 +function trees() {
168 + if (!treesModule) throw new Error("File tree renderer not loaded");
169 + return treesModule;
172 +async function renderReview(review: ReviewPayload) {
173 + const generation = ++renderGeneration;
100 174 reviewHash = hashReview(review);
101 175 renderMeta(review);
102 176 renderTree(review);
103 - renderDiffs(review);
177 + const fileDiffs = await renderDiffs(review, generation);
178 + if (!fileDiffs || generation !== renderGeneration) return;
104 179 renderAnnotations();
180 + void buildSearchIndex(fileDiffs, generation);
107 183 function renderMeta(review: ReviewPayload) {
108 184 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);
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);
112 202 updateFindingCount();
205 +function 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}`;
212 +function 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;
115 225 function renderTree(review: ReviewPayload) {
116 226 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,
119 232 search: true,
233 + unsafeCSS: TREE_CSS,
120 234 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;
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;
255 + selectFile(path, true);
256 + },
124 258 fileTree.render({ fileTreeContainer: els.tree });
259 + wireTreeSearchClear(fileTree);
127 -function renderDiffs(review: ReviewPayload) {
262 +function 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) }];
270 +function renamedTargetForPrevPath(review: ReviewPayload, path: string) {
271 + return review.files.find((file) => file.status === "renamed" && file.prevPath === path)?.path;
274 +function 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 + };
287 +function 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 + };
320 +function 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);
326 + return skipped;
329 +function 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] };
335 +async function renderDiffs(review: ReviewPayload, generation: number): Promise<FileDiffMetadata[] | undefined> {
128 336 for (const view of diffViews.values()) view.cleanUp();
129 337 diffViews.clear();
130 338 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();
348 + return files;
138 351 function renderFileDiff(fileDiff: FileDiffMetadata) {
139 352 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 },
142 355 diffStyle: "split",
143 356 overflow: "scroll",
144 357 enableLineSelection: true,
146 359 lineHoverHighlight: "both",
147 360 themeType: themeMode,
148 361 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)),
153 366 renderAnnotation: renderAnnotation,
155 368 view.render({ fileDiff, containerWrapper: section, lineAnnotations: [] });
160 373 const section = document.createElement("section");
161 374 section.className = "file-section";
162 375 section.dataset.fileSection = fileDiff.name;
376 + if (fileDiff.name === selectedFile) section.dataset.selectedFile = "true";
164 378 const title = document.createElement("h2");
165 379 title.className = "file-title";
180 394 return chip;
183 -function setSelection(file: string, range: SelectedLineRange | null) {
397 +function setSelection(file: string, range: SelectedLineRange | null, point?: ViewPoint) {
184 398 const next = normalizeSelection(file, range);
399 + if (!next) {
400 + clearSelection(false);
401 + return;
185 403 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);
410 +function 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 + });
421 +function hideFindingForm() {
422 + els.inlineFinding.hidden = true;
423 + delete els.inlineFinding.dataset.open;
426 +function 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`;
441 +function 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 };
451 +function centerPoint(): ViewPoint {
452 + return { x: window.innerWidth / 2, y: window.innerHeight / 2 };
455 +function eventPoint(event: MouseEvent | PointerEvent): ViewPoint {
456 + return { x: event.clientX, y: event.clientY };
191 459 function normalizeSelection(file: string, range: SelectedLineRange | null): ReviewSelection | undefined {
208 476 function wireActions() {
209 477 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] ?? ""; });
210 480 els.add.addEventListener("click", addFinding);
211 481 els.submit.addEventListener("click", submitReview);
212 482 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;
514 + if (event.key === "ArrowDown" || event.key === "ArrowUp") {
515 + event.preventDefault();
516 + navigateSearch(event.key === "ArrowDown" ? 1 : -1);
517 + return;
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();
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 + });
538 +function scheduleNotesAutoGrow() {
539 + if (notesGrowFrame !== undefined) return;
540 + notesGrowFrame = requestAnimationFrame(() => {
541 + notesGrowFrame = undefined;
542 + autoGrowTextarea(els.notes);
543 + });
546 +function autoGrowTextarea(textarea: HTMLTextAreaElement) {
547 + textarea.style.height = "auto";
548 + textarea.style.height = `${textarea.scrollHeight}px`;
551 +function 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 + });
215 559 function updateThemeMode() {
219 563 for (const view of diffViews.values()) view.setThemeType(themeMode);
566 +function 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);
574 +function 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 });
602 +function 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();
618 +function writeLayout(layout: LayoutState) {
619 + localStorage.setItem(LAYOUT_STORAGE_KEY, JSON.stringify(layout));
622 +function defaultLayout(): LayoutState {
623 + return { left: PANE_LIMITS.left.fallback, right: PANE_LIMITS.right.fallback, leftCollapsed: false, rightCollapsed: false };
626 +function 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");
637 +function 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)));
222 643 async function addFinding() {
223 644 const draft = draftFromSelection();
224 645 if (!draft) return;
227 648 await api(ROUTES.validateFinding, postJson(draft));
228 649 findings.push(draft);
229 650 clearFindingForm();
651 + clearSelection(true);
230 652 renderFindings();
231 653 renderAnnotations();
232 654 setStatus("Finding added");
233 655 } catch (err) {
234 656 setStatus(errorMessage(err), "error");
235 657 } finally {
236 - els.add.disabled = false;
658 + els.add.disabled = !selected;
286 708 els.comment.value = "";
711 +function 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);
289 720 function renderFindings() {
290 721 els.findings.replaceChildren();
291 722 els.findings.className = findings.length === 0 ? "empty-list" : "";
301 732 function findingItem(finding: FindingDraft, index: number) {
302 733 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;
308 756 const remove = document.createElement("button");
309 757 remove.className = "remove-finding";
310 758 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);
315 776 return item;
324 785 function updateFindingCount() {
325 786 els.findingCount.textContent = `${findings.length} finding${findings.length === 1 ? "" : "s"}`;
787 + els.drawerCount.textContent = String(findings.length);
328 790 function 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();
797 +async 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();
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);
815 +function 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 });
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 });
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 });
837 + deletionLine += content.deletions;
838 + additionLine += content.additions;
842 + return entries;
845 +function 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;
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;
869 + renderSearchResults();
870 + updateSearchBadge();
873 +function 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);
886 +function 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();
897 +function 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}`;
905 +function 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;
918 + return hits;
921 +function 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;
955 +function 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]);
971 + });
974 +function 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" });
982 +function 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");
989 +function isEscapeKey(event: KeyboardEvent) {
990 + return event.key === "Escape" || event.key === "Esc";
993 +function cancelPendingSearch() {
994 + window.clearTimeout(searchDebounce);
995 + searchDebounce = undefined;
998 +function closeCodeSearchPopup() {
999 + cancelPendingSearch();
1000 + searchActiveIndex = -1;
1001 + hideSearch();
1004 +function clearCodeSearch(refocus: boolean) {
1005 + cancelPendingSearch();
1006 + els.search.value = "";
1007 + searchResults = [];
1008 + searchActiveIndex = -1;
1009 + hideSearch();
1010 + updateSearchBadge();
1011 + if (refocus) els.search.focus();
1014 +function hideSearch() {
1015 + els.searchResults.hidden = true;
1016 + updateSearchBadge();
332 1019 function annotationsFor(file: string): DiffLineAnnotation<FindingMeta>[] {
371 1058 const review = await api<ReviewPayload>(ROUTES.review);
372 1059 const nextHash = hashReview(review);
373 1060 if (nextHash === reviewHash) return;
374 - renderReview(review);
1061 + await renderReview(review);
375 1062 setStatus("Diff updated", "ok");
376 1063 } catch (err) {
377 - setStatus(errorMessage(err), "error");
1064 + setDisconnectedStatus(err);
411 1098 els.status.className = tone === "neutral" ? "" : tone;
1101 +function 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");
414 1107 function readThemeMode(): ThemeMode {
415 1108 return themeModeFromValue(localStorage.getItem(THEME_STORAGE_KEY));
418 1111 function applyThemeMode(mode: ThemeMode) {
419 1112 document.documentElement.dataset.theme = mode === "system" ? (systemTheme.matches ? "light" : "dark") : mode;
420 1113 document.documentElement.dataset.themeMode = mode;
1114 + const icon = document.querySelector<HTMLElement>(".theme-icon");
1115 + if (icon) icon.textContent = mode === "dark" ? "☾" : mode === "light" ? "☼" : "◐";
1118 +function selectFile(path: string | undefined, scroll: boolean) {
1119 + selectedFile = path;
1120 + applySelectedFileEmphasis();
1121 + if (scroll) scrollToFile(path);
1124 +function 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;
423 1132 function scrollToFile(path: string | undefined) {
424 1133 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" });
428 1141 function toGitStatus(status: ReviewPayload["files"][number]["status"]): GitStatusEntry["status"] {

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

Added
new file mode 100644
1 +import { CODE_FONT, NUGU_DARK, NUGU_LIGHT } from "./theme.js";
3 +export 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 +`;
66 +export 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};
101 + [data-file-tree-virtualized-scroll='true'] {
102 + overflow-x: auto;
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;
110 + [data-item-git-status='ignored'] {
111 + opacity: .58;
112 + cursor: not-allowed;
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;
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;
125 + [data-file-tree-search-container] {
126 + position: relative;
127 + display: block !important;
128 + padding-inline: var(--trees-padding-inline) !important;
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;
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;
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;
172 + [data-file-tree-search-input]:placeholder-shown + .tree-search-clear {
173 + display: none;
175 + .tree-search-clear:hover {
176 + background: color-mix(in srgb, var(--trees-accent) 24%, transparent);
177 + color: var(--trees-fg);

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

Modified
1 1 @font-face {
2 - font-family: "Nugu Code Nerd";
2 + font-family: "JetBrains Mono Nerd";
3 3 src: url("./assets/JetBrainsMonoNuguCode.woff2") format("woff2");
4 4 font-weight: 400;
5 5 font-style: normal;
88 88 background: radial-gradient(circle at top left, color-mix(in srgb, var(--accent) 12%, transparent), transparent 28rem), var(--bg);
90 90 button, select, textarea { font: inherit; }
91 +code, pre { font-family: "JetBrains Mono Nerd", "JetBrains Mono", "Fira Code", ui-monospace, SFMono-Regular, Menlo, Consolas, monospace; }
91 92 button { cursor: pointer; }
92 93 button:disabled { cursor: not-allowed; opacity: .48; }
94 95 #app {
96 + --left-pane: 288px;
97 + --right-pane: 382px;
95 98 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);
97 100 height: 100vh;
98 101 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; }
101 109 #sidebar, #drawer, #main {
102 110 min-height: 0;
111 119 #sidebar { border-inline-end: 1px solid var(--border); }
112 120 #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);
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);
139 +.splitter:hover,
140 +#app[data-resizing="true"] .splitter {
141 + background: color-mix(in srgb, var(--focus) 16%, var(--panel));
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;
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);
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%); }
115 170 #topbar {
116 171 display: flex;
121 176 border-bottom: 1px solid var(--border);
122 177 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;
185 +.search-wrap {
186 + position: relative;
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;
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;
216 +.search-clear:hover {
217 + background: color-mix(in srgb, var(--accent) 24%, transparent);
218 + color: var(--fg);
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;
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;
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;
255 +.search-result {
256 + padding: 8px 10px;
257 + border-radius: 10px;
258 + cursor: pointer;
259 + font-size: 12px;
260 + line-height: 1.4;
262 +.search-result:hover,
263 +.search-result:focus-visible {
264 + background: color-mix(in srgb, var(--focus) 14%, transparent);
265 + outline: none;
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;
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;
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;
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;
293 +.search-result-preview mark {
294 + color: #fff;
295 + background: #c026d3;
296 + border-radius: 3px;
297 + padding: 1px 3px;
298 + font-weight: 700;
300 +:root[data-theme="light"] .search-result-preview mark {
301 + color: #fff;
302 + background: #a21caf;
304 +.search-result-active .search-result-preview mark {
305 + background: #e879f9;
306 + color: #1e1e2e;
308 +.search-empty {
309 + padding: 14px;
310 + color: var(--muted);
311 + font-size: 13px;
312 + text-align: center;
314 +.search-more {
315 + padding: 8px 10px;
316 + color: var(--muted);
317 + font-size: 11px;
318 + text-align: center;
320 +#diffs {
321 + overflow: auto;
322 + padding: 16px 14px 72vh;
323 + scroll-padding-top: 16px;
126 326 .brand { display: grid; grid-template-columns: 1fr auto; gap: 10px; align-items: start; margin-bottom: 14px; }
127 327 h1 { font-size: 22px; line-height: 1; margin: 0; letter-spacing: -0.03em; color: var(--nugu-content-important-global); }
128 -.subtitle { margin-top: 6px; font-size: 14px; color: var(--muted); }
129 -.topbar-title { margin: 0 0 3px; font-size: 16px; font-weight: 800; color: var(--nugu-content-important-global); }
130 -#summary { color: var(--fg-soft); font-size: 14px; }
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;
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;
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;
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);
368 +.summary-hint {
369 + color: var(--faint);
370 + font-weight: 500;
131 372 .card-title, .file-title { color: var(--nugu-content-important-global); font-weight: 800; }
132 373 .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;
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;
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;
407 +.meta-label {
408 + color: var(--faint);
409 + font-weight: 600;
410 + text-transform: uppercase;
411 + letter-spacing: .04em;
413 +.meta-value {
414 + color: color-mix(in srgb, var(--fg-soft) 76%, var(--muted));
415 + font-weight: 800;
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;
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;
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); }
135 452 #tree { height: calc(100vh - 116px); border-radius: var(--radius); background: color-mix(in srgb, var(--bg) 65%, var(--panel)); overflow: hidden; }
136 453 .count-pill {
137 454 padding: 6px 10px;
144 461 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);
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;
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;
501 +.inline-finding label { margin-block: 8px; }
502 +.inline-finding textarea { min-height: 96px; }
147 504 .card {
148 505 padding: 12px;
149 506 margin-bottom: 12px;
155 512 .selection-empty { color: var(--muted); }
156 513 .selection-active { color: var(--fg); font-weight: 800; }
157 514 .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;
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;
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;
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);
562 +.theme-label select:focus { box-shadow: none; }
161 564 label { display: grid; gap: 6px; margin-block: 10px; font-size: 14px; color: var(--fg-soft); font-weight: 700; }
162 565 textarea, select {
173 576 box-shadow: 0 0 0 3px color-mix(in srgb, var(--focus) 28%, transparent);
175 578 textarea { 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;
177 589 .actions { position: sticky; bottom: 0; display: grid; grid-template-columns: 1fr 1fr; gap: 8px; padding-top: 4px; background: linear-gradient(transparent, var(--panel) 20%); }
178 590 .actions button, #add, .remove-finding {
186 598 #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)); }
187 599 #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;
611 +.file-section[data-selected-file="true"] {
612 + background: linear-gradient(90deg, color-mix(in srgb, var(--accent) 10%, transparent), transparent 28rem);
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;
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);
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;
190 646 .file-title {
191 647 position: sticky;
192 - top: -16px;
193 - z-index: 2;
648 + top: 0;
649 + z-index: 5;
194 650 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;
196 655 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;
199 -diffs-container { border-radius: var(--radius); overflow: hidden; box-shadow: 0 0 0 1px var(--border); }
660 +diffs-container { position: relative; z-index: 2; border-radius: var(--radius); overflow: hidden; box-shadow: 0 0 0 1px var(--border); }
200 661 .empty-list { color: var(--muted); font-size: 14px; }
201 662 .finding-item {
202 663 display: grid;
203 - gap: 6px;
664 + gap: 8px;
204 665 border: 1px solid var(--border);
205 666 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;
209 670 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;
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;
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;
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;
715 +.finding-comment { color: var(--fg); line-height: 1.45; white-space: pre-wrap; }
212 716 .finding-chip {
213 717 font-size: 11px;
214 718 padding: 4px 6px;
217 721 color: var(--fg);
218 722 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);
221 733 .error { color: var(--nugu-error); }
222 734 .ok { color: var(--nugu-info); }
224 736 #tree file-tree-container,
225 737 #tree {
226 738 --trees-fg-override: var(--fg);
227 - --trees-muted-fg-override: var(--muted);
739 + --trees-fg-muted-override: var(--muted);
228 740 --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);
229 756 --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);
231 759 --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;
234 767 @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
1 +export 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 +};
14 +export 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 +};
27 +export const CODE_FONT = "'JetBrains Mono Nerd', 'JetBrains Mono', 'Fira Code', ui-monospace, SFMono-Regular, Menlo, Consolas, monospace";
28 +export const NUGU_CODE_THEME = "nugu-code";
30 +type RegisterCustomCSSVariableTheme = (name: string, theme: Record<string, string>, isDark?: boolean) => void;
32 +export 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);

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

Modified
14 14 export function extensionDir() { return EXT_DIR; }
15 15 export function staticDir() { return STATIC_DIR; }
17 -export async function ensureBrowserBundle(): Promise<void> {
17 +export async function ensureBrowserBundle(onStatus?: (message: string) => void): Promise<void> {
18 + onStatus?.("checking browser bundle");
18 19 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`);
20 25 try {
21 26 await execFileAsync("bun", ["run", "build"], { cwd: EXT_DIR, maxBuffer: 1024 * 1024 * 5 });
22 27 } catch (err) {
24 29 const stderr = anyErr.stderr ? String(anyErr.stderr).trim() : "";
25 30 throw new Error(`${problem}. Build failed. Run: cd ${EXT_DIR} && bun install && bun run build${stderr ? `\n${stderr}` : ""}`);
32 + onStatus?.("verifying browser bundle");
27 33 const after = await bundleProblem();
28 34 if (after) throw new Error(`${after}. Run: cd ${EXT_DIR} && bun install && bun run build`);
35 + onStatus?.("browser bundle ready");
31 38 async function bundleProblem(): Promise<string | undefined> {

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

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

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

Modified
11 11 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));
13 13 if (round.notes?.trim()) lines.push("", "## Notes", round.notes.trim());
14 14 lines.push("", "Use this review to propose and discuss a fix plan first. Do not edit files yet.");
15 15 return lines.join("\n");
36 -function formatFinding(finding: Finding): string {
36 +function formatFinding(finding: Finding, index: number): string {
37 37 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");
58 +function fencedText(text: string): string {
59 + const fence = longestBacktickRun(text) >= 3 ? "`".repeat(longestBacktickRun(text) + 1) : "```";
60 + return `${fence}text\n${text}\n${fence}`;
63 +function 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
1 -import type { ExtensionAPI } from "@mariozechner/pi-coding-agent";
1 +import { randomBytes, randomUUID } from "node:crypto";
2 +import type { ExtensionAPI, ExtensionContext } from "@mariozechner/pi-coding-agent";
2 3 import { CANCEL_COMMAND, REVIEW_COMMAND, STATUS_ID } from "./constants.js";
3 -import { parseArgs } from "./args.js";
4 +import { parseArgs, type DiffReviewArgs } from "./args.js";
4 5 import { ensureBrowserBundle } from "./bundle.js";
5 6 import { collectDiff } from "./git.js";
6 7 import { openBrowser } from "./open-browser.js";
7 8 import { formatReviewMarkdown, makeReviewRound } from "./format.js";
8 -import { appendReviewRound, openFindings, restoreReviewState } from "./session-state.js";
9 +import { appendLiveReview, appendReviewRound, openFindings, restoreReviewState } from "./session-state.js";
9 10 import { startReviewServer, type ReviewServer } from "./server.js";
10 -import type { ReviewState } from "./types.js";
11 +import type { ReviewLiveEntry, ReviewState } from "./types.js";
12 13 export default function diffReviewExtension(pi: ExtensionAPI) {
13 14 let state: ReviewState = { round: 0, findings: [], rounds: [] };
14 15 let active: ReviewServer | undefined;
16 + let restoring: Promise<void> | undefined;
16 18 pi.on("session_start", async (_event, ctx) => {
17 19 state = restoreReviewState(ctx);
18 20 const open = openFindings(state).length;
19 21 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; });
22 25 pi.on("session_shutdown", async () => {
23 26 active?.close("shutdown");
24 27 active = undefined;
28 + restoring = undefined;
27 31 pi.registerCommand(REVIEW_COMMAND, {
28 32 description: "Open browser UI to review current git diff and send findings back to Pi",
29 33 handler: async (rawArgs, ctx) => {
30 34 if (!ctx.hasUI) return ctx.ui.notify("/diff-review requires interactive mode", "error");
35 + if (restoring) await restoring;
36 + state = restoreReviewState(ctx);
31 37 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}`);
33 40 return;
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 + }
36 51 await ctx.waitForIdle();
38 - let args: ReturnType<typeof parseArgs>;
53 + let args: DiffReviewArgs;
39 54 try {
40 55 args = parseArgs(rawArgs);
41 56 } catch (err) {
46 61 try {
47 - ctx.ui.setStatus(STATUS_ID, "building review UI");
48 - await ensureBrowserBundle();
62 + await ensureBrowserBundle((message) => ctx.ui.setStatus(STATUS_ID, message));
50 64 ctx.ui.setStatus(STATUS_ID, "collecting diff");
51 65 const diff = await collectDiff(ctx.cwd, args);
55 69 return;
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);
74 76 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 - });
80 77 ctx.ui.setStatus(STATUS_ID, `live ${server.url}`);
81 78 ctx.ui.notify(`Diff review live: ${server.url}`, "info");
97 94 if (!active) return ctx.ui.notify("No active diff-review", "info");
98 95 active.close("command");
99 96 active = undefined;
97 + if (state.live) appendLiveReview(ctx, { ...state.live, status: "closed", reason: "command" });
98 + state = restoreReviewState(ctx);
100 99 ctx.ui.setStatus(STATUS_ID, undefined);
101 100 ctx.ui.notify("diff-review cancelled", "info");
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");
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;
146 +function 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
6 6 "main": "index.ts",
7 7 "scripts": {
8 8 "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"
11 12 "dependencies": {
12 13 "@pierre/diffs": "^1.1.22",

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

Added
new file mode 100644
1 +import { execFile, spawn, type ChildProcess } from "node:child_process";
2 +import { mkdtemp, rm, stat, writeFile } from "node:fs/promises";
3 +import { tmpdir } from "node:os";
4 +import { dirname, join } from "node:path";
5 +import { fileURLToPath } from "node:url";
6 +import { promisify } from "node:util";
7 +import { collectDiff } from "../git.js";
8 +import { parseArgs } from "../args.js";
9 +import { startReviewServer, type ReviewServer } from "../server.js";
11 +const execFileAsync = promisify(execFile);
12 +const EXT_DIR = dirname(dirname(fileURLToPath(import.meta.url)));
13 +const CHROME_COMMANDS = ["google-chrome-stable", "google-chrome", "chromium", "chromium-browser"];
14 +const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));
16 +type CdpClient = Awaited<ReturnType<typeof cdp>>;
18 +async 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");
29 +async 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`);
35 +async 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 + }
64 +async 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`);
79 +async 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");
88 +async 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}`);
93 +async 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)}`);
108 +async 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;
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)}`);
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)}`);
147 + if (!result.popupHidden || result.searchValue !== "needle") throw new Error(`Escape did not close popup and preserve value: ${JSON.stringify(result)}`);
150 +async function git(cwd: string, args: string[]) {
151 + await execFileAsync("git", args, { cwd, maxBuffer: 10 * 1024 * 1024 });
154 +async function findChrome() {
155 + for (const command of CHROME_COMMANDS) {
156 + try {
157 + await execFileAsync(command, ["--version"], { maxBuffer: 1024 * 1024 });
158 + return command;
159 + } catch {}
161 + return undefined;
164 +async 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);
173 + throw new Error("Chrome CDP tab not available");
176 +async 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 + };
203 +main().catch((err) => {
204 + console.error(err);
205 + process.exit(1);
206 +});

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

Modified
6 6 target: "browser";
7 7 minify: boolean;
8 8 sourcemap: "none";
9 + splitting?: boolean;
9 10 naming: { entry: string; chunk: string; asset: string };
10 11 }): Promise<{ success: boolean; logs: unknown[] }>;
30 31 target: "browser",
31 32 minify: true,
32 33 sourcemap: "none",
34 + splitting: true,
33 35 naming: {
34 36 entry: "app.[ext]",
35 37 chunk: "assets/[name]-[hash].[ext]",

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

Modified
129 129 line.dispatchEvent(new MouseEvent('click', { bubbles: true, composed: true, clientX: 900, clientY: y }));
130 130 await wait(200);
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);
134 135 const comment = must('#comment');
135 136 comment.value = commentText;
136 137 comment.dispatchEvent(new Event('input', { bubbles: true }));
141 142 await document.fonts.ready;
142 - const shadowRoot = must('diffs-container').shadowRoot;
143 - const addLine1 = must('[data-additions] [data-line="1"]', shadowRoot);
144 - const addLine2 = must('[data-additions] [data-line="2"]', shadowRoot);
145 143 const themeMode = must('#theme-mode');
146 144 themeMode.value = 'light';
147 145 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);
151 149 must('.remove-finding').click();
152 150 await wait(200);
157 155 const result = {
158 156 findingsText: must('#findings').innerText,
159 157 failedResources,
160 - fontLoaded: document.fonts.check('12px "Nugu Code Nerd"'),
158 + fontLoaded: document.fonts.check('12px "JetBrains Mono Nerd"'),
161 159 theme: document.documentElement.dataset.theme,
163 161 must('#submit').click();
175 173 if (!isRecord(value)) throw new Error("browser smoke returned invalid result");
176 174 if (typeof value.findingsText !== "string") throw new Error("browser smoke missing findings text");
177 175 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");
179 177 if (value.theme !== "light") throw new Error("theme selector did not apply light mode");
180 178 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
3 3 import { randomBytes, randomUUID } from "node:crypto";
4 4 import { createReadStream } from "node:fs";
5 5 import { stat } from "node:fs/promises";
6 6 import { createServer, type IncomingMessage, type Server, type ServerResponse } from "node:http";
7 7 import { extname, resolve, sep } from "node:path";
8 -import { ANCHOR_CONTEXT_LINES, HEARTBEAT_CHECK_INTERVAL_MS, HEARTBEAT_LOST_MS, REQUEST_BODY_MAX_BYTES, TOKEN_COOKIE } from "./constants.js";
8 +import { ANCHOR_CONTEXT_LINES, HEARTBEAT_CHECK_INTERVAL_MS, HEARTBEAT_LOST_MS, REQUEST_BODY_MAX_BYTES, REVIEW_PORT, TOKEN_COOKIE } from "./constants.js";
9 9 import { staticDir } from "./bundle.js";
10 10 import type { BrowserResult, CollectedDiff, Finding, FindingDraft, ReviewCategory, ReviewPayload, ReviewSeverity, ReviewSide, ReviewState } from "./types.js";
19 19 diff: CollectedDiff;
20 20 state: ReviewState;
21 21 round: number;
22 + token?: string;
22 23 timeoutMs?: number;
23 24 refreshDiff?: () => Promise<CollectedDiff>;
24 25 onSubmit?: (result: Extract<BrowserResult, { type: "submit" }>, diff: CollectedDiff) => Promise<void> | void;
47 48 export async function startReviewServer(options: StartServerOptions): Promise<ReviewServer> {
48 - const token = randomBytes(32).toString("base64url");
49 + const token = options.token ?? randomBytes(32).toString("base64url");
49 50 const id = randomUUID();
50 51 let server: Server;
51 52 let finished = false;
83 84 server = createServer((req, res) => void dispatch(req, res, ctx));
84 85 try {
85 - await listen(server);
86 + await listen(server, REVIEW_PORT);
86 87 } catch (err) {
87 88 clearInterval(heartbeatTimer);
88 89 if (timeoutTimer) clearTimeout(timeoutTimer);
334 335 return !!value && typeof value === "object" && !Array.isArray(value);
337 -function listen(server: Server) {
338 +function listen(server: Server, preferredPort: number) {
338 339 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 + });

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

Modified
1 1 import type { ExtensionContext } from "@mariozechner/pi-coding-agent";
2 2 import { EXTENSION_ID } from "./constants.js";
3 -import type { ReviewRoundEntry, ReviewState } from "./types.js";
3 +import type { ReviewLiveEntry, ReviewRoundEntry, ReviewState } from "./types.js";
5 5 type WritableSessionManager = ExtensionContext["sessionManager"] & {
6 6 appendCustomEntry(customType: string, data?: unknown): string;
10 10 return (ctx.sessionManager as WritableSessionManager).appendCustomEntry(EXTENSION_ID, data);
13 +export function appendLiveReview(ctx: ExtensionContext, data: ReviewLiveEntry): string {
14 + return (ctx.sessionManager as WritableSessionManager).appendCustomEntry(EXTENSION_ID, data);
13 17 export function restoreReviewState(ctx: ExtensionContext): ReviewState {
14 18 const rounds: ReviewRoundEntry[] = [];
19 + let live: ReviewLiveEntry | undefined;
15 20 for (const entry of ctx.sessionManager.getBranch()) {
16 21 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;
20 27 return {
21 28 round: Math.max(0, ...rounds.map((round) => round.round)),
22 29 findings: rounds.flatMap((round) => round.findings),
23 30 rounds,
31 + ...(live && { live }),

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

Deleted
deleted file mode 100644
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/assets/JetBrainsMonoNuguCode-e77247bx.woff2

Deleted
deleted file mode 100644

Previous version contains binary or non-UTF-8 data.

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

Deleted
deleted file mode 100644
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
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 -}

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

Modified
46 46 createdAt: string;
49 +export 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 +};
49 65 export type ReviewState = {
50 66 round: number;
51 67 findings: Finding[];
52 68 rounds: ReviewRoundEntry[];
69 + live?: ReviewLiveEntry;
55 72 export type DiffFileStatus = "added" | "modified" | "deleted" | "renamed" | "binary";