Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

PullRequestDetailPanel.tsx

1,414 lines61.8 KB

1import { scopeProjectRef } from "@t3tools/client-runtime/environment";
2import { squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime";
3import type {
4 EnvironmentId,
5 PullRequestAction,
6 PullRequestMergeMethod,
7 PullRequestRef,
8 PullRequestState,
9} from "@t3tools/contracts";
10import {
11 ArrowDownUpIcon,
12 ArrowLeftIcon,
13 ArrowUpRightIcon,
14 BookOpenIcon,
15 CircleDotIcon,
16 ChevronDownIcon,
17 FileDiffIcon,
18 FolderGit2Icon,
19 GitBranchIcon,
20 GitCommitHorizontalIcon,
21 GitMergeIcon,
22 GitPullRequestClosedIcon,
23 GitPullRequestDraftIcon,
24 GitPullRequestIcon,
25 HammerIcon,
26 MessageCircleQuestionIcon,
27 MessageSquareIcon,
28 LinkIcon,
29 MoreHorizontalIcon,
30 PanelRightIcon,
31 RefreshCwIcon,
32 TriangleAlertIcon,
33} from "lucide-react";
34import {
35 lazy,
36 Suspense,
37 useCallback,
38 useEffect,
39 useLayoutEffect,
40 useMemo,
41 useRef,
42 useState,
43} from "react";
44​
45import { type DraftId, useComposerDraftStore } from "~/composerDraftStore";
46import { useNewThreadHandler } from "~/hooks/useHandleNewThread";
47import { useCopyToClipboard, writeTextToClipboard } from "~/hooks/useCopyToClipboard";
48import { usePreparePullRequestThreadAction } from "~/lib/sourceControlActions";
49import { cn } from "~/lib/utils";
50import { readLocalApi } from "~/localApi";
51import type { ReviewCommentContext } from "~/reviewCommentContext";
52import { useEnvironmentQuery } from "~/state/query";
53import { useLiveRefresh } from "~/hooks/useLiveRefresh";
54import { pullRequestEnvironment } from "~/state/pullRequests";
55import { useAtomCommand } from "~/state/use-atom-command";
56import { formatRelativeTimeLabel } from "~/timestampFormat";
57​
58import {
59 AlertDialog,
60 AlertDialogClose,
61 AlertDialogDescription,
62 AlertDialogFooter,
63 AlertDialogHeader,
64 AlertDialogPopup,
65 AlertDialogTitle,
66} from "../ui/alert-dialog";
67import { Badge } from "../ui/badge";
68import { Button } from "../ui/button";
69import {
70 Menu,
71 MenuItem,
72 MenuPopup,
73 MenuRadioGroup,
74 MenuRadioItem,
75 MenuSeparator,
76 MenuTrigger,
77} from "../ui/menu";
78import { toastManager } from "../ui/toast";
79import { PullRequestDetailGhost, PullRequestTimelineGhost } from "./PullRequestGhosts";
80import { PullRequestActivityUnavailableState } from "./PullRequestActivityUnavailableState";
81import { DiffPanelLoadingState } from "../DiffPanelShell";
82import { PullRequestsUnavailableState } from "./PullRequestsUnavailableState";
83import type { PullRequestAskSelectionInput } from "./PullRequestCodeTab";
84import { PullRequestSummaryTab } from "./PullRequestSummaryTab";
85import { PullRequestTimelineTab } from "./PullRequestTimelineTab";
86import {
87 buildAskAboutLinesHandoff,
88 buildAskAboutPullRequestHandoff,
89 buildExplainPullRequestHandoff,
90 buildFixFindingHandoff,
91 buildFixFindingsHandoff,
92 buildResolveConflictsPrompt,
93 handoffPrompt,
94 handoffReviewComments,
95 pullRequestFindingKey,
96 readableFailure,
97 type PullRequestFinding,
98} from "./pullRequestDetail.logic";
99import {
100 PullRequestActorLabel,
101 PullRequestDiffStat,
102 PullRequestMetaLine,
103 resolvePullRequestState,
104 summarizePullRequestChecks,
105} from "./pullRequestPresentation";
106​
107type DetailTab = "summary" | "timeline" | "code";
108​
109const ACTION_SUCCESS_LABELS: Record<PullRequestAction, string> = {
110 merge: "Pull request merged",
111 ready: "Marked ready for review",
112 draft: "Converted to draft",
113 close: "Pull request closed",
114 reopen: "Pull request reopened",
115};
116​
117/** Said as the thing that did not happen, rather than as the operation that returned an error. */
118const ACTION_FAILURE_LABELS: Record<PullRequestAction, string> = {
119 merge: "Could not merge this pull request",
120 ready: "Could not mark this ready for review",
121 draft: "Could not convert this to a draft",
122 close: "Could not close this pull request",
123 reopen: "Could not reopen this pull request",
124};
125​
126/** What to try, for the times the host says only that it refused. */
127const ACTION_FAILURE_HINTS: Record<PullRequestAction, string> = {
128 merge:
129 "The host refused the merge. Check that you have write access, that the checks it requires have passed, and that the branch is not conflicting.",
130 ready: "The host refused it. Check that you have write access to this repository.",
131 draft: "The host refused it. Check that you have write access to this repository.",
132 close: "The host refused it. Check that you have write access, or that you opened it.",
133 reopen:
134 "The host refused it. Check that you have write access, and that the branch still exists.",
135};
136​
137/** Named for the host rather than "externally": the point is where you will land. */
138const OPEN_ON_HOST_LABELS: Partial<Record<string, string>> = {
139 github: "Open on GitHub",
140 gitlab: "Open on GitLab",
141 bitbucket: "Open on Bitbucket",
142 "azure-devops": "Open on Azure DevOps",
143};
144​
145const TABS: ReadonlyArray<{ value: DetailTab; label: string }> = [
146 { value: "summary", label: "Summary" },
147 { value: "timeline", label: "Timeline" },
148 { value: "code", label: "Code" },
149];
150​
151// The diff viewer pulls in its worker pool, so it stays out of the bundle until Code is opened.
152// Named rather than inlined so the panel can also call it itself, to start the download before
153// anyone has clicked the tab.
154const loadCodeTab = () => import("./PullRequestCodeTab");
155const PullRequestCodeTab = lazy(loadCodeTab);
156​
157/**
158 * What the last hand-off wrote into each draft, kept outside React because the panel that wrote it
159 * is closed by the time the next one opens. It is how a prompt the reader has since edited is told
160 * apart from the one they were handed: only the sentence still exactly as written may be replaced.
161 */
162const lastHandoffPromptByDraft = new Map<DraftId, string>();
163​
164export function PullRequestDetailPanel({
165 environmentId,
166 reference,
167 refreshToken: forcedRefreshToken = 0,
168 onActed,
169 onClose,
170 onStateChange,
171 context = "page",
172 chromeVariant = "full",
173}: {
174 environmentId: EnvironmentId;
175 reference: PullRequestRef;
176 /**
177 * Bumped by whatever holds the panel when a reader asks for everything on screen to be read
178 * again. The panel owns its own reads, so the page cannot refresh them for it — it says when,
179 * and this says it.
180 */
181 refreshToken?: number;
182 /**
183 * An action changed this pull request on the host, so a list showing it is now out of date.
184 * Told rather than assumed: only the page knows whether it is showing one.
185 */
186 onActed?: () => void;
187 /** Page-owned detail columns use this to clear the selected pull request. */
188 onClose?: () => void;
189 /** Keeps compact chrome, such as the right-panel tab, in step with refreshed host state. */
190 onStateChange?: (status: {
191 projectId: string;
192 repository: string;
193 number: number;
194 state: PullRequestState;
195 isDraft: boolean;
196 }) => void;
197 /**
198 * Beside a thread, the checkout affordance disappears: the panel is showing that thread's
199 * own pull request, so the branch is already under the reader's feet — and checking it out
200 * again is at best a no-op and at worst git refusing a branch two checkouts.
201 */
202 context?: "page" | "thread";
203 /**
204 * How the metadata above the content behaves: `full` keeps every row pinned; `collapse`
205 * folds the whole of it into the top row once the active tab scrolls, and unfolds at the
206 * top — the chrome spends its height on what is being read.
207 */
208 chromeVariant?: "full" | "collapse";
209}) {
210 const pullRequestKey = `${reference.projectId}:${reference.repository}#${reference.number}`;
211 const [tab, setTab] = useState<DetailTab>("summary");
212 const [timelineOrder, setTimelineOrder] = useState<"newest" | "oldest">("newest");
213 const [codeCommitScope, setCodeCommitScope] = useState<{
214 readonly pullRequestKey: string;
215 readonly oid: string | null;
216 }>(() => ({ pullRequestKey, oid: null }));
217 const selectedCodeCommitOid =
218 codeCommitScope.pullRequestKey === pullRequestKey ? codeCommitScope.oid : null;
219 const selectCodeCommit = (oid: string | null) => {
220 setCodeCommitScope({ pullRequestKey, oid });
221 };
222 const openCommit = (oid: string) => {
223 selectCodeCommit(oid);
224 setTab("code");
225 };
226 // Every tab the reader has opened stays mounted behind the active one. The diff viewer
227 // always needed this (it virtualizes against its own scroll position); the trace showed the
228 // summary needs it too — a large description re-parses its whole markdown on every return
229 // to the tab. `visibility` keeps boxes, sizes and scroll offsets, and takes hidden content
230 // out of the tab order and the accessibility tree.
231 const [mountedTabs, setMountedTabs] = useState<ReadonlySet<DetailTab>>(
232 () => new Set<DetailTab>(["summary"]),
233 );
234 useEffect(() => {
235 setMountedTabs((previous) =>
236 previous.has(tab) ? previous : new Set<DetailTab>(previous).add(tab),
237 );
238 }, [tab]);
239 const [chromeCondensed, setChromeCondensed] = useState(false);
240 // Each tab remembers whether its chrome was condensed. Only the active tab can emit scroll
241 // events, so the capture handler always writes the active tab's entry — and a tab switch
242 // reads the destination's memory instead of inheriting the tab being left. A tab too short
243 // to scroll remembers "expanded", which is what keeps it from being stranded under a chrome
244 // it has no scrollbar to reopen.
245 const chromeStateByTab = useRef<Partial<Record<DetailTab, boolean>>>({});
246 useEffect(() => {
247 setChromeCondensed(chromeStateByTab.current[tab] ?? false);
248 }, [tab]);
249 const condensed = chromeVariant === "collapse" && chromeCondensed;
250 // Collapsing removes the fold's height from the chrome, which would otherwise hand that
251 // height to the scrollport and leap the content up by it mid-scroll. The cure is exact
252 // compensation: collapse only once the reader has scrolled at least the fold's height,
253 // then give that height back to `scrollTop` before the next paint — the content under
254 // their eyes does not move, and the collapse itself is the only thing that changes.
255 const scrollerRef = useRef<HTMLElement | null>(null);
256 const foldRef = useRef<HTMLDivElement | null>(null);
257 // The condensed chrome's second row opens as the fold closes, so the height the scrollport
258 // gains is the fold's minus this row's. Measured the same way the fold is: `scrollHeight`
259 // through a zero track reads its natural height in either state.
260 const condensedRowRef = useRef<HTMLDivElement | null>(null);
261 const compensationRef = useRef<number | null>(null);
262 useLayoutEffect(() => {
263 if (compensationRef.current === null) return;
264 const scroller = scrollerRef.current;
265 const delta = compensationRef.current;
266 compensationRef.current = null;
267 if (scroller) scroller.scrollTop = Math.max(0, scroller.scrollTop + delta);
268 }, [condensed]);
269 const [mergeMethod, setMergeMethod] = useState<PullRequestMergeMethod>("merge");
270 const [confirmAction, setConfirmAction] = useState<"merge" | "close" | null>(null);
271 // Which handoff is preparing, keyed so a per-finding button can say "Preparing..." on itself
272 // alone. One at a time whatever the key: they all check the same pull request out.
273 const [handoff, setHandoff] = useState<string | null>(null);
274 const { copyToClipboard: copyBranchToClipboard, isCopied: isBranchCopied } = useCopyToClipboard({
275 target: "branch name",
276 timeout: 1600,
277 });
278​
279 // The chunk is fetched as soon as the panel exists rather than waiting for the Code tab to be
280 // clicked, so a reader who does click it lands on a chunk already in the module cache.
281 useEffect(() => {
282 void loadCodeTab();
283 }, []);
284​
285 const detailQuery = useEnvironmentQuery(
286 pullRequestEnvironment.detail({ environmentId, input: reference }),
287 );
288 const activityQuery = useEnvironmentQuery(
289 pullRequestEnvironment.activity({ environmentId, input: reference }),
290 );
291 // Detail and diff are independent server reads, so the diff for the default view (no commit,
292 // no cursor) is started here too rather than waiting for the Code tab to mount. This is one
293 // extra cached read per opened pull request even for readers who never open the tab, but it
294 // turns the tab's first paint from a cold request into a cache hit.
295 const _diffWarmUpQuery = useEnvironmentQuery(
296 pullRequestEnvironment.diff({ environmentId, input: { ...reference } }),
297 );
298 const coreDetail = detailQuery.data;
299 const activity = activityQuery.data;
300 const detail = useMemo(
301 () =>
302 coreDetail === null
303 ? null
304 : {
305 ...coreDetail,
306 author: activity?.author ?? coreDetail.author,
307 reviewers: activity?.reviewers ?? coreDetail.reviewers,
308 comments: activity?.comments ?? [],
309 commentCount: activity?.commentCount ?? 0,
310 commentsTruncated: activity?.commentsTruncated ?? false,
311 reviewThreads: activity?.reviewThreads ?? [],
312 commits: activity?.commits ?? [],
313 },
314 [activity, coreDetail],
315 );
316 const activityPending = activityQuery.isPending && activity === null;
317 const activityError = activity === null ? activityQuery.error : null;
318 const refreshDetail = useCallback(() => {
319 detailQuery.refresh();
320 activityQuery.refresh();
321 }, [activityQuery.refresh, detailQuery.refresh]);
322 useEffect(() => {
323 if (!detail) return;
324 onStateChange?.({
325 projectId: detail.projectId,
326 repository: detail.repository,
327 number: detail.number,
328 state: detail.state,
329 isDraft: detail.isDraft,
330 });
331 }, [detail, onStateChange]);
332 // A pull request changes while it is open in front of somebody — a push lands, a check
333 // finishes, a review arrives — so the panel reads it again on the way back to the window and
334 // while a reader sits on it. Keyed by the pull request rather than by the panel, because this
335 // one panel shows a different pull request every time it is opened.
336 useLiveRefresh(refreshDetail, {
337 key: `pull-request:${reference.projectId}:${reference.repository}#${reference.number}`,
338 });
339 // The button, on the other hand, goes around the server's cache rather than through it: it is
340 // the answer for a reader who can see that what they are looking at is behind. The
341 // invalidation goes first so the re-reads miss that cache; if it fails, the reads still run
342 // and at worst answer from it.
343 const invalidate = useAtomCommand(pullRequestEnvironment.invalidate, { reportFailure: false });
344 const [refreshToken, setRefreshToken] = useState(0);
345 const refreshFromHost = useCallback(async () => {
346 await invalidate({ environmentId, input: { reference } });
347 refreshDetail();
348 setRefreshToken((token) => token + 1);
349 }, [environmentId, invalidate, reference, refreshDetail]);
350 // A refresh asked for by the page: the detail, and through the token below, the diff with it.
351 const appliedForcedToken = useRef(forcedRefreshToken);
352 useEffect(() => {
353 if (appliedForcedToken.current === forcedRefreshToken) return;
354 appliedForcedToken.current = forcedRefreshToken;
355 void refreshFromHost();
356 }, [forcedRefreshToken, refreshFromHost]);
357 const runAction = useAtomCommand(pullRequestEnvironment.runAction, { reportFailure: false });
358 const [actionPending, setActionPending] = useState(false);
359 const newThread = useNewThreadHandler();
360 const prepareThread = usePreparePullRequestThreadAction({
361 environmentId,
362 cwd: detail?.workspaceRoot ?? null,
363 });
364​
365 const perform = async (action: PullRequestAction, method?: PullRequestMergeMethod) => {
366 if (actionPending) return;
367 setActionPending(true);
368 const result = await runAction({
369 environmentId,
370 input: { ...reference, action, ...(method ? { mergeMethod: method } : {}) },
371 });
372 setActionPending(false);
373 if (result._tag === "Failure") {
374 // The host's own sentence, because it is the only thing that says why. A merge strategy a
375 // branch policy forbids is refused at completion and nowhere earlier — Azure DevOps
376 // publishes no per-strategy availability to hide the control with — so "action failed"
377 // would leave the reader pressing the same button again.
378 const failure = squashAtomCommandFailure(result);
379 toastManager.add({
380 type: "error",
381 title: ACTION_FAILURE_LABELS[action],
382 description: readableFailure(failure, ACTION_FAILURE_HINTS[action]),
383 });
384 return;
385 }
386 toastManager.add({ type: "success", title: ACTION_SUCCESS_LABELS[action] });
387 refreshDetail();
388 onActed?.();
389 };
390​
391 type ThreadTask = {
392 prompt: string;
393 reviewComments?: ReadonlyArray<ReviewCommentContext>;
394 };
395​
396 /**
397 * Opens a thread on this project and leaves the task in its composer for the reader to send.
398 *
399 * Nothing is checked out: asking a question is not a reason to move somebody's working tree or
400 * to make a worktree they did not ask for. The two hand-offs that do need the code call this
401 * after preparing it, so there is one path from "a task" to "a thread holding it".
402 */
403 const openThreadWithTask = async (
404 projectRef: ReturnType<typeof scopeProjectRef>,
405 task: ThreadTask | null,
406 opened?: { draftId: DraftId },
407 ): Promise<{ draftId: DraftId } | null> => {
408 const session =
409 opened ??
410 (await newThread(projectRef).then(
411 (result) => result,
412 () => null,
413 ));
414 if (session === null) return null;
415 const store = useComposerDraftStore.getState();
416 if (task === null) return session;
417 // The latest press is the ask: it takes over what an earlier hand-off left, prompt and chips
418 // both, rather than stacking a second one under the first. What the reader typed themselves
419 // survives — the composer they are handed is not always a fresh one, and a prompt they have
420 // since edited is theirs rather than the hand-off's.
421 const draft = store.getComposerDraft(session.draftId);
422 const existingComments = draft?.reviewComments ?? [];
423 const prompt = handoffPrompt(
424 {
425 prompt: draft?.prompt ?? "",
426 lastHandoffPrompt: lastHandoffPromptByDraft.get(session.draftId),
427 },
428 task.prompt,
429 );
430 // Remember the hand-off's own contribution, not the merged prompt: only that sentence is
431 // this session's to take back next time, and the reader's text around it is not.
432 lastHandoffPromptByDraft.set(session.draftId, task.prompt);
433 store.setPrompt(session.draftId, prompt);
434 store.setReviewComments(
435 session.draftId,
436 handoffReviewComments(existingComments, task.reviewComments ?? []),
437 );
438 return session;
439 };
440​
441 /** A question about the change, which needs a thread and nothing else. */
442 const startAsk = async (kind: string, task: ThreadTask) => {
443 if (!detail || handoff !== null) return;
444 setHandoff(kind);
445 const projectRef = scopeProjectRef(environmentId, detail.projectId);
446 const opened = await openThreadWithTask(projectRef, task);
447 setHandoff(null);
448 if (opened === null) {
449 toastManager.add({
450 type: "error",
451 title: "Could not open a thread",
452 description: "Try again from the project, or open a thread first.",
453 });
454 return;
455 }
456 toastManager.add({
457 type: "success",
458 title: "Asked in a thread",
459 // "Ask" leaves the composer empty on purpose, so saying the question is in it would send
460 // the reader looking for something that is not there. The chips are what landed.
461 description:
462 task.prompt.length > 0
463 ? "The question is in the composer — read it over, then send."
464 : "The pull request is in the composer — type your question, then send.",
465 });
466 };
467​
468 // Every handoff works the same way: check the pull request out into its own worktree, open a
469 // thread there, and — when it carries a task — put that in the composer for the user to read
470 // before sending. Checking out is the whole point of the ones that carry nothing.
471 const startHandoff = async (
472 kind: string,
473 task: { prompt: string; reviewComments?: ReadonlyArray<ReviewCommentContext> } | null,
474 // A worktree leaves whatever is open alone, which is why it is the default. Checking out in
475 // the repository itself is what you want when the point is to run the thing where you
476 // already work — and it moves the branch under everything else that is open there.
477 mode: "worktree" | "local" = "worktree",
478 ) => {
479 if (!detail || handoff !== null) return;
480 setHandoff(kind);
481 // The menu closes on the press and takes its "Preparing..." label with it, so this is the
482 // only thing answering for the checkout. It carries no timeout of its own: a loading toast
483 // never expires, and an explicit one would survive the update and pin the result on screen.
484 const toastId = toastManager.add({
485 type: "loading",
486 title: "Preparing the pull request checkout...",
487 });
488 const projectRef = scopeProjectRef(environmentId, detail.projectId);
489 // The thread is opened before the checkout rather than after it, because the project's setup
490 // script only runs for a checkout that knows which thread it is for — and a worktree with no
491 // dependencies installed is not something anyone can test.
492 const opened = await newThread(projectRef).then(
493 (session) => session,
494 () => null,
495 );
496 if (opened === null) {
497 setHandoff(null);
498 // Without a thread there is nowhere for the checkout to belong: its setup script would not
499 // run and its task would have no composer to land in. Better to stop before touching the
500 // working tree than to prepare a worktree nobody asked for.
501 toastManager.update(toastId, {
502 type: "error",
503 title: "Could not open a thread for the checkout",
504 description: "Try again from the project, or open a thread first.",
505 });
506 return;
507 }
508 const prepared = await prepareThread.run({
509 reference: detail.url,
510 mode,
511 threadId: opened.threadId,
512 });
513 if (prepared._tag === "Failure") {
514 setHandoff(null);
515 // The server says what to do about it — that the branch is already checked out in the main
516 // repository, say — and that sentence is the only way out of the failure.
517 const detailMessage =
518 prepareThread.error instanceof Error ? prepareThread.error.message : null;
519 toastManager.update(toastId, {
520 type: "error",
521 title: "Could not prepare the pull request checkout",
522 ...(detailMessage ? { description: detailMessage } : {}),
523 });
524 return;
525 }
526 // The same thread again, now that there is somewhere to point it at. A local checkout has
527 // no worktree of its own, so the thread runs where the repository already is.
528 const pointed = await newThread(projectRef, {
529 branch: prepared.value.branch,
530 worktreePath: prepared.value.worktreePath,
531 envMode: prepared.value.worktreePath === null ? "local" : "worktree",
532 }).then(
533 (session) => session !== null,
534 () => false,
535 );
536 if (!pointed) {
537 setHandoff(null);
538 // The checkout is on disk; only the thread failed to move onto it. Writing the task now
539 // would send the agent at whatever the thread was already open on — which is the one
540 // outcome worth stopping for, since it reads as success and is not.
541 toastManager.update(toastId, {
542 type: "error",
543 title: "Checked out, but the thread stayed where it was",
544 description: `The checkout is ready on \`${prepared.value.branch}\`. Point a thread at it from the branch picker, then ask again.`,
545 });
546 return;
547 }
548 // Released here whatever happened next: a loading toast never expires on its own, so leaving
549 // this set would spin forever and lock every handoff behind it until a reload.
550 setHandoff(null);
551 // A worktree that was already there and had been worked in keeps whatever it holds, so the
552 // thread opens on older code than the pull request carries. Said once, in place of the
553 // success, because everything else about the handoff did happen.
554 const staleCheckoutToast = {
555 type: "warning",
556 title: "Checked out, but not on the latest commits",
557 description:
558 "The checkout could not be moved onto the pull request's latest commits, so the code there is older than the pull request. Uncommitted work or local commits keep it where it is.",
559 } as const;
560 if (task === null) {
561 toastManager.update(
562 toastId,
563 prepared.value.isOnPullRequestHead
564 ? {
565 type: "success",
566 title: mode === "local" ? "Checked out here" : "Checked out",
567 description:
568 mode === "local"
569 ? "This repository is on the pull request's branch, with a thread open on it."
570 : "The pull request is in its own worktree, with a thread open on it.",
571 }
572 : staleCheckoutToast,
573 );
574 return;
575 }
576 await openThreadWithTask(projectRef, task, opened);
577 toastManager.update(
578 toastId,
579 prepared.value.isOnPullRequestHead
580 ? {
581 type: "success",
582 title: "Checkout ready",
583 description: "The task is in the composer — read it over, then send.",
584 }
585 : staleCheckoutToast,
586 );
587 };
588​
589 const askAboutPullRequest = () => {
590 if (!detail) return;
591 void startAsk("ask", {
592 ...buildAskAboutPullRequestHandoff({
593 number: detail.number,
594 title: detail.title,
595 url: detail.url,
596 headBranch: detail.headBranch,
597 baseBranch: detail.baseBranch,
598 }),
599 });
600 };
601​
602 const explainPullRequest = () => {
603 if (!detail) return;
604 void startAsk("explain", {
605 ...buildExplainPullRequestHandoff({
606 number: detail.number,
607 title: detail.title,
608 url: detail.url,
609 headBranch: detail.headBranch,
610 baseBranch: detail.baseBranch,
611 }),
612 });
613 };
614​
615 /** Lines the reader marked in the diff, asked about rather than commented on. */
616 const askAboutSelection = (selection: PullRequestAskSelectionInput) => {
617 if (!detail) return;
618 void startAsk(`ask:${selection.comment.id}`, {
619 ...buildAskAboutLinesHandoff({
620 number: detail.number,
621 title: detail.title,
622 url: detail.url,
623 headBranch: detail.headBranch,
624 baseBranch: detail.baseBranch,
625 comment: selection.comment,
626 question: selection.question,
627 }),
628 });
629 };
630​
631 const startCheckout = (mode: "worktree" | "local") => {
632 if (!detail) return;
633 void startHandoff(`checkout:${mode}`, null, mode);
634 };
635​
636 /** One finding, handed over on its own — the surfaces that show findings call this. */
637 const startFixFinding = (finding: PullRequestFinding) => {
638 if (!detail) return;
639 void startHandoff(
640 pullRequestFindingKey(finding),
641 buildFixFindingHandoff({
642 number: detail.number,
643 title: detail.title,
644 url: detail.url,
645 headBranch: detail.headBranch,
646 baseBranch: detail.baseBranch,
647 finding,
648 }),
649 );
650 };
651​
652 const startFixFindings = () => {
653 if (!detail) return;
654 void startHandoff(
655 "findings",
656 buildFixFindingsHandoff({
657 number: detail.number,
658 title: detail.title,
659 url: detail.url,
660 headBranch: detail.headBranch,
661 baseBranch: detail.baseBranch,
662 reviewThreads: detail.reviewThreads,
663 comments: detail.comments,
664 checks: detail.checks,
665 commentsTruncated: detail.commentsTruncated,
666 }),
667 );
668 };
669​
670 const startResolveConflicts = () => {
671 if (!detail) return;
672 void startHandoff("conflicts", {
673 prompt: buildResolveConflictsPrompt({
674 number: detail.number,
675 url: detail.url,
676 headBranch: detail.headBranch,
677 baseBranch: detail.baseBranch,
678 }),
679 });
680 };
681​
682 // The host says which strategies it offers at all; the repository narrows that to the ones
683 // it actually allows.
684 const allowedMergeMethods = detail
685 ? detail.capabilities.mergeMethods.filter((method) => detail.mergeCapabilities[method])
686 : [];
687 const selectedMergeMethod = allowedMergeMethods.includes(mergeMethod)
688 ? mergeMethod
689 : (allowedMergeMethods[0] ?? "merge");
690 const conflicting = detail?.state === "open" && detail.mergeability === "conflicting";
691 // A host that cannot produce a patch has no Code tab to open. The tabs themselves stay hidden
692 // until the detail arrives, so the loading ghost is the panel's only unfinished UI.
693 const visibleTabs = TABS.filter(
694 (item) => item.value !== "code" || detail === null || detail.capabilities.diff,
695 );
696 // The Code tab can be opened while the detail is still on its way, and the detail may then say
697 // this host has no patch to show. The tab goes, so whoever was standing on it is moved back to
698 // the summary rather than left looking at a panel that is no longer reachable.
699 useEffect(() => {
700 if (!visibleTabs.some((item) => item.value === tab)) setTab("summary");
701 }, [tab, visibleTabs]);
702 // Two questions, both of which have to say yes: whether this host can do it at all, and
703 // whether this account may. A reader with read access on someone else's project sees the pull
704 // request and none of the buttons that would only ever be refused.
705 const can = (action: PullRequestAction) =>
706 detail?.capabilities.actions.includes(action) === true &&
707 detail.viewerPermissions.actions.includes(action);
708 // One live action holds the slot. A conflicting change cannot be merged now, so the slot goes
709 // to the thing that would help instead of a Merge button that only ever says no.
710 const primaryAction =
711 detail === null || detail.state !== "open"
712 ? null
713 : detail.isDraft && can("ready")
714 ? "ready"
715 : !can("merge")
716 ? null
717 : conflicting
718 ? "resolve"
719 : allowedMergeMethods.length > 0
720 ? "merge"
721 : null;
722 // The pull request number carries this state in the overview and the right-panel tab mirrors
723 // it. Conflicts keep their own row below: an open pull request remains green there.
724 const statePresentation = detail
725 ? resolvePullRequestState({ state: detail.state, isDraft: detail.isDraft })
726 : null;
727 const checksSummary = detail ? summarizePullRequestChecks(detail.checks) : null;
728​
729 return (
730 <div className="flex h-full min-h-0 w-full flex-col bg-background">
731 {/* The top row's geometry never changes: both of its states occupy the same stacked
732 cell and crossfade, so the actions on the right have one home whatever the chrome
733 is doing below. The fold and this fade share one 200ms clock. */}
734 <div className="grid shrink-0 grid-cols-[minmax(0,1fr)_auto] items-start gap-x-2 border-b border-border/60">
735 {/* The fixed height lives on the two top-row cells — not the grid, whose later rows
736 are the fold — so the actions have one immovable home in both states. */}
737 <div className="ml-4 grid h-11 min-w-0 items-center">
738 <div
739 aria-hidden={condensed}
740 inert={condensed}
741 className={cn(
742 "col-start-1 row-start-1 flex min-w-0 items-center gap-1 text-sm text-muted-foreground transition-opacity sm:text-xs motion-reduce:transition-none",
743 // Sequenced, not simultaneous: the leaving layer clears quickly before the
744 // arriving one lands, so no frame shows both texts superimposed at half opacity.
745 condensed
746 ? "pointer-events-none opacity-0 duration-100"
747 : "opacity-100 delay-75 duration-150",
748 )}
749 >
750 {detail && statePresentation ? (
751 <>
752 <span className="min-w-0 truncate" title={detail.repository}>
753 {detail.repository}
754 </span>
755 <button
756 type="button"
757 onClick={() => void readLocalApi()?.shell.openExternal(detail.url)}
758 className={cn(
759 "shrink-0 font-medium underline-offset-2 hover:underline",
760 statePresentation.toneClassName,
761 )}
762 title={OPEN_ON_HOST_LABELS[detail.provider] ?? "Open on host"}
763 aria-label={`Open pull request #${detail.number} on host`}
764 >
765 #{detail.number}
766 </button>
767 </>
768 ) : null}
769 </div>
770 <div
771 aria-hidden={!condensed}
772 inert={!condensed}
773 className={cn(
774 "col-start-1 row-start-1 flex min-w-0 items-center gap-1.5 text-sm transition-opacity sm:text-xs motion-reduce:transition-none",
775 condensed
776 ? "opacity-100 delay-75 duration-150"
777 : "pointer-events-none opacity-0 duration-100",
778 )}
779 >
780 {detail && statePresentation ? (
781 <>
782 <button
783 type="button"
784 tabIndex={condensed ? 0 : -1}
785 onClick={() => void readLocalApi()?.shell.openExternal(detail.url)}
786 className={cn(
787 "shrink-0 font-medium underline-offset-2 hover:underline",
788 statePresentation.toneClassName,
789 )}
790 title={OPEN_ON_HOST_LABELS[detail.provider] ?? "Open on host"}
791 aria-label={`Open pull request #${detail.number} on host`}
792 >
793 #{detail.number}
794 </button>
795 <span className="min-w-0 truncate font-medium text-foreground" title={detail.title}>
796 {detail.title}
797 </span>
798 {conflicting ? (
799 <Badge
800 variant="error"
801 className="h-5 shrink-0 gap-1 rounded px-1.5 text-[10px] text-destructive"
802 >
803 <TriangleAlertIcon className="size-3" />
804 Conflicts
805 </Badge>
806 ) : checksSummary ? (
807 <span className="shrink-0 text-[10px] text-muted-foreground">
808 {checksSummary}
809 </span>
810 ) : null}
811 </>
812 ) : null}
813 </div>
814 </div>
815 <div className="mr-4 flex h-11 min-w-0 flex-nowrap items-center justify-end gap-1">
816 {detail ? (
817 <>
818 <Menu>
819 <MenuTrigger
820 className="inline-flex size-6 shrink-0 items-center justify-center rounded-md text-muted-foreground hover:bg-accent hover:text-foreground"
821 aria-label="More pull request actions"
822 >
823 <MoreHorizontalIcon className="size-4" />
824 </MenuTrigger>
825 <MenuPopup align="end" side="bottom" className="min-w-72">
826 <MenuItem disabled={detailQuery.isPending} onClick={() => void refreshFromHost()}>
827 <RefreshCwIcon className="size-3.5" />
828 Refresh
829 </MenuItem>
830 <MenuItem disabled={handoff !== null} onClick={askAboutPullRequest}>
831 <MessageCircleQuestionIcon className="mt-0.5 size-3.5 shrink-0 self-start" />
832 <span className="flex min-w-0 flex-col">
833 <span>{handoff === "ask" ? "Opening..." : "Ask a question"}</span>
834 <span className="text-xs text-muted-foreground">
835 Opens a thread that knows which pull request you mean.
836 </span>
837 </span>
838 </MenuItem>
839 <MenuItem disabled={handoff !== null} onClick={explainPullRequest}>
840 <BookOpenIcon className="mt-0.5 size-3.5 shrink-0 self-start" />
841 <span className="flex min-w-0 flex-col">
842 <span>{handoff === "explain" ? "Opening..." : "Explain this PR"}</span>
843 <span className="text-xs text-muted-foreground">
844 A walk through the diff and what to read closely.
845 </span>
846 </span>
847 </MenuItem>
848 <MenuItem disabled={handoff !== null} onClick={startFixFindings}>
849 <HammerIcon className="size-3.5" />
850 {handoff === "findings" ? "Preparing..." : "Fix findings in a thread"}
851 </MenuItem>
852 <MenuSeparator />
853 {detail.state === "open" ? (
854 <>
855 {/* Only where the button row could not take it: "Ready for review" on a
856 draft is the primary header button, so offering it here as well would
857 show the same action twice. */}
858 {can(detail.isDraft ? "ready" : "draft") &&
859 !(detail.isDraft && primaryAction === "ready") ? (
860 <MenuItem
861 disabled={actionPending}
862 onClick={() => void perform(detail.isDraft ? "ready" : "draft")}
863 >
864 {detail.isDraft ? (
865 <GitPullRequestIcon className="size-3.5" />
866 ) : (
867 <GitPullRequestDraftIcon className="size-3.5" />
868 )}
869 {detail.isDraft ? "Ready for review" : "Convert to draft"}
870 </MenuItem>
871 ) : null}
872 {/* A preference for the merge action rather than a second action, so it
873 is a radio group here instead of a chevron welded to the Merge pill.
874 Hidden while conflicting: every method would fail. */}
875 {/* Only where merging is on offer at all: a strategy to merge with is not
876 a choice for someone who may not merge. */}
877 {can("merge") &&
878 !detail.isDraft &&
879 !conflicting &&
880 allowedMergeMethods.length > 1 ? (
881 <>
882 <MenuSeparator />
883 <MenuRadioGroup
884 value={selectedMergeMethod}
885 onValueChange={(method) =>
886 setMergeMethod(method as PullRequestMergeMethod)
887 }
888 >
889 {allowedMergeMethods.map((method) => (
890 <MenuRadioItem key={method} value={method} disabled={actionPending}>
891 {/* The radio item lays its children out as one block, so the
892 icon and the label need their own row to share a line. */}
893 <span className="flex min-w-0 items-center gap-2">
894 <GitMergeIcon className="size-3.5" />
895 <span className="capitalize">{method}</span>
896 </span>
897 </MenuRadioItem>
898 ))}
899 </MenuRadioGroup>
900 </>
901 ) : null}
902 <MenuSeparator />
903 </>
904 ) : null}
905 <MenuItem onClick={() => void readLocalApi()?.shell.openExternal(detail.url)}>
906 <ArrowUpRightIcon className="size-3.5" />
907 {OPEN_ON_HOST_LABELS[detail.provider] ?? "Open on host"}
908 </MenuItem>
909 <MenuItem onClick={() => void writeTextToClipboard(detail.url)}>
910 <LinkIcon className="size-3.5" />
911 Copy link
912 </MenuItem>
913 {/* Only where the button row could not take it, so it is never offered twice. */}
914 {conflicting && primaryAction !== "resolve" ? (
915 <MenuItem disabled={handoff !== null} onClick={startResolveConflicts}>
916 <GitMergeIcon className="size-3.5" />
917 {handoff === "conflicts" ? "Preparing..." : "Resolve conflicts in a thread"}
918 </MenuItem>
919 ) : null}
920 {detail.state === "open" && can("close") ? (
921 <>
922 <MenuSeparator />
923 <MenuItem
924 variant="destructive"
925 disabled={actionPending}
926 onClick={() => setConfirmAction("close")}
927 >
928 <GitPullRequestClosedIcon className="size-3.5" />
929 Close pull request
930 </MenuItem>
931 </>
932 ) : detail.state === "closed" && can("reopen") ? (
933 <>
934 <MenuSeparator />
935 <MenuItem disabled={actionPending} onClick={() => void perform("reopen")}>
936 <GitPullRequestIcon className="size-3.5" />
937 Reopen pull request
938 </MenuItem>
939 </>
940 ) : null}
941 </MenuPopup>
942 </Menu>
943 {/* Checking a pull request out is the reason to open one here at all, so it is a
944 button of its own rather than a side effect of asking an agent for something.
945 It asks where, because the two answers are not interchangeable: one leaves your
946 work where it is, the other moves the repository you are standing in. Only on
947 the page: beside a thread the branch is already checked out right there. */}
948 {context === "page" ? (
949 <Menu>
950 <MenuTrigger
951 disabled={handoff !== null}
952 render={
953 <Button size="xs" variant="outline">
954 {handoff?.startsWith("checkout") ? (
955 "Checking out..."
956 ) : (
957 <>
958 <GitBranchIcon className="size-3" />
959 Check out
960 <ChevronDownIcon className="size-3 text-muted-foreground" />
961 </>
962 )}
963 </Button>
964 }
965 />
966 <MenuPopup align="end" side="bottom" className="min-w-72">
967 <MenuItem onClick={() => startCheckout("worktree")}>
968 <GitBranchIcon className="mt-0.5 size-3.5 shrink-0 self-start" />
969 <span className="flex min-w-0 flex-col">
970 <span>In a separate worktree</span>
971 <span className="text-xs text-muted-foreground">
972 Its own folder and thread. Nothing you have open moves.
973 </span>
974 </span>
975 </MenuItem>
976 <MenuItem onClick={() => startCheckout("local")}>
977 <FolderGit2Icon className="mt-0.5 size-3.5 shrink-0 self-start" />
978 <span className="flex min-w-0 flex-col">
979 <span>In this repository</span>
980 <span className="text-xs text-muted-foreground">
981 Switches the branch you are working in, like `gh pr checkout`.
982 </span>
983 </span>
984 </MenuItem>
985 </MenuPopup>
986 </Menu>
987 ) : null}
988 {primaryAction === "ready" ? (
989 <Button size="xs" disabled={actionPending} onClick={() => void perform("ready")}>
990 Ready for review
991 </Button>
992 ) : primaryAction === "merge" ? (
993 <Button
994 size="xs"
995 disabled={actionPending}
996 onClick={() => setConfirmAction("merge")}
997 >
998 {actionPending ? "Merging..." : "Merge"}
999 </Button>
1000 ) : null}
1001 </>
1002 ) : null}
1003 {onClose ? (
1004 <Button
1005 size="icon-xs"
1006 variant="ghost"
1007 aria-label="Collapse pull request panel"
1008 onClick={onClose}
1010 <PanelRightIcon className="size-3.5" />
1011 </Button>
1012 ) : null}
1013 </div>
1014​
1015 {/* The condensed chrome's second row: the tabs that the closing fold takes with it,
1016 and compact copies of the branch pair and diff stat so they stay in sight while
1017 the full rows are folded away. Same zero-track mechanism as the fold, inverted. */}
1018 <div className={cn("col-span-2 grid", condensed ? "grid-rows-[1fr]" : "grid-rows-[0fr]")}>
1019 <div
1020 ref={condensedRowRef}
1021 className={cn(
1022 "min-h-0 overflow-hidden",
1023 condensed
1024 ? "opacity-100 transition-opacity duration-200 ease-out motion-reduce:transition-none"
1025 : "opacity-0",
1026 )}
1027 inert={!condensed}
1029 {detail ? (
1030 <div className="flex min-w-0 items-center gap-1 px-4 pb-2">
1031 <nav aria-label="Pull request tabs" className="flex shrink-0 items-center gap-0.5">
1032 {visibleTabs.map((item) => (
1033 <button
1034 key={item.value}
1035 type="button"
1036 tabIndex={condensed ? 0 : -1}
1037 aria-pressed={tab === item.value}
1038 onClick={() => setTab(item.value)}
1039 className={cn(
1040 "rounded-md px-2 py-1 text-[11px] transition-colors",
1041 tab === item.value
1042 ? "bg-accent text-foreground"
1043 : "text-muted-foreground hover:text-foreground",
1044 )}
1046 {item.label}
1047 </button>
1048 ))}
1049 </nav>
1050 <span
1051 className="ml-auto inline-flex min-w-0 shrink items-center gap-1 font-mono text-[11px] text-muted-foreground"
1052 title={`${detail.baseBranch} ← ${detail.headBranch}`}
1054 <span className="truncate">{detail.baseBranch}</span>
1055 <ArrowLeftIcon aria-label="receives changes from" className="size-3 shrink-0" />
1056 <span className="truncate">{detail.headBranch}</span>
1057 </span>
1058 <span className="ml-2 inline-flex shrink-0 items-center gap-2 text-[11px] text-muted-foreground">
1059 <span className="inline-flex items-center gap-1 tabular-nums">
1060 <FileDiffIcon className="size-3" />
1061 {detail.changedFiles.toLocaleString()}
1062 </span>
1063 <PullRequestDiffStat
1064 additions={detail.additions}
1065 deletions={detail.deletions}
1066 className="shrink-0 font-mono text-[11px]"
1067 />
1068 </span>
1069 </div>
1070 ) : null}
1071 </div>
1072 </div>
1073​
1074 {/* Folding is a grid track going to zero: the rows below stay mounted, the track
1075 animates closed over them, and `inert` takes the hidden controls out of the tab
1076 order for as long as the chrome is condensed. */}
1077 <div
1078 className={cn(
1079 "col-span-2 grid",
1080 // Instant in both directions: the scroll compensation keeps the content pinned
1081 // through either flip, and an animated track would fight it frame by frame. The
1082 // top row's crossfade is the transition.
1083 condensed ? "grid-rows-[0fr]" : "grid-rows-[1fr]",
1084 )}
1086 <div
1087 ref={foldRef}
1088 // One-way on purpose: appearing content eases in over ground the instant track
1089 // already reserved; departing content cuts, because its ground is gone in the
1090 // same frame and the scroll compensation reads it as scrolled past.
1091 className={cn(
1092 "min-h-0 overflow-hidden",
1093 condensed
1094 ? "opacity-0"
1095 : "opacity-100 transition-opacity duration-200 ease-out motion-reduce:transition-none",
1096 )}
1097 inert={condensed}
1099 {detail ? (
1100 <div className="col-span-2 mt-3 min-w-0 px-4 pb-4">
1101 <h1 className="text-base font-semibold leading-snug">{detail.title}</h1>
1102 <PullRequestMetaLine className="mt-2 text-xs text-muted-foreground">
1103 <PullRequestActorLabel actor={detail.author} className="font-medium" />
1104 <span>updated {formatRelativeTimeLabel(detail.updatedAt)}</span>
1105 </PullRequestMetaLine>
1106​
1107 <div className="mt-4 flex min-w-0 items-center gap-2 text-xs text-muted-foreground">
1108 <code
1109 className="min-w-0 max-w-48 shrink truncate rounded-md bg-muted px-2 py-1 font-mono text-xs text-foreground"
1110 title={detail.baseBranch}
1112 {detail.baseBranch}
1113 </code>
1114 <ArrowLeftIcon aria-label="receives changes from" className="size-4 shrink-0" />
1115 <button
1116 type="button"
1117 className="grid min-w-0 max-w-64 shrink cursor-pointer rounded-md bg-muted px-2 py-1 font-mono text-xs text-foreground outline-none transition-colors hover:bg-accent focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-1 focus-visible:ring-offset-background"
1118 aria-label={isBranchCopied ? "Branch name copied" : "Copy pull request branch"}
1119 title={isBranchCopied ? "Copied" : "Copy pull request branch"}
1120 onClick={() => copyBranchToClipboard(detail.headBranch)}
1122 <code
1123 className={cn(
1124 "col-start-1 row-start-1 min-w-0 truncate transition-opacity duration-150 motion-reduce:transition-none",
1125 isBranchCopied ? "opacity-0" : "opacity-100",
1126 )}
1127 title={detail.headBranch}
1129 {detail.headBranch}
1130 </code>
1131 <span
1132 aria-hidden="true"
1133 className={cn(
1134 "col-start-1 row-start-1 truncate text-center transition-opacity duration-150 motion-reduce:transition-none",
1135 isBranchCopied ? "opacity-100" : "opacity-0",
1136 )}
1138 Copied
1139 </span>
1140 </button>
1141 <span className="ml-auto inline-flex shrink-0 items-center justify-end gap-2">
1142 <span className="inline-flex items-center gap-1.5 tabular-nums">
1143 <FileDiffIcon className="size-3.5" />
1144 {detail.changedFiles.toLocaleString()}{" "}
1145 {detail.changedFiles === 1 ? "file" : "files"}
1146 </span>
1147 <PullRequestDiffStat
1148 additions={detail.additions}
1149 deletions={detail.deletions}
1150 className="shrink-0 font-mono text-xs"
1151 />
1152 </span>
1153 </div>
1154 </div>
1155 ) : null}
1156​
1157 {detail && conflicting ? (
1158 <div className="col-span-2 flex items-center gap-1 px-4 pb-3">
1159 <Badge
1160 variant="error"
1161 className="h-auto gap-1.5 rounded-md px-3 py-1.5 text-xs text-destructive"
1163 <TriangleAlertIcon className="size-3.5" />
1164 Merge conflicts
1165 </Badge>
1166 <Button
1167 size="xs"
1168 variant="ghost"
1169 className="ml-auto text-destructive hover:bg-destructive/8 hover:text-destructive"
1170 disabled={handoff !== null}
1171 onClick={startResolveConflicts}
1173 {handoff === "conflicts" ? "Preparing..." : "Resolve in a new thread"}
1174 <ArrowUpRightIcon className="size-3.5 text-destructive" />
1175 </Button>
1176 </div>
1177 ) : null}
1178​
1179 {detail ? (
1180 <nav
1181 className="col-span-2 flex min-w-0 items-center gap-1 overflow-x-auto border-t border-border/60 px-4 py-2"
1182 aria-label="Pull request tabs"
1184 {visibleTabs.map((item) => (
1185 <button
1186 key={item.value}
1187 type="button"
1188 aria-pressed={tab === item.value}
1189 onClick={() => setTab(item.value)}
1190 className={cn(
1191 "inline-flex items-center gap-1.5 rounded-md px-3 py-1.5 text-xs transition-colors",
1192 tab === item.value
1193 ? "bg-accent text-foreground"
1194 : "text-muted-foreground hover:text-foreground",
1195 )}
1197 {item.label}
1198 </button>
1199 ))}
1200 {tab === "summary" ? (
1201 <span
1202 className="ml-auto inline-flex shrink-0 items-center gap-1.5 text-xs text-muted-foreground"
1203 aria-label={checksSummary ? `Checks: ${checksSummary}` : "Checks"}
1205 <CircleDotIcon aria-hidden className="size-3.5" />
1206 {checksSummary}
1207 </span>
1208 ) : tab === "timeline" ? (
1209 <div className="ml-auto flex shrink-0 items-center gap-2 text-xs text-muted-foreground">
1210 <PullRequestMetaLine
1211 className={cn(
1212 "whitespace-nowrap text-[11px] transition-opacity",
1213 (activityPending || activityError) && "opacity-35",
1214 )}
1216 <span
1217 className="inline-flex items-center gap-1"
1218 aria-label={
1219 activityError
1220 ? "Comments unavailable"
1221 : `${detail.commentCount.toLocaleString()} ${
1222 detail.commentCount === 1 ? "comment" : "comments"
1223 }`
1226 <MessageSquareIcon aria-hidden className="size-3" />
1227 {activityError
1228 ? "—"
1229 : activityPending
1230 ? "…"
1231 : detail.commentCount.toLocaleString()}
1232 </span>
1233 <span
1234 className="inline-flex items-center gap-1"
1235 aria-label={
1236 activityError
1237 ? "Commits unavailable"
1238 : `${detail.commits.length.toLocaleString()} ${
1239 detail.commits.length === 1 ? "commit" : "commits"
1240 }`
1243 <GitCommitHorizontalIcon aria-hidden className="size-3" />
1244 {activityError
1245 ? "—"
1246 : activityPending
1247 ? "…"
1248 : detail.commits.length.toLocaleString()}
1249 </span>
1250 </PullRequestMetaLine>
1251 <Button
1252 size="xs"
1253 variant="ghost"
1254 className="h-7 px-2 text-[10px] text-muted-foreground"
1255 aria-label={
1256 timelineOrder === "newest"
1257 ? "Show oldest activity first"
1258 : "Show newest activity first"
1260 onClick={() =>
1261 setTimelineOrder((value) => (value === "newest" ? "oldest" : "newest"))
1264 <ArrowDownUpIcon aria-hidden className="size-3" />
1265 {timelineOrder === "newest" ? "Newest first" : "Oldest first"}
1266 </Button>
1267 </div>
1268 ) : null}
1269 </nav>
1270 ) : null}
1271 </div>
1272 </div>
1273 </div>
1274​
1275 <div
1276 className="relative min-h-0 flex-1 overflow-hidden"
1277 // Scroll does not bubble, but it captures: one listener hears every tab's own scroll
1278 // container. Collapse past two line-heights, expand only back at the very top, so the
1279 // boundary row cannot flap the chrome open and shut.
1280 onScrollCapture={(event) => {
1281 if (chromeVariant !== "collapse") return;
1282 const scroller = event.target as HTMLElement;
1283 scrollerRef.current = scroller;
1284 const top = scroller.scrollTop;
1285 setChromeCondensed((previous) => {
1286 let next = previous;
1287 // `scrollHeight` reads the fold's natural height whichever state the track is in.
1288 const foldHeight = foldRef.current?.scrollHeight ?? 0;
1289 // The chrome trades the fold for the condensed second row, so the height the
1290 // scrollport actually gains is the difference between the two.
1291 const chromeDelta = foldHeight - (condensedRowRef.current?.scrollHeight ?? 0);
1292 if (previous) {
1293 // The hard top reopens the chrome. The refund puts the reader a fold's height
1294 // from the top, pinned to the same pixels — the metadata is scrolled up to,
1295 // not thrown at them.
1296 if (top < 4 && foldHeight > 0) {
1297 compensationRef.current = chromeDelta;
1298 next = false;
1300 } else if (foldHeight > 0 && top > foldHeight + 32) {
1301 compensationRef.current = -chromeDelta;
1302 next = true;
1304 chromeStateByTab.current[tab] = next;
1305 return next;
1306 });
1307 }}
1309 {detailQuery.isPending && !detail ? (
1310 // The ghost wears the shape of the tab being waited on, so switching tabs mid-load
1311 // does not flash a summary outline under a timeline heading.
1312 tab === "timeline" ? (
1313 <PullRequestTimelineGhost />
1314 ) : tab === "code" ? (
1315 <DiffPanelLoadingState label="Loading pull request diff..." />
1316 ) : (
1317 <PullRequestDetailGhost />
1319 ) : detailQuery.error && !detail ? (
1320 <PullRequestsUnavailableState error={detailQuery.error} onRetry={refreshDetail} />
1321 ) : detail ? (
1322 <>
1323 {mountedTabs.has("summary") ? (
1324 <div className={cn("absolute inset-0", tab !== "summary" && "invisible")}>
1325 <PullRequestSummaryTab
1326 environmentId={environmentId}
1327 reference={reference}
1328 detail={detail}
1329 activityPending={activityPending}
1330 activityError={activityError}
1331 pendingFinding={handoff}
1332 onFixFinding={startFixFinding}
1333 onRefresh={refreshDetail}
1334 />
1335 </div>
1336 ) : null}
1337 {mountedTabs.has("timeline") ? (
1338 <div className={cn("absolute inset-0", tab !== "timeline" && "invisible")}>
1339 {activityPending ? (
1340 <PullRequestTimelineGhost />
1341 ) : activityError ? (
1342 <PullRequestActivityUnavailableState
1343 error={activityError}
1344 onRetry={activityQuery.refresh}
1345 />
1346 ) : (
1347 <PullRequestTimelineTab
1348 detail={detail}
1349 order={timelineOrder}
1350 onOpenCommit={openCommit}
1351 />
1352 )}
1353 </div>
1354 ) : null}
1355 {mountedTabs.has("code") ? (
1356 <div className={cn("absolute inset-0", tab !== "code" && "invisible")}>
1357 <Suspense fallback={<DiffPanelLoadingState label="Loading pull request diff..." />}>
1358 <PullRequestCodeTab
1359 onAskAboutSelection={askAboutSelection}
1360 environmentId={environmentId}
1361 reference={reference}
1362 detail={detail}
1363 selectedCommitOid={selectedCodeCommitOid}
1364 onSelectedCommitChange={selectCodeCommit}
1365 pendingFinding={handoff}
1366 onFixFinding={startFixFinding}
1367 onRefresh={refreshDetail}
1368 refreshToken={refreshToken}
1369 />
1370 </Suspense>
1371 </div>
1372 ) : null}
1373 </>
1374 ) : null}
1375 </div>
1376​
1377 <AlertDialog
1378 open={confirmAction !== null}
1379 onOpenChange={(open) => !open && setConfirmAction(null)}
1381 <AlertDialogPopup>
1382 <AlertDialogHeader>
1383 <AlertDialogTitle>
1384 {confirmAction === "merge" ? "Merge pull request?" : "Close pull request?"}
1385 </AlertDialogTitle>
1386 <AlertDialogDescription>
1387 {confirmAction === "merge"
1388 ? `This merges #${reference.number} using ${selectedMergeMethod}.`
1389 : `This closes #${reference.number} without merging it.`}
1390 </AlertDialogDescription>
1391 </AlertDialogHeader>
1392 <AlertDialogFooter>
1393 <AlertDialogClose render={<Button variant="outline" size="sm" />}>
1394 Cancel
1395 </AlertDialogClose>
1396 <Button
1397 size="sm"
1398 variant={confirmAction === "close" ? "destructive" : "default"}
1399 disabled={actionPending}
1400 onClick={() => {
1401 const action = confirmAction;
1402 setConfirmAction(null);
1403 if (action === "merge") void perform("merge", selectedMergeMethod);
1404 if (action === "close") void perform("close");
1405 }}
1407 {confirmAction === "merge" ? "Merge" : "Close"}
1408 </Button>
1409 </AlertDialogFooter>
1410 </AlertDialogPopup>
1411 </AlertDialog>
1412 </div>
1413 );