Open History to see the last commit
1import type { CodeViewItem, DiffLineAnnotation, SelectedLineRange } from "@pierre/diffs";
2import type { CodeViewDiffItem, CodeViewHandle } from "@pierre/diffs/react";
3import type {
4 EnvironmentId,
5 PullRequestDetailView,
6 PullRequestDiffSide,
7 PullRequestOmittedFileStat,
8 PullRequestRef,
9 PullRequestReviewPosition,
10 PullRequestReviewThread,
11 PullRequestThreadCommentsResult,
12} from "@t3tools/contracts";
13import {
14 ChevronDownIcon,
15 ChevronRightIcon,
16 ChevronsDownUpIcon,
17 ChevronsUpDownIcon,
18 Columns2Icon,
19 FolderTreeIcon,
20 MessageSquareIcon,
21 MessageSquareOffIcon,
22 Rows3Icon,
23 TextWrapIcon,
24 TriangleAlertIcon,
25 XIcon,
26} from "lucide-react";
27import { useAtomRefresh } from "@effect/atom-react";
28import * as Schema from "effect/Schema";
29import { useCallback, useEffect, useMemo, useRef, useState, type ReactNode } from "react";
30
31import { useLocalStorage } from "~/hooks/useLocalStorage";
32import { useClientSettings, useUpdateClientSettings } from "~/hooks/useSettings";
33import { useTheme } from "~/hooks/useTheme";
34import { areAllDiffFilesCollapsed } from "~/lib/diffCollapse";
35import { pullRequestFindingKey, type PullRequestFinding } from "./pullRequestDetail.logic";
36import { canEditPullRequestComment } from "./pullRequestEditing.logic";
37import { orderDiffFiles } from "./pullRequestFileOrder.logic";
38import {
39 buildFileDiffRenderKey,
40 fnv1a32,
41 getDiffLineStat,
42 getRenderablePatch,
43 resolveDiffThemeName,
44 resolveFileDiffPath,
45 resolveFileDiffPreviousPath,
46 type RenderablePatch,
47} from "~/lib/diffRendering";
48import { PREFERRED_HIGHLIGHTER } from "~/lib/syntaxHighlighting";
49import { cn } from "~/lib/utils";
50import { createPullRequestDiffFileContentsLoader } from "~/lib/diffFileContents";
51import {
52 buildDiffReviewComment,
53 resolveDiffReviewPosition,
54 type ReviewCommentContext,
55} from "~/reviewCommentContext";
56import { pullRequestEnvironment } from "~/state/pullRequests";
57import { useEnvironmentQuery } from "~/state/query";
58import { useAtomCommand } from "~/state/use-atom-command";
59
60import { DiffPanelLoadingState } from "../DiffPanelShell";
61import { DiffWorkerPoolProvider } from "../DiffWorkerPoolProvider";
62import { DiffCommentAnnotation } from "../diffs/DiffCommentAnnotation";
63import { DiffFileTree } from "../diffs/DiffFileTree";
64import { diffFileTreeEntries } from "../diffs/diffFileTree.logic";
65import { StyledDiffCodeView } from "../diffs/StyledDiffCodeView";
66import { Button } from "../ui/button";
67import { Collapsible, CollapsiblePanel, CollapsibleTrigger } from "../ui/collapsible";
68import {
69 DropdownMenu,
70 DropdownMenuContent,
71 DropdownMenuItem,
72 DropdownMenuTrigger,
73} from "../ui/menu";
74import { toastManager } from "../ui/toast";
75import { Toggle, ToggleGroup } from "../ui/toggle-group";
76import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";
77import { PendingReviewCommentCard, ReviewThreadCard } from "./PullRequestReviewAnnotation";
78import { PullRequestReviewBar } from "./PullRequestReviewBar";
79import {
80 isFileDiffCollapsed,
81 isLineInFileDiff,
82 type DiffFoldOverride,
83} from "./pullRequestDiff.logic";
84import { PullRequestDiffStat, PullRequestMetaLine } from "./pullRequestPresentation";
85import {
86 nextPendingReviewCommentId,
87 pullRequestReviewKey,
88 usePendingReviewComments,
89 usePullRequestReviewStore,
90 type PendingReviewComment,
91} from "./pullRequestReviewStore";
92
93/** Everything pinned to one line of one file: what is already there, and what is being added. */
94interface ReviewAnnotationGroup {
95 readonly threads: ReadonlyArray<PullRequestReviewThread>;
96 readonly pending: ReadonlyArray<PendingReviewComment>;
97 readonly draft: boolean;
98}
99
100type ReviewAnnotation = DiffLineAnnotation<ReviewAnnotationGroup>;
101
102/** Commits per press of "Show more" in the scope menu. */
103const COMMIT_PAGE_SIZE = 10;
104
105const PULL_REQUEST_FILE_TREE_STORAGE_KEY = "t3code.pullRequestFileTreeOpen";
106
107/** One answer from the host: a whole number of files, and where the next one carries on. */
108interface DiffSlice {
109 /** What was asked for, null being the first slice. Identifies the slice among the loaded ones. */
110 readonly cursor: string | null;
111 readonly patch: string;
112 readonly truncated: boolean;
113 readonly nextCursor: string | null;
114 readonly omittedFileStats: ReadonlyArray<PullRequestOmittedFileStat>;
115}
116
117/**
118 * The viewer's own per-file counts are hidden and drawn from this side of its shadow root
119 * instead: its counts are hunk sums, and a file whose hunks the host withheld would read as
120 * an empty change rather than as the counts the host did report.
121 */
122const REPLACE_FILE_COUNTS_CSS = `
123[data-diffs-header] [data-additions-count],
124[data-diffs-header] [data-deletions-count] {
125 display: none !important;
126}`;
127
128/** Nothing loaded yet, as one identity, so the memos below do not see a new array every render. */
129const NO_SLICES: ReadonlyArray<DiffSlice> = [];
130
131/** A group while it is still gathering what belongs on its line. */
132interface MutableAnnotationGroup {
133 readonly side: PullRequestDiffSide;
134 readonly line: number;
135 readonly threads: PullRequestReviewThread[];
136 readonly pending: PendingReviewComment[];
137 draft: boolean;
138}
139
140interface DraftAnchor {
141 readonly fileKey: string;
142 readonly path: string;
143 /** What the file was called before the change, for the hosts that resolve a position by both. */
144 readonly oldPath: string | null;
145 readonly position: PullRequestReviewPosition;
146 /** The whole selection, which the comment collapses to one line but a question keeps. */
147 readonly range: SelectedLineRange;
148}
149
150/** A range of the diff and the reader's request for the agent. */
151export interface PullRequestAgentSelectionInput {
152 /** The marked lines, already in the shape the composer draws and the agent reads. */
153 readonly comment: ReviewCommentContext;
154 readonly request: string;
155}
156
157/** The contract's sides named the way the diff viewer names them, and back again. */
158function toViewerSide(side: PullRequestDiffSide) {
159 return side === "left" ? ("deletions" as const) : ("additions" as const);
160}
161
162function getReviewPositionAnchor(position: PullRequestReviewPosition): {
163 line: number;
164 side: PullRequestDiffSide;
165} {
166 switch (position.kind) {
167 case "added":
168 return { line: position.newLine, side: "right" };
169 case "deleted":
170 return { line: position.oldLine, side: "left" };
171 case "context":
172 return {
173 line: position.side === "left" ? position.oldLine : position.newLine,
174 side: position.side,
175 };
176 }
177}
178
179/**
180 * Whether the viewer draws this line at all. A line counts the new file on the right and the old
181 * one on the left, and each hunk covers one run of each; a line outside every run — a
182 * conversation the host could not mark outdated, or one under a hunk it withheld — has no row to
183 * be pinned to, however much its file looks like a match.
184 */
185/**
186 * The pull request's patch, with the review written against it. Conversations already on the
187 * host sit under the line they were written on, and a new comment joins the review being
188 * drafted rather than being posted as it is typed.
189 */
190export function PullRequestCodeTab({
191 environmentId,
192 reference,
193 detail,
194 selectedCommitOid,
195 onSelectedCommitChange,
196 pendingFinding,
197 fixFindingLabel = "Fix in a thread",
198 onFixFinding,
199 onAddToAgentSelection,
200 onRefresh,
201 refreshToken = 0,
202}: {
203 environmentId: EnvironmentId;
204 reference: PullRequestRef;
205 detail: PullRequestDetailView;
206 /** Commit whose diff is open. Null keeps the whole pull-request diff selected. */
207 selectedCommitOid: string | null;
208 onSelectedCommitChange: (oid: string | null) => void;
209 /** The hand-off currently preparing, if any, so only the finding it belongs to says so. */
210 pendingFinding?: string | null;
211 fixFindingLabel?: string;
212 onFixFinding?: (finding: PullRequestFinding) => void;
213 /** Absent where there is no active agent composer to receive a local comment. */
214 onAddToAgentSelection?: (input: PullRequestAgentSelectionInput) => void;
215 onRefresh: () => void;
216 /** Bumped by the panel's refresh button: drop the accumulated pages and re-read the diff. */
217 refreshToken?: number;
218}) {
219 const { resolvedTheme } = useTheme();
220 const settings = useClientSettings();
221 const [toggledFiles, setToggledFiles] = useState<ReadonlySet<string>>(() => new Set());
222 // A change of any size can carry hundreds of commits, and a menu that long is a scroll rather
223 // than a choice. The rest arrive ten at a time, on request.
224 const [visibleCommitCount, setVisibleCommitCount] = useState(COMMIT_PAGE_SIZE);
225 /** Set once the reader has asked for every file at once, until they pick a file apart again. */
226 const [foldOverride, setFoldOverride] = useState<DiffFoldOverride>(null);
227 const diffLayout = settings.diffLayout;
228 const updateClientSettings = useUpdateClientSettings();
229 const [wordWrap, setWordWrap] = useState(settings.wordWrap);
230 const [fileTreeOpen, setFileTreeOpen] = useLocalStorage(
231 PULL_REQUEST_FILE_TREE_STORAGE_KEY,
232 false,
233 Schema.Boolean,
234 );
235 const [selectedLines, setSelectedLines] = useState<{
236 id: string;
237 range: SelectedLineRange;
238 } | null>(null);
239 const [draft, setDraft] = useState<DraftAnchor | null>(null);
240 const [threadPending, setThreadPending] = useState(false);
241 const [orphansOpen, setOrphansOpen] = useState(false);
242 // Closed by default so the review form does not permanently eat vertical space below the
243 // diff; opened on demand as a floating overlay instead.
244 const [reviewOpen, setReviewOpen] = useState(false);
245 // Which pull request the slices belong to travels with them, so a render taken before the
246 // reset below cannot read the previous one's slices — or send its cursor to the host.
247 const [sliceState, setSliceState] = useState<{
248 readonly key: string;
249 readonly cursor: string | null;
250 readonly slices: ReadonlyArray<DiffSlice>;
251 }>({ key: "", cursor: null, slices: NO_SLICES });
252 const parseCache = useRef(new Map<string, RenderablePatch>());
253 const viewerRef = useRef<CodeViewHandle<ReviewAnnotationGroup> | null>(null);
254
255 const referenceKey = pullRequestReviewKey(reference);
256 const commit = selectedCommitOid;
257 // One commit's own changes and the whole change are two different diffs, paged separately, so
258 // everything below is keyed by both.
259 const scopeKey = commit === null ? referenceKey : `${referenceKey}@${commit}`;
260 // The panel keeps this mounted across pull requests, so an open composer would otherwise
261 // survive the switch and attach its comment to whichever one is on screen when it is sent.
262 useEffect(() => {
263 setDraft(null);
264 setSelectedLines(null);
265 setToggledFiles(new Set());
266 setFoldOverride(null);
267 setVisibleCommitCount(COMMIT_PAGE_SIZE);
268 setOrphansOpen(false);
269 setSliceState({ key: scopeKey, cursor: null, slices: NO_SLICES });
270 parseCache.current.clear();
271 }, [scopeKey]);
272
273 const loadedSlices = sliceState.key === scopeKey ? sliceState.slices : NO_SLICES;
274 const cursor = sliceState.key === scopeKey ? sliceState.cursor : null;
275 const diffQuery = useEnvironmentQuery(
276 pullRequestEnvironment.diff({
277 environmentId,
278 input: {
279 ...reference,
280 ...(cursor === null ? {} : { cursor }),
281 ...(commit === null ? {} : { commit }),
282 },
283 }),
284 );
285 // Each answer is kept as its own slice. Concatenating the patches and re-parsing the growing
286 // text would cost more with every slice, which is the wall the slicing exists to remove.
287 useEffect(() => {
288 const data = diffQuery.data;
289 if (data === null) return;
290 setSliceState((previous) => {
291 const slices = previous.key === scopeKey ? previous.slices : NO_SLICES;
292 const next = {
293 cursor,
294 patch: data.patch,
295 truncated: data.truncated,
296 nextCursor: data.nextCursor,
297 omittedFileStats: data.omittedFileStats ?? [],
298 };
299 const index = slices.findIndex((slice) => slice.cursor === cursor);
300 if (index === -1) {
301 return { key: scopeKey, cursor, slices: [...slices, next] };
302 }
303 const existing = slices[index];
304 if (
305 existing !== undefined &&
306 existing.patch === next.patch &&
307 existing.truncated === next.truncated &&
308 existing.nextCursor === next.nextCursor &&
309 existing.omittedFileStats.length === next.omittedFileStats.length &&
310 existing.omittedFileStats.every((file, index) => {
311 const refreshed = next.omittedFileStats[index];
312 return (
313 refreshed !== undefined &&
314 refreshed.path === file.path &&
315 refreshed.additions === file.additions &&
316 refreshed.deletions === file.deletions
317 );
318 })
319 ) {
320 return previous;
321 }
322 // A page that came back different means the diff moved under the review. The slices
323 // after it go with the replacement: their cursors were positions in the old diff.
324 return { key: scopeKey, cursor, slices: [...slices.slice(0, index), next] };
325 });
326 }, [cursor, diffQuery.data, scopeKey]);
327 // The refresh button rereads from the first page rather than the page the reader is on:
328 // pages are positions in one snapshot of the diff, and a fresh snapshot starts over.
329 const refreshFirstDiffPage = useAtomRefresh(
330 pullRequestEnvironment.diff({
331 environmentId,
332 input: { ...reference, ...(commit === null ? {} : { commit }) },
333 }),
334 );
335 const appliedRefreshToken = useRef(refreshToken);
336 useEffect(() => {
337 if (appliedRefreshToken.current === refreshToken) return;
338 appliedRefreshToken.current = refreshToken;
339 setSliceState({ key: scopeKey, cursor: null, slices: NO_SLICES });
340 refreshFirstDiffPage();
341 }, [refreshToken, scopeKey, refreshFirstDiffPage]);
342 const reviewKey = referenceKey;
343 const pendingComments = usePendingReviewComments(reference);
344 const addComment = usePullRequestReviewStore((store) => store.addComment);
345 const removeComment = usePullRequestReviewStore((store) => store.removeComment);
346 const replyToThread = useAtomCommand(pullRequestEnvironment.replyToThread, {
347 reportFailure: false,
348 });
349 const setThreadResolution = useAtomCommand(pullRequestEnvironment.setThreadResolution, {
350 reportFailure: false,
351 });
352 const updateComment = useAtomCommand(pullRequestEnvironment.updateComment, {
353 reportFailure: false,
354 });
355 const loadThreadComments = useAtomCommand(pullRequestEnvironment.threadComments, {
356 reportFailure: false,
357 });
358 const getDiffFileContents = useAtomCommand(pullRequestEnvironment.diffFileContents);
359 const loadDiffFiles = useMemo(
360 () =>
361 createPullRequestDiffFileContentsLoader(getDiffFileContents, {
362 environmentId,
363 reference,
364 commit,
365 cacheKey: `pull-request:${referenceKey}:${detail.updatedAt}:${commit ?? "all"}`,
366 }),
367 [commit, detail.updatedAt, environmentId, getDiffFileContents, reference, referenceKey],
368 );
369
370 // What is offered is the intersection of two different questions: what this host can do at
371 // all, and what this account may do on this repository. Either one saying no means a control
372 // that would only ever end in a refusal.
373 const review = useMemo(() => {
374 const hostReview = detail.capabilities.review;
375 const viewer = detail.viewerPermissions;
376 return {
377 inlineComment: hostReview.inlineComment && viewer.comment,
378 reply: hostReview.reply && viewer.comment,
379 resolve: hostReview.resolve && viewer.resolve,
380 verdicts: hostReview.verdicts.filter((verdict) => viewer.verdicts.includes(verdict)),
381 };
382 }, [detail.capabilities.review, detail.viewerPermissions]);
383 // A comment is posted against the pull request's head diff, so a line number taken from one
384 // commit's own diff would land somewhere else entirely. Commenting waits for the whole change.
385 const canCommentOnLines = review.inlineComment && commit === null;
386 // Every slice is parsed on its own and the result held, so a slice arriving costs one parse
387 // rather than one per slice already on screen. Its cache key carries the theme, which is what
388 // the tokenizer caches against, so a theme change is still a fresh parse.
389 const parsedSlices = useMemo(
390 () =>
391 loadedSlices.map((slice) => {
392 // The patch's own hash is part of the key: a refreshed page reuses its cursor, and a
393 // key of position alone would keep handing back the parse of the patch it replaced.
394 const cacheKey = `pull-request:${scopeKey}:${resolvedTheme}:${slice.cursor ?? "first"}:${fnv1a32(slice.patch)}`;
395 const cached = parseCache.current.get(cacheKey);
396 if (cached) return cached;
397 const parsed = getRenderablePatch(slice.patch, cacheKey, {
398 compactPartialHunkOffsets: true,
399 });
400 if (parsed) parseCache.current.set(cacheKey, parsed);
401 return parsed;
402 }),
403 [loadedSlices, resolvedTheme, scopeKey],
404 );
405 // Ordered within a slice rather than across them: ordering the accumulated set would let a late
406 // slice push a file the reader is part way through further down the page.
407 const files = useMemo(
408 () =>
409 parsedSlices.flatMap((parsed) =>
410 parsed?.kind === "files" ? orderDiffFiles(parsed.files) : [],
411 ),
412 [parsedSlices],
413 );
414 const nextCursor = loadedSlices.at(-1)?.nextCursor ?? null;
415 // What a slice withheld: the host declining to inline part of it, or a patch the viewer could
416 // not structure and so dropped. Neither says anything about there being more to fetch.
417 const withheldContent =
418 loadedSlices.some((slice) => slice.truncated) ||
419 parsedSlices.some((parsed) => parsed?.kind === "raw");
420
421 // Placing a conversation takes more than its file being in the diff: its line has to fall
422 // inside a hunk that was rendered. One that does not is drawn nowhere, so it belongs in the
423 // off-diff list rather than disappearing between the two.
424 const placedThreadIds = useMemo(() => {
425 const placed = new Set<string>();
426 // A commit's diff counts lines within that commit; a review comment is anchored to the
427 // pull request's head diff. Pinning one onto the other would put the remark against
428 // whichever code happens to hold that line number in this commit, so while a commit is on
429 // screen every conversation is listed rather than placed.
430 if (commit !== null) return placed;
431 for (const file of files) {
432 const path = resolveFileDiffPath(file);
433 for (const thread of detail.reviewThreads) {
434 if (
435 thread.path === path &&
436 thread.line !== null &&
437 isLineInFileDiff(file, thread.side, thread.line)
438 ) {
439 placed.add(thread.id);
440 }
441 }
442 }
443 return placed;
444 }, [commit, detail.reviewThreads, files]);
445
446 const items = useMemo<CodeViewDiffItem<ReviewAnnotationGroup>[]>(
447 () =>
448 files.map((fileDiff) => {
449 const fileKey = buildFileDiffRenderKey(fileDiff);
450 const path = resolveFileDiffPath(fileDiff);
451 // One annotation per line, so a line that already carries a conversation shows a new
452 // comment underneath it rather than in place of it.
453 const groups = new Map<string, MutableAnnotationGroup>();
454 const groupAt = (side: PullRequestDiffSide, line: number) => {
455 const key = `${side}:${line}`;
456 const existing = groups.get(key);
457 if (existing) return existing;
458 const created: MutableAnnotationGroup = {
459 side,
460 line,
461 threads: [],
462 pending: [],
463 draft: false,
464 };
465 groups.set(key, created);
466 return created;
467 };
468
469 for (const thread of detail.reviewThreads) {
470 if (thread.path !== path || thread.line === null) continue;
471 if (!placedThreadIds.has(thread.id)) continue;
472 groupAt(thread.side, thread.line).threads.push(thread);
473 }
474 // Pending comments anchor to the head diff exactly like host threads do, so a
475 // commit's diff must not place them either — the same line means other code there.
476 if (commit === null) {
477 for (const comment of pendingComments) {
478 if (comment.path !== path) continue;
479 const anchor = getReviewPositionAnchor(comment.position);
480 groupAt(anchor.side, anchor.line).pending.push(comment);
481 }
482 }
483 if (draft?.fileKey === fileKey) {
484 const anchor = getReviewPositionAnchor(draft.position);
485 groupAt(anchor.side, anchor.line).draft = true;
486 }
487
488 const collapsed = isFileDiffCollapsed(fileKey, foldOverride, toggledFiles);
489
490 const annotations: ReviewAnnotation[] = [...groups.values()].map((group) => ({
491 side: toViewerSide(group.side),
492 lineNumber: group.line,
493 metadata: { threads: group.threads, pending: group.pending, draft: group.draft },
494 }));
495 return {
496 id: fileKey,
497 type: "diff" as const,
498 fileDiff,
499 annotations,
500 collapsed,
501 // The viewer re-renders an item only when its version changes, so everything the
502 // annotations show has to be part of it.
503 version: fnv1a32(
504 `${collapsed ? "1" : "0"}:${annotations
505 .map(
506 ({ side, lineNumber, metadata }) =>
507 `${side}:${lineNumber}:${metadata.draft ? "d" : ""}:${metadata.pending
508 .map((comment) => `${comment.id}:${comment.body}`)
509 .join(",")}:${metadata.threads
510 .map(
511 (thread) =>
512 `${thread.id}:${thread.isResolved ? "r" : ""}:${
513 thread.isOutdated ? "o" : ""
514 }:${thread.comments
515 .map(
516 (comment) =>
517 `${comment.id}:${comment.author?.login ?? ""}:${comment.createdAt}:${comment.body}:${(
518 comment.reactions ?? []
519 )
520 .map(
521 (r) => `${r.content}:${r.count}:${r.viewerHasReacted ? "v" : ""}`,
522 )
523 .join(",")}`,
524 )
525 .join(";")}`,
526 )
527 .join(",")}`,
528 )
529 .join("|")}`,
530 ),
531 };
532 }),
533 [
534 commit,
535 detail.reviewThreads,
536 draft,
537 files,
538 foldOverride,
539 pendingComments,
540 placedThreadIds,
541 toggledFiles,
542 ],
543 );
544 const lineStat = useMemo(() => getDiffLineStat(files), [files]);
545 const omittedFileStats = useMemo(
546 () =>
547 new Map(
548 loadedSlices.flatMap((slice) =>
549 slice.omittedFileStats.map((file) => [file.path, file] as const),
550 ),
551 ),
552 [loadedSlices],
553 );
554 const fileKeys = useMemo(() => items.map((item) => item.id), [items]);
555 const collapsedFileKeys = useMemo(
556 () => new Set(items.filter((item) => item.collapsed === true).map((item) => item.id)),
557 [items],
558 );
559 const allFilesCollapsed = areAllDiffFilesCollapsed(fileKeys, collapsedFileKeys);
560 const fileTreeEntries = useMemo(() => diffFileTreeEntries(files), [files]);
561
562 // A failed slice must not be asked for again on its own. The files already loaded keep the
563 // sentinel on screen, so re-arming it after a failure would request the same slice forever.
564 const canLoadNextSlice =
565 nextCursor !== null &&
566 nextCursor !== cursor &&
567 !diffQuery.isPending &&
568 diffQuery.error === null;
569 const loadNextSlice = useCallback(() => {
570 if (nextCursor === null) return;
571 setSliceState((previous) => ({ ...previous, cursor: nextCursor }));
572 }, [nextCursor]);
573
574 // The sentinel is held as state rather than a ref because the viewer mounts its own footer:
575 // an effect reading a ref could run before that node exists and would never arm the observer.
576 const [sentinel, setSentinel] = useState<HTMLDivElement | null>(null);
577 useEffect(() => {
578 if (sentinel === null || !canLoadNextSlice) return;
579 const observer = new IntersectionObserver(
580 (observed) => {
581 if (observed.some((entry) => entry.isIntersecting)) loadNextSlice();
582 },
583 // Start the next slice slightly before the sentinel is on screen.
584 { rootMargin: "240px" },
585 );
586 observer.observe(sentinel);
587 return () => observer.disconnect();
588 }, [canLoadNextSlice, loadNextSlice, sentinel]);
589
590 // A stable identity: the viewer's SlotPortals memoizes each file's header/annotation portal on
591 // these render props, so a fresh function here would recreate every visible file's portal on
592 // every tab re-render (a line-selection drag, a keystroke in the draft, a review-store update).
593 const toggleFile = useCallback(
594 (fileKey: string) =>
595 setToggledFiles((current) => {
596 // The override becomes this file's new default the moment it is folded into the set below,
597 // so nothing has to be re-derived when the reader goes back to choosing one at a time.
598 const next = new Set(current);
599 if (next.has(fileKey)) next.delete(fileKey);
600 else next.add(fileKey);
601 return next;
602 }),
603 [],
604 );
605
606 // Held as state so the scroll runs after a folded file has been drawn open; scrolling in the
607 // same tick would land on the folded header's position.
608 const [treeReveal, setTreeReveal] = useState<{ fileKey: string; id: number } | null>(null);
609 useEffect(() => {
610 if (treeReveal === null) return;
611 viewerRef.current?.scrollTo({ type: "item", id: treeReveal.fileKey, align: "start" });
612 }, [treeReveal]);
613 const revealFile = useCallback(
614 (path: string) => {
615 const item = items.find((candidate) => resolveFileDiffPath(candidate.fileDiff) === path);
616 if (item === undefined) return;
617 if (item.collapsed === true) toggleFile(item.id);
618 setTreeReveal((current) => ({ fileKey: item.id, id: (current?.id ?? 0) + 1 }));
619 },
620 [items, toggleFile],
621 );
622
623 const toggleAllFiles = () => {
624 // Held as an override of the default rather than as the file keys on screen: a diff that is
625 // still paging would otherwise bring its next slice in folded, moments after the reader
626 // asked for everything to be open.
627 setFoldOverride(areAllDiffFilesCollapsed(fileKeys, collapsedFileKeys) ? "expanded" : "folded");
628 setToggledFiles(new Set());
629 };
630
631 // Newest first: the last commit is the one a reader coming back to a change is looking for.
632 const orderedCommits = useMemo(
633 () =>
634 // By instant, not by the text: GitLab keeps a commit's own UTC offset, so two commits
635 // from different zones would sort by how they were written rather than when they landed.
636 detail.commits.toSorted(
637 (left, right) => Date.parse(right.committedDate) - Date.parse(left.committedDate),
638 ),
639 [detail.commits],
640 );
641
642 const beginComment = useCallback(
643 (range: SelectedLineRange | null, context: { item: CodeViewItem<ReviewAnnotationGroup> }) => {
644 if (!range || !canCommentOnLines) return;
645 const item = context.item;
646 if (item.type !== "diff") return;
647 const file = files.find((candidate) => buildFileDiffRenderKey(candidate) === item.id);
648 if (!file) return;
649 // A range collapses to its last line: only GitHub carries a multi-line comment, and one
650 // that silently lost its first line on the other hosts would be worse than one line.
651 const path = resolveFileDiffPath(file);
652 const previousPath = resolveFileDiffPreviousPath(file);
653 const position = resolveDiffReviewPosition(file, range.end, range.endSide ?? range.side);
654 if (position === null) return;
655 setDraft({
656 fileKey: item.id,
657 path,
658 oldPath: previousPath === path ? null : previousPath,
659 position,
660 range,
661 });
662 },
663 [canCommentOnLines, files],
664 );
665
666 // Built here because the parsed diff only lives here, and built by the same function the
667 // thread panel's own line selection uses — the gesture is the same one, so a second reading of
668 // the hunks would only be a second place for it to drift.
669 const finishSelection = useCallback(
670 (anchor: DraftAnchor, text: string, onFinish: (comment: ReviewCommentContext) => void) => {
671 const file = files.find((candidate) => buildFileDiffRenderKey(candidate) === anchor.fileKey);
672 const comment =
673 file === undefined
674 ? null
675 : buildDiffReviewComment({
676 id: `pull-request-selection:${anchor.fileKey}:${anchor.range.start}:${anchor.range.end}`,
677 sectionId: `pull-request:${detail.number}`,
678 sectionTitle: `PR #${detail.number} review`,
679 filePath: anchor.path,
680 fileDiff: file,
681 range: anchor.range,
682 text,
683 });
684 setDraft(null);
685 setSelectedLines(null);
686 if (comment !== null) onFinish(comment);
687 },
688 [detail.number, files],
689 );
690
691 // The viewer's SlotPortals memoizes each visible file's header/annotation portal on these
692 // render props and on `options` below; a fresh identity on any of them — as a plain inline
693 // function or object literal would be — invalidates that memo and recreates every portal on
694 // screen on any tab re-render (a drag-selection, a keystroke in the draft, a review-store
695 // update), which is the jank this file is otherwise clean of.
696 const renderCodeViewFooter = useCallback(
697 () =>
698 // Only while something is still owed. A finished diff whose query fails on a later
699 // refresh — a reconnect re-runs every one of them — is whole on screen already, and
700 // saying otherwise sends the reader looking for files that are all there.
701 nextCursor === null ? null : (
702 <div
703 ref={setSentinel}
704 className="flex items-center justify-center gap-2 py-2 text-xs text-muted-foreground"
705 >
706 {diffQuery.error !== null ? (
707 <>
708 <span>The rest of this diff could not be loaded.</span>
709 <Button size="xs" variant="outline" onClick={() => diffQuery.refresh()}>
710 Retry
711 </Button>
712 </>
713 ) : diffQuery.isPending ? (
714 "Loading more files..."
715 ) : null}
716 </div>
717 ),
718 [nextCursor, diffQuery.error, diffQuery.isPending, diffQuery.refresh],
719 );
720
721 const renderHeaderPrefix = useCallback(
722 (item: CodeViewItem<ReviewAnnotationGroup>) => {
723 // The item the viewer is drawing already carries the state the memo settled on, so the
724 // chevron follows it rather than recomputing the default here.
725 const collapsed = item.collapsed === true;
726 return (
727 <Button
728 size="icon-micro"
729 variant="ghost-muted"
730 aria-expanded={!collapsed}
731 aria-label={collapsed ? "Expand diff" : "Collapse diff"}
732 className="mr-1 rounded hover:bg-transparent"
733 onClick={(event) => {
734 event.stopPropagation();
735 toggleFile(item.id);
736 }}
737 >
738 {collapsed ? (
739 <ChevronRightIcon className="size-4" />
740 ) : (
741 <ChevronDownIcon className="size-4" />
742 )}
743 </Button>
744 );
745 },
746 [toggleFile],
747 );
748
749 const renderHeaderMetadata = useCallback(
750 (item: CodeViewItem<ReviewAnnotationGroup>) => {
751 if (item.type !== "diff") return null;
752 let additions = 0;
753 let deletions = 0;
754 for (const hunk of item.fileDiff.hunks) {
755 additions += hunk.additionLines;
756 deletions += hunk.deletionLines;
757 }
758 if (additions === 0 && deletions === 0) {
759 const withheld = omittedFileStats.get(resolveFileDiffPath(item.fileDiff));
760 if (withheld) ({ additions, deletions } = withheld);
761 }
762 return (
763 <PullRequestDiffStat
764 additions={additions}
765 deletions={deletions}
766 className="font-mono text-[11px]"
767 />
768 );
769 },
770 [omittedFileStats],
771 );
772
773 const diffViewOptions = useMemo(
774 () => ({
775 diffStyle: diffLayout === "split" ? ("split" as const) : ("unified" as const),
776 lineDiffType: "none" as const,
777 overflow: wordWrap ? ("wrap" as const) : ("scroll" as const),
778 theme: resolveDiffThemeName(resolvedTheme),
779 preferredHighlighter: PREFERRED_HIGHLIGHTER,
780 themeType: resolvedTheme,
781 stickyHeaders: true,
782 loadDiffFiles,
783 enableGutterUtility: canCommentOnLines && draft === null,
784 enableLineSelection: canCommentOnLines && draft === null,
785 // Two gestures reach the same place: dragging the line numbers selects a range, and the
786 // gutter's own button comments on the one line it sits on. They are separate callbacks in
787 // the viewer, so a reader who only ever presses the button gets nothing unless both are
788 // wired.
789 onGutterUtilityClick: beginComment,
790 onLineSelectionEnd: beginComment,
791 }),
792 [diffLayout, wordWrap, resolvedTheme, loadDiffFiles, canCommentOnLines, draft, beginComment],
793 );
794
795 const runThreadCommand = useCallback(
796 async (label: string, run: () => Promise<{ readonly _tag: string }>): Promise<boolean> => {
797 if (threadPending) return false;
798 setThreadPending(true);
799 const result = await run();
800 setThreadPending(false);
801 if (result._tag === "Failure") {
802 toastManager.add({ type: "error", title: label });
803 return false;
804 }
805 onRefresh();
806 return true;
807 },
808 [onRefresh, threadPending],
809 );
810
811 // A conversation is the same card wired to the same commands whether it sits on its line or
812 // was stranded off the diff; only where it is drawn differs.
813 const renderThreadCard = useCallback(
814 (thread: PullRequestReviewThread) => (
815 <ReviewThreadCard
816 // Named with the pull request too: a thread's id is the host's own, and two pull requests
817 // can hand out the same one — which would leave one card's open editor standing over the
818 // other's conversation.
819 key={`${reference.projectId}#${reference.number}:${thread.id}`}
820 thread={thread}
821 workspaceRoot={detail.workspaceRoot}
822 canReply={review.reply}
823 canResolve={review.resolve}
824 canReact={detail.capabilities.reactions === true}
825 environmentId={environmentId}
826 reference={reference}
827 pending={threadPending}
828 fixPending={pendingFinding === pullRequestFindingKey({ kind: "thread", thread })}
829 fixLabel={fixFindingLabel}
830 {...(onFixFinding ? { onFix: () => onFixFinding({ kind: "thread", thread }) } : {})}
831 onLoadMore={async (cursor): Promise<PullRequestThreadCommentsResult | null> => {
832 const result = await loadThreadComments({
833 environmentId,
834 input: { ...reference, threadId: thread.id, cursor },
835 });
836 if (result._tag === "Failure") {
837 toastManager.add({
838 type: "error",
839 title: "More comments could not be loaded",
840 });
841 return null;
842 }
843 return result.value;
844 }}
845 onReply={(body) =>
846 runThreadCommand("Reply could not be posted", () =>
847 replyToThread({
848 environmentId,
849 input: { ...reference, threadId: thread.id, body },
850 }),
851 )
852 }
853 // A conversation on a line is made of review comments, whatever the host filed them as.
854 canEditComment={(comment) =>
855 canEditPullRequestComment(detail, { author: comment.author, kind: "review-comment" })
856 }
857 onEditComment={(commentId, body) =>
858 runThreadCommand("The comment could not be saved", () =>
859 updateComment({
860 environmentId,
861 input: { ...reference, commentId, kind: "review-comment", body },
862 }),
863 )
864 }
865 onToggleResolved={() =>
866 void runThreadCommand("The conversation could not be updated", () =>
867 setThreadResolution({
868 environmentId,
869 input: { ...reference, threadId: thread.id, resolved: !thread.isResolved },
870 }),
871 )
872 }
873 onReacted={onRefresh}
874 />
875 ),
876 [
877 detail,
878 environmentId,
879 fixFindingLabel,
880 loadThreadComments,
881 onRefresh,
882 onFixFinding,
883 pendingFinding,
884 reference,
885 replyToThread,
886 review.reply,
887 review.resolve,
888 runThreadCommand,
889 setThreadResolution,
890 threadPending,
891 updateComment,
892 ],
893 );
894
895 const renderAnnotation = useCallback(
896 (annotation: ReviewAnnotation) => (
897 <div className="py-1 font-sans text-foreground">
898 {annotation.metadata.threads.map(renderThreadCard)}
899 {annotation.metadata.pending.map((comment) => (
900 <PendingReviewCommentCard
901 key={comment.id}
902 comment={comment}
903 onRemove={() => removeComment(reviewKey, comment.id)}
904 />
905 ))}
906 {annotation.metadata.draft && draft ? (
907 <DiffCommentAnnotation
908 kind="draft"
909 rangeLabel={`${draft.path}:${getReviewPositionAnchor(draft.position).line}`}
910 text=""
911 submitLabel="Add to review"
912 {...(onAddToAgentSelection
913 ? {
914 secondaryAction: {
915 label: "Add to agent",
916 onAction: (text: string) =>
917 finishSelection(draft, text, (comment) =>
918 onAddToAgentSelection({ comment, request: text }),
919 ),
920 },
921 }
922 : {})}
923 onCancel={() => {
924 setDraft(null);
925 setSelectedLines(null);
926 }}
927 onComment={(body) => {
928 addComment(reviewKey, {
929 id: nextPendingReviewCommentId(),
930 path: draft.path,
931 ...(draft.oldPath === null ? {} : { oldPath: draft.oldPath }),
932 position: draft.position,
933 body,
934 });
935 setDraft(null);
936 setSelectedLines(null);
937 }}
938 />
939 ) : null}
940 </div>
941 ),
942 [
943 addComment,
944 draft,
945 finishSelection,
946 onAddToAgentSelection,
947 removeComment,
948 renderThreadCard,
949 reviewKey,
950 ],
951 );
952
953 /**
954 * The review overlay belongs to the pull request, not to the patch: a change whose diff
955 * cannot be structured — or read at all — is still one a reviewer can approve or reject, so
956 * it survives every branch below. It floats over the scroll area rather than sitting in the
957 * layout flow, so the diff keeps the full height instead of permanently losing a strip to a
958 * footer most reviews never touch. Hidden entirely where the host offers no verdicts, same as
959 * the bar it wraps did.
960 */
961 const reviewOverlay =
962 review.verdicts.length === 0 ? null : (
963 <div className="pointer-events-none absolute inset-x-0 bottom-0 z-10">
964 {reviewOpen ? (
965 <div className="surface-glass pointer-events-auto absolute inset-x-3 bottom-3 rounded-xl border border-border/60 shadow-lg">
966 <Button
967 type="button"
968 size="icon-sm"
969 variant="ghost"
970 aria-label="Close review"
971 className="absolute right-2 top-2"
972 onClick={() => setReviewOpen(false)}
973 >
974 <XIcon className="size-3.5" />
975 </Button>
976 <PullRequestReviewBar
977 environmentId={environmentId}
978 reference={reference}
979 verdicts={review.verdicts}
980 onSubmitted={() => {
981 onRefresh();
982 setReviewOpen(false);
983 }}
984 />
985 </div>
986 ) : (
987 // Bottom-right, clear of the vertical scrollbar the diff view keeps to its own right
988 // edge.
989 <Button
990 className="pointer-events-auto absolute right-4 bottom-3 rounded-full shadow-lg"
991 onClick={() => setReviewOpen(true)}
992 size="compact"
993 variant="glass"
994 >
995 <MessageSquareIcon className="size-3.5" />
996 Review
997 {pendingComments.length > 0 ? (
998 <span className="flex size-4 items-center justify-center rounded-full bg-accent text-[10px] tabular-nums text-accent-foreground">
999 {pendingComments.length}
1000 </span>
1001 ) : null}
1002 </Button>
1003 )}
1004 </div>
1005 );
1006 // A rebase or a force-push can take the scoped commit out of the change. Its diff may still
1007 // be reachable on the host, but it is no longer part of what is being reviewed, so the scope
1008 // goes back to the whole change rather than sitting under a name nothing matches.
1009 //
1010 // Including when the change reports no commits at all: the scope dropdown is the only way back
1011 // to the whole diff and it is not drawn without commits to list, so a scope that outlived them
1012 // would leave the tab reading one obsolete commit with nothing to press.
1013 const selectedCommit = orderedCommits.find((entry) => entry.oid === commit);
1014 useEffect(() => {
1015 if (commit !== null && selectedCommit === undefined) {
1016 onSelectedCommitChange(null);
1017 }
1018 }, [commit, onSelectedCommitChange, selectedCommit]);
1019 const scopeLabel = selectedCommit ? selectedCommit.messageHeadline : "All commits";
1020 /**
1021 * The same controls the thread diff panel carries, in the same order, minus the
1022 * ignore-whitespace toggle: that is `git diff -w` on the server, and no host's pull request
1023 * diff API offers it.
1024 */
1025 const toolbar = (
1026 <div className="flex h-10 min-h-10 shrink-0 items-center justify-between gap-2 border-b border-border/60 bg-background px-4 text-xs text-muted-foreground">
1027 <div className="flex min-w-0 flex-1 items-center gap-3">
1028 {/* A host that reports no commits has nothing to scope by, and a dropdown whose only
1029 entry is the scope already showing is a control that does nothing. */}
1030 {orderedCommits.length > 0 ? (
1031 <DropdownMenu>
1032 <DropdownMenuTrigger
1033 className="inline-flex h-6 max-w-64 items-center gap-1 rounded-md bg-accent px-2 text-xs font-medium text-accent-foreground outline-none transition-colors hover:bg-accent/80 focus-visible:ring-2 focus-visible:ring-ring"
1034 aria-label={`Diff scope: ${scopeLabel}`}
1035 >
1036 <span className="truncate">{scopeLabel}</span>
1037 <ChevronDownIcon className="size-3.5 shrink-0 opacity-70" />
1038 </DropdownMenuTrigger>
1039 <DropdownMenuContent align="start" className="w-80">
1040 <DropdownMenuItem
1041 className={commit === null ? "bg-foreground/[0.08]" : undefined}
1042 onClick={() => onSelectedCommitChange(null)}
1043 >
1044 <span>All commits</span>
1045 </DropdownMenuItem>
1046 {orderedCommits.slice(0, visibleCommitCount).map((entry) => (
1047 <DropdownMenuItem
1048 key={entry.oid}
1049 className={entry.oid === commit ? "bg-foreground/[0.08]" : undefined}
1050 onClick={() => onSelectedCommitChange(entry.oid)}
1051 >
1052 {/* Headlines run long, and the abbreviated oid after one is what a reader
1053 matches against the commit list on the host. */}
1054 <Tooltip>
1055 <TooltipTrigger
1056 render={<span className="min-w-0 truncate">{entry.messageHeadline}</span>}
1057 />
1058 <TooltipPopup side="top">{entry.messageHeadline}</TooltipPopup>
1059 </Tooltip>
1060 <span className="ml-auto shrink-0 font-mono text-xs text-muted-foreground">
1061 {entry.oid.slice(0, 7)}
1062 </span>
1063 </DropdownMenuItem>
1064 ))}
1065 {orderedCommits.length > visibleCommitCount ? (
1066 // Kept out of the radio group: it changes how much of the list is on screen
1067 // rather than what the diff is scoped to.
1068 <DropdownMenuItem
1069 closeOnClick={false}
1070 onClick={() => setVisibleCommitCount((count) => count + COMMIT_PAGE_SIZE)}
1071 >
1072 <span className="text-muted-foreground">
1073 Show more ({orderedCommits.length - visibleCommitCount} left)
1074 </span>
1075 </DropdownMenuItem>
1076 ) : null}
1077 </DropdownMenuContent>
1078 </DropdownMenu>
1079 ) : null}
1080 {/* One count, and the caveats as icons that carry their own words. Spelled out they
1081 competed for a strip this narrow and every one of them truncated to nothing. */}
1082 <PullRequestMetaLine>
1083 <span className="shrink-0 tabular-nums">
1084 {files.length} {files.length === 1 ? "file" : "files"}
1085 {nextCursor === null ? "" : "+"}
1086 </span>
1087 {withheldContent ? (
1088 <Tooltip>
1089 <TooltipTrigger render={<span className="flex shrink-0 items-center" />}>
1090 <TriangleAlertIcon
1091 aria-label="Some of this diff was not shown"
1092 className="size-3.5 text-amber-600 dark:text-amber-500"
1093 />
1094 </TooltipTrigger>
1095 <TooltipPopup side="bottom">
1096 The host withheld part of this diff — a binary file, or a change too large to
1097 inline.
1098 </TooltipPopup>
1099 </Tooltip>
1100 ) : null}
1101 {commit !== null && review.inlineComment ? (
1102 <Tooltip>
1103 <TooltipTrigger render={<span className="flex shrink-0 items-center" />}>
1104 <MessageSquareOffIcon
1105 aria-label="Line comments are written from the whole change"
1106 className="size-3.5"
1107 />
1108 </TooltipTrigger>
1109 <TooltipPopup side="bottom">
1110 A comment is anchored to the whole change, so switch to All commits to write one.
1111 </TooltipPopup>
1112 </Tooltip>
1113 ) : null}
1114 </PullRequestMetaLine>
1115 </div>
1116 <div className="flex shrink-0 items-center gap-1">
1117 <PullRequestDiffStat
1118 additions={lineStat.additions}
1119 deletions={lineStat.deletions}
1120 className="mr-1"
1121 />
1122 {fileKeys.length > 0 ? (
1123 <Tooltip>
1124 <TooltipTrigger
1125 render={
1126 <Button
1127 type="button"
1128 size="icon-sm"
1129 variant="ghost"
1130 aria-label={allFilesCollapsed ? "Expand all files" : "Collapse all files"}
1131 onClick={toggleAllFiles}
1132 />
1133 }
1134 >
1135 {allFilesCollapsed ? (
1136 <ChevronsUpDownIcon className="size-3.5" />
1137 ) : (
1138 <ChevronsDownUpIcon className="size-3.5" />
1139 )}
1140 </TooltipTrigger>
1141 <TooltipPopup side="top">
1142 {allFilesCollapsed ? "Expand all files" : "Collapse all files"}
1143 </TooltipPopup>
1144 </Tooltip>
1145 ) : null}
1146 <ToggleGroup
1147 className="shrink-0 gap-1"
1148 size="sm"
1149 value={[diffLayout]}
1150 onValueChange={(value) => {
1151 const next = value[0];
1152 if (next === "stacked" || next === "split") {
1153 updateClientSettings({ diffLayout: next });
1154 }
1155 }}
1156 >
1157 <Toggle aria-label="Stacked diff view" value="stacked" variant="ghost">
1158 <Rows3Icon className="size-3.5" />
1159 </Toggle>
1160 <Toggle aria-label="Split diff view" value="split" variant="ghost">
1161 <Columns2Icon className="size-3.5" />
1162 </Toggle>
1163 </ToggleGroup>
1164 <Tooltip>
1165 <TooltipTrigger
1166 render={
1167 <Toggle
1168 aria-label={wordWrap ? "Disable diff line wrapping" : "Enable diff line wrapping"}
1169 variant="ghost"
1170 size="sm"
1171 pressed={wordWrap}
1172 onPressedChange={(pressed) => {
1173 setWordWrap(Boolean(pressed));
1174 }}
1175 />
1176 }
1177 >
1178 <TextWrapIcon className="size-3.5" />
1179 </TooltipTrigger>
1180 <TooltipPopup side="top">
1181 {wordWrap ? "Disable line wrapping" : "Enable line wrapping"}
1182 </TooltipPopup>
1183 </Tooltip>
1184 {fileKeys.length > 0 ? (
1185 <Tooltip>
1186 <TooltipTrigger
1187 render={
1188 <Toggle
1189 aria-label={fileTreeOpen ? "Hide file tree" : "Show file tree"}
1190 variant="ghost"
1191 size="sm"
1192 pressed={fileTreeOpen}
1193 onPressedChange={(pressed) => setFileTreeOpen(Boolean(pressed))}
1194 />
1195 }
1196 >
1197 <FolderTreeIcon className="size-3.5" />
1198 </TooltipTrigger>
1199 <TooltipPopup side="top">
1200 {fileTreeOpen ? "Hide file tree" : "Show file tree"}
1201 </TooltipPopup>
1202 </Tooltip>
1203 ) : null}
1204 </div>
1205 </div>
1206 );
1207 // The toolbar rides above every branch below, not just the one with a patch in it: a commit
1208 // whose diff is empty or unreadable still needs the scope dropdown that got the reader there.
1209 const withReviewBar = (body: ReactNode) => (
1210 <div className="flex h-full min-h-0 flex-col">
1211 {toolbar}
1212 {/* The overlay is anchored to this wrapper, not the scroller: absolute positioning
1213 inside an overflowing element tracks the content's bottom edge, which would carry
1214 the trigger away with the first scroll. */}
1215 <div className="relative min-h-0 flex-1">
1216 <div className="h-full overflow-auto">{body}</div>
1217 {reviewOverlay}
1218 </div>
1219 </div>
1220 );
1221
1222 // Under the toolbar rather than in place of it, so choosing a commit does not take the
1223 // dropdown that was just used off the screen while its diff loads.
1224 if (diffQuery.isPending && loadedSlices.length === 0) {
1225 return withReviewBar(<DiffPanelLoadingState label="Loading pull request diff..." />);
1226 }
1227
1228 // A slice that fails once there are files on screen is reported at the end of them instead:
1229 // the diff already read is worth more than the error that stopped it growing.
1230 if (diffQuery.error && loadedSlices.length === 0) {
1231 return withReviewBar(
1232 <p className="px-4 py-5 text-sm text-muted-foreground">{diffQuery.error}</p>,
1233 );
1234 }
1235
1236 // A patch the viewer cannot structure (binary, or a format it does not parse) still has to
1237 // be readable, so it falls back to the raw text rather than an empty tab. Only once the diff
1238 // is whole: returning here while a cursor is outstanding would take the sentinel off screen
1239 // and end the walk, leaving the rest of the change unasked for.
1240 const rawSlices =
1241 nextCursor === null
1242 ? parsedSlices.flatMap((parsed) => (parsed?.kind === "raw" ? [parsed] : []))
1243 : [];
1244 if (files.length === 0 && rawSlices.length > 0) {
1245 return withReviewBar(
1246 <div className="space-y-4 px-4 py-5">
1247 {rawSlices.map((slice) => (
1248 <div key={`${slice.reason}:${slice.text.slice(0, 64)}`} className="space-y-2">
1249 <p className="text-xs text-muted-foreground">{slice.reason}</p>
1250 <pre className="whitespace-pre-wrap break-words font-mono text-xs">{slice.text}</pre>
1251 </div>
1252 ))}
1253 </div>,
1254 );
1255 }
1256
1257 if (items.length === 0 && nextCursor === null) {
1258 return withReviewBar(
1259 <p className="px-4 py-5 text-sm text-muted-foreground">
1260 {commit === null
1261 ? "This pull request has no file changes."
1262 : "This commit has no file changes."}
1263 </p>,
1264 );
1265 }
1266
1267 const orphanThreads = detail.reviewThreads.filter((thread) => !placedThreadIds.has(thread.id));
1268 // A file carrying five stranded conversations should read as that file once rather than as
1269 // five copies of its path.
1270 const orphanFiles = new Map<string, PullRequestReviewThread[]>();
1271 for (const thread of orphanThreads) {
1272 const existing = orphanFiles.get(thread.path);
1273 if (existing) existing.push(thread);
1274 else orphanFiles.set(thread.path, [thread]);
1275 }
1276
1277 const unstructured =
1278 rawSlices.length === 0 ? null : (
1279 // A slice the viewer cannot structure is still part of the change. Shown under the files
1280 // that did parse rather than dropped, because the alternative is a diff that silently
1281 // omits whatever the viewer could not read.
1282 <div className="space-y-4 border-t border-border/60 px-4 py-5">
1283 {rawSlices.map((slice) => (
1284 <div key={`${slice.reason}:${slice.text.slice(0, 64)}`} className="space-y-2">
1285 <p className="text-xs text-muted-foreground">{slice.reason}</p>
1286 <pre className="whitespace-pre-wrap break-words font-mono text-xs">{slice.text}</pre>
1287 </div>
1288 ))}
1289 </div>
1290 );
1291
1292 return (
1293 <DiffWorkerPoolProvider>
1294 <div className="flex h-full min-h-0 flex-col">
1295 {toolbar}
1296 {/* Above the code, closed, and counted: these belong to the change rather than to any
1297 line of it, and in the stream they read as cards dropped into the patch. */}
1298 {orphanFiles.size > 0 ? (
1299 <Collapsible
1300 className="shrink-0 border-b border-border/60"
1301 open={orphansOpen}
1302 onOpenChange={setOrphansOpen}
1303 >
1304 {/* Still a heading, so the section keeps its place in a screen reader's outline;
1305 the count is spelled out there rather than left as a bare number. */}
1306 <h2>
1307 <CollapsibleTrigger className="flex w-full items-center gap-1.5 px-4 py-2 text-left text-xs text-muted-foreground">
1308 {/* While slices are still arriving a conversation may simply belong to a file
1309 that has not landed yet, which is not the same as being off the diff. */}
1310 <span>
1311 {nextCursor === null
1312 ? "Conversations not on the current diff"
1313 : "Conversations not on the diff loaded so far"}
1314 </span>
1315 <ChevronRightIcon
1316 aria-hidden
1317 className={cn("size-3.5 transition-transform", orphansOpen && "rotate-90")}
1318 />
1319 <span aria-hidden className="tabular-nums">
1320 {orphanThreads.length}
1321 </span>
1322 <span className="sr-only">
1323 {orphanThreads.length === 1
1324 ? "1 conversation"
1325 : `${orphanThreads.length} conversations`}
1326 </span>
1327 </CollapsibleTrigger>
1328 </h2>
1329 <CollapsiblePanel>
1330 {/* Capped: opened on a change with dozens of them, this would otherwise leave no
1331 room for the diff it sits above. */}
1332 <div className="max-h-64 space-y-3 overflow-auto px-4 pb-3">
1333 {[...orphanFiles].map(([path, threads]) => (
1334 <div key={path}>
1335 <Tooltip>
1336 <TooltipTrigger
1337 render={
1338 <p className="truncate px-3 text-xs text-muted-foreground">{path}</p>
1339 }
1340 />
1341 <TooltipPopup side="top">{path}</TooltipPopup>
1342 </Tooltip>
1343 <div className="mt-1 space-y-2">
1344 {threads.map((thread) => (
1345 <div key={thread.id}>
1346 {thread.line === null ? null : (
1347 <p className="px-3 text-xs text-muted-foreground">Line {thread.line}</p>
1348 )}
1349 {renderThreadCard(thread)}
1350 </div>
1351 ))}
1352 </div>
1353 </div>
1354 ))}
1355 </div>
1356 </CollapsiblePanel>
1357 </Collapsible>
1358 ) : null}
1359 <div className="flex min-h-0 flex-1 overflow-hidden">
1360 {/* Relative wrapper so the review overlay floats over the diff rather than pushing it
1361 up; the viewer inside still owns its own scrolling. */}
1362 <div
1363 className="relative min-h-0 min-w-0 flex-1"
1364 // The chevron answers this too, but the whole header row is the target a reader
1365 // actually aims for. The header lives in the viewer's shadow tree, so the capture
1366 // listener walks `composedPath` — the only way to see through the shadow boundary.
1367 onClickCapture={(event) => {
1368 const composedPath = event.nativeEvent.composedPath?.() ?? [];
1369 for (const node of composedPath) {
1370 if (!(node instanceof HTMLElement)) continue;
1371 // A control inside the header — the collapse chevron — handles itself, and
1372 // this capture listener fires before its own click does. Leave it alone or
1373 // the two toggles cancel out.
1374 if (node instanceof HTMLButtonElement || node instanceof HTMLAnchorElement) {
1375 return;
1376 }
1377 if (node.hasAttribute("data-diffs-header")) {
1378 const filePath = node.querySelector("[data-title]")?.textContent?.trim();
1379 if (filePath === undefined || filePath === "") return;
1380 const item = items.find(
1381 (candidate) => resolveFileDiffPath(candidate.fileDiff) === filePath,
1382 );
1383 if (item !== undefined) toggleFile(item.id);
1384 return;
1385 }
1386 }
1387 }}
1388 >
1389 {/* The viewer virtualizes against the element it is told is scrolling and places its
1390 rows absolutely, so it has to own that element — the thread diff panel hands it the
1391 same one. Scrolling from a parent instead leaves it painting over its neighbours. */}
1392 <StyledDiffCodeView<ReviewAnnotationGroup>
1393 // Keep scrollbar space stable so file metadata and line numbers do not shift as a
1394 // diff crosses the overflow boundary. The viewer is itself focusable for keyboard
1395 // interaction, but its native host outline clips and competes with the focus
1396 // indicators on its actual controls.
1397 className="h-full overflow-auto [scrollbar-gutter:stable]"
1398 viewerRef={viewerRef}
1399 items={items}
1400 selectedLines={selectedLines}
1401 onSelectedLinesChange={setSelectedLines}
1402 options={diffViewOptions}
1403 // The viewer owns the scroll container, so the sentinel that asks for the next slice
1404 // has to live inside it — at the end of the files, where reaching it means the reader
1405 // is running out of diff.
1406 renderCodeViewFooter={renderCodeViewFooter}
1407 renderHeaderPrefix={renderHeaderPrefix}
1408 renderHeaderMetadata={renderHeaderMetadata}
1409 renderAnnotation={renderAnnotation}
1410 unsafeCSSExtra={REPLACE_FILE_COUNTS_CSS}
1411 />
1412 {reviewOverlay}
1413 </div>
1414 {fileTreeOpen ? (
1415 <aside className="flex w-[min(20rem,40%)] min-w-48 shrink-0 border-l border-border/60">
1416 <DiffFileTree
1417 ariaLabel={`Pull request #${detail.number} files`}
1418 entries={fileTreeEntries}
1419 onSelectFile={revealFile}
1420 // The tree lists only what has arrived; a footer says so while the diff is still
1421 // paging, and lets the reader pull the rest in without scrolling for it.
1422 footer={
1423 nextCursor === null ? null : (
1424 <div className="shrink-0 border-t border-border/60 p-2">
1425 <Button
1426 type="button"
1427 size="xs"
1428 variant="outline"
1429 className="w-full"
1430 disabled={diffQuery.isPending}
1431 onClick={
1432 diffQuery.error !== null ? () => diffQuery.refresh() : loadNextSlice
1433 }
1434 >
1435 {diffQuery.error !== null
1436 ? "Retry"
1437 : diffQuery.isPending
1438 ? "Loading more files..."
1439 : "Load more files"}
1440 </Button>
1441 </div>
1442 )
1443 }
1444 />
1445 </aside>
1446 ) : null}
1447 </div>
1448 {unstructured}
1449 </div>
1450 </DiffWorkerPoolProvider>
1451 );
1452}
1453
1454export default PullRequestCodeTab;