The best way to control Claude Code, Codex and more from any computer or phone

main
tsx 2,230 lines 86.4 KB
Raw
1 import {
2 parsePullRequestAnchor,
3 pullRequestLinkCommit,
4 resolvePullRequestReviewAnchor,
5 type PullRequestAnchor,
6 } from "@t3tools/shared/pullRequestAnchor";
7 import { projectChangeRequestUrl } from "@t3tools/client-runtime/change-request-links";
8 import { normalizeThreadPullRequestKey } from "@t3tools/client-runtime/thread-pull-requests";
9 import { useAtomValue } from "@effect/atom-react";
10 import { usePullRequestStack } from "~/state/usePullRequestStack";
11 import { scopeProjectRef, scopeThreadRef } from "@t3tools/client-runtime/environment";
12 import {
13 isAtomCommandInterrupted,
14 squashAtomCommandFailure,
15 } from "@t3tools/client-runtime/state/runtime";
16 import {
17 AuthOrchestrationOperateScope,
18 AuthSourceControlWriteScope,
19 type EnvironmentId,
20 type PullRequestAction,
21 type PullRequestDetail,
22 type PullRequestMergeMethod,
23 type PullRequestListEntry,
24 type PullRequestUpdateMethod,
25 type PullRequestRef,
26 type PullRequestReviewGuideStop,
27 type PullRequestSummary,
28 resolveEnvironmentMachineKind,
29 type ScopedThreadRef,
30 } from "@t3tools/contracts";
31 import {
32 ArrowDownUpIcon,
33 ArrowLeftIcon,
34 CircleDotIcon,
35 FileDiffIcon,
36 GitCommitHorizontalIcon,
37 MessageSquareIcon,
38 PanelRightIcon,
39 } from "lucide-react";
40 import {
41 lazy,
42 Suspense,
43 useEffect,
44 useEffectEvent,
45 useLayoutEffect,
46 useRef,
47 useState,
48 } from "react";
49 import { msg, T, useGT, useMessages, Var } from "gt-react";
50
51 import { m } from "~/i18n/messages";
52
53 import { type DraftId, useComposerDraftStore } from "~/composerDraftStore";
54 import { type PullRequestDetailTab, useRightPanelStore } from "~/rightPanelStore";
55 import { useEnvironmentSettings } from "~/hooks/useSettings";
56 import { useNewThreadHandler } from "~/hooks/useHandleNewThread";
57 import { useCopyToClipboard } from "~/hooks/useCopyToClipboard";
58 import { isCommandPaletteOpen } from "~/commandPaletteBus";
59 import { resolveShortcutCommand, type ShortcutMatchContext } from "~/keybindings";
60 import { primaryServerKeybindingsAtom } from "~/state/server";
61 import {
62 usePullRequestDefaultMergeMethodResolver,
63 writeHandoffToComposer,
64 } from "./usePullRequestActions";
65 import { offHeadPullRequestCheckoutToast } from "./pullRequestCheckoutToast";
66 import { usePreparePullRequestThreadAction } from "~/state/sourceControlActions";
67 import { cn } from "~/lib/utils";
68 import { readLocalApi } from "~/localApi";
69 import type { ReviewCommentContext } from "~/reviewCommentContext";
70 import { useProjects, useServerConfigs } from "~/state/entities";
71 import { useEnvironments } from "~/state/environments";
72 import { useEnvironmentQuery } from "~/state/query";
73 import { readEnvironmentScope, useEnvironmentScope } from "~/state/session";
74 import { useLiveRefresh } from "~/hooks/useLiveRefresh";
75 import { pullRequestEnvironment, usePullRequestTurnRefresh } from "~/state/pullRequests";
76 import { useAtomCommand } from "~/state/use-atom-command";
77 import { PullRequestStackMenu } from "./PullRequestStackMenu";
78 import { pullRequestCompletionScope } from "./PullRequestMarkdownTextarea";
79 import { PullRequestChangeBreakdownStat } from "./PullRequestChangeBreakdownStat";
80 import { sourceControlClients } from "@t3tools/client-runtime/source-control-clients";
81 import { PullRequestThreadLinks } from "./PullRequestThreadLinks";
82 import { vcsEnvironment } from "~/state/vcs";
83 import { RelativeTime } from "~/components/RelativeTime";
84 import { useUiStateStore } from "~/uiStateStore";
85
86 import { Button } from "../ui/button";
87 import { toastManager } from "../ui/toast";
88 import { Tooltip, TooltipPopup, TooltipProvider, TooltipTrigger } from "../ui/tooltip";
89 import { MiddleTruncate } from "../ui/middle-truncate";
90 import {
91 PullRequestChecksStatusLine,
92 PullRequestDetailHeaderBody,
93 PullRequestDetailTabBar,
94 } from "./PullRequestDetailLayout";
95 import { PullRequestDetailGhost, PullRequestTimelineGhost } from "./PullRequestGhosts";
96 import { PullRequestCopyableCode } from "./PullRequestCopyableCode";
97 import { pullRequestRefKey, usePullRequestDetail } from "./usePullRequestDetail";
98 import { PullRequestActionsMenu } from "./PullRequestActionsMenu";
99 import {
100 PullRequestApproveWorkflowsButton,
101 PullRequestCheckoutMenu,
102 PullRequestPrimaryAction,
103 PullRequestResolveConflictsButton,
104 } from "./PullRequestDetailActions";
105 import { PullRequestBaseBranch } from "./PullRequestBaseBranch";
106 import { PullRequestDetailCrumbs } from "./PullRequestDetailCrumbs";
107 import { PullRequestTitleEditor } from "./PullRequestTitleEditor";
108 import { PullRequestActivityUnavailableState } from "./PullRequestActivityUnavailableState";
109 import { SourceControlAppAccessNotice } from "../SourceControlAppAccessNotice";
110 import { DiffPanelLoadingState } from "../DiffPanelShell";
111 import { PullRequestsUnavailableState } from "./PullRequestsUnavailableState";
112 import type { PullRequestAgentSelectionInput } from "./PullRequestCodeTab";
113 import { openOnHostLabel } from "./pullRequestLinkContextMenu";
114 import { PullRequestMarkdownContext } from "./PullRequestMarkdown";
115 import { pullRequestMarkdownPlugins } from "./pullRequestMarkdown.logic";
116 import { PullRequestComposer } from "./PullRequestComposer";
117 import { PullRequestSummaryTab } from "./PullRequestSummaryTab";
118 import { PullRequestTimelineTab } from "./PullRequestTimelineTab";
119 import {
120 buildAddSelectionToAgentHandoff,
121 buildAskAboutGuideStopHandoff,
122 buildAskAboutPullRequestHandoff,
123 buildExplainPullRequestHandoff,
124 buildFixFindingHandoff,
125 buildFixFindingsHandoff,
126 buildPullRequestCommentContext,
127 buildPullRequestContext,
128 buildResolveConflictsPrompt,
129 latestPullRequestReviewOutcomes,
130 loadingPullRequestCheckoutCommand,
131 isPullRequestNotFound,
132 isStackedPullRequestBase,
133 pullRequestActionNeedsHostRefresh,
134 pullRequestCheckoutCommand,
135 pullRequestTimelineEventMatches,
136 buildPullRequestTimeline,
137 pullRequestFindingKey,
138 pullRequestHandoffLabels,
139 PULL_REQUEST_MERGE_METHOD_LABELS,
140 checkoutFailureDescription,
141 readableFailure,
142 resolvePullRequestReferenceHost,
143 resolvePullRequestPrimaryControl,
144 allowedPullRequestMergeMethods,
145 allowsSinglePullRequestMerge,
146 canDeletePullRequestBranch,
147 isPullRequestConflicting,
148 resolveBaseFreshness,
149 resolvePullRequestMergeMethod,
150 type PullRequestChatSubject,
151 type PullRequestFinding,
152 shouldRefreshPullRequestActivity,
153 } from "./pullRequestDetail.logic";
154 import { resolvePickableEnvironments } from "./pullRequestProjectAssignment.logic";
155 import { PullRequestChecksPopover } from "./PullRequestChecksPopover";
156 import {
157 PullRequestActorLabel,
158 PullRequestMetaLine,
159 PullRequestReviewOutcomeIcon,
160 pullRequestChecksState,
161 pullRequestChecksStatePresentation,
162 pullRequestReviewOutcomeToneClassName,
163 resolvePullRequestState,
164 summarizePullRequestChecks,
165 } from "./pullRequestPresentation";
166 import { resolveFilterOptions } from "./pullRequestListOptions";
167 import { PullRequestGuideTab } from "./PullRequestGuideTab";
168 import { guideRunKey, useGuideRunStore } from "./guide/guideRunStore";
169 import { useReviewGuideWriter } from "./guide/useReviewGuideWriter";
170
171 import { changeRequestTermKind, type ChangeRequestTermKind } from "./changeRequestTerm";
172
173 const actionFailureLabels = (term: ChangeRequestTermKind): Record<PullRequestAction, string> => ({
174 merge: m(
175 msg(
176 "Could not merge this {term, select, mr {merge request} cr {change request} other {pull request}}",
177 { term },
178 ),
179 ),
180 ready: m(msg("Could not mark this ready for review")),
181 draft: m(msg("Could not convert this to a draft")),
182 close: m(
183 msg(
184 "Could not close this {term, select, mr {merge request} cr {change request} other {pull request}}",
185 { term },
186 ),
187 ),
188 reopen: m(
189 msg(
190 "Could not reopen this {term, select, mr {merge request} cr {change request} other {pull request}}",
191 { term },
192 ),
193 ),
194 "update-branch": m(msg("Could not update this branch")),
195 "enable-auto-merge": m(msg("Could not turn on auto-merge")),
196 "disable-auto-merge": m(msg("Could not turn off auto-merge")),
197 revert: m(
198 msg(
199 "Could not open a revert {term, select, mr {merge request} cr {change request} other {pull request}}",
200 { term },
201 ),
202 ),
203 "delete-branch": m(msg("Could not delete this branch")),
204 "approve-workflows": m(msg("Could not approve workflows")),
205 });
206
207 const actionFailureHints = (term: ChangeRequestTermKind): Record<PullRequestAction, string> => ({
208 merge: m(
209 msg(
210 "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.",
211 ),
212 ),
213 ready: m(msg("The host refused it. Check that you have write access to this repository.")),
214 draft: m(msg("The host refused it. Check that you have write access to this repository.")),
215 close: m(msg("The host refused it. Check that you have write access, or that you opened it.")),
216 reopen: m(
217 msg("The host refused it. Check that you have write access, and that the branch still exists."),
218 ),
219 "update-branch": m(
220 msg(
221 "The host refused it. Check that you have write access to the branch (a fork branch also needs its author to allow edits from maintainers), and that it does not conflict with the base.",
222 ),
223 ),
224 "enable-auto-merge": m(
225 msg(
226 "The host refused it. Check that this repository allows auto-merge, that you have write access, and that there is something left for it to wait on.",
227 ),
228 ),
229 "disable-auto-merge": m(
230 msg(
231 "The host refused it. Check that you have write access, and that the merge has not already happened.",
232 ),
233 ),
234 revert: m(
235 msg(
236 "The host refused it. Check that you have write access and that this {term, select, mr {merge request} cr {change request} other {pull request}} was merged on the host.",
237 { term },
238 ),
239 ),
240 "delete-branch": m(
241 msg(
242 "The host refused it. Check that you have write access to the source repository and that the branch has not moved since this page loaded.",
243 ),
244 ),
245 "approve-workflows": m(
246 msg(
247 "The host refused it. Check that you have Actions write access and that these workflow runs are still awaiting approval.",
248 ),
249 ),
250 });
251
252 const AUTO_MERGE_LABELS: Record<PullRequestMergeMethod, string> = {
253 merge: msg("Auto-merge (merge)"),
254 squash: msg("Auto-merge (squash and merge)"),
255 rebase: msg("Auto-merge (rebase and merge)"),
256 "fast-forward": msg("Auto-merge (fast-forward merge)"),
257 };
258
259 const UPDATE_BRANCH_REBASE_FAILURE_HINT = msg(
260 "The host refused it. A rebase stops at the first commit that does not apply cleanly; updating with a merge commit may still work.",
261 );
262
263 const TABS: ReadonlyArray<{ value: PullRequestDetailTab; label: string }> = [
264 { value: "summary", label: msg("Summary", { $context: "pull request tab" }) },
265 { value: "guide", label: msg("Guide", { $context: "pull request tab" }) },
266 { value: "timeline", label: msg("Timeline", { $context: "pull request tab" }) },
267 { value: "code", label: msg("Code", { $context: "pull request tab" }) },
268 ];
269
270 // Defer the diff viewer's worker pool until Code is approached.
271 const loadCodeTab = () => import("./PullRequestCodeTab");
272 const PullRequestCodeTab = lazy(loadCodeTab);
273
274 function reportCheckoutCommandError(error: Error) {
275 toastManager.add({
276 type: "error",
277 title: m(msg("Could not copy checkout command")),
278 description: error.message,
279 });
280 }
281
282 function resolvePullRequestReference(
283 requestedReference: PullRequestRef,
284 repositoryIdentity: Parameters<typeof resolvePullRequestReferenceHost>[1],
285 supportsThreadPullRequests: boolean,
286 ): PullRequestRef {
287 return supportsThreadPullRequests
288 ? resolvePullRequestReferenceHost(requestedReference, repositoryIdentity)
289 : {
290 projectId: requestedReference.projectId,
291 repository: requestedReference.repository,
292 number: requestedReference.number,
293 };
294 }
295
296 function pullRequestMarkdownContext(
297 detail: Pick<PullRequestDetail, "provider" | "url" | "repository"> | null,
298 threadRef: ScopedThreadRef | null,
299 ) {
300 return {
301 remarkPlugins: pullRequestMarkdownPlugins(detail),
302 lineBreaks: sourceControlClients.find(detail?.provider ?? "")?.hardLineBreaks ?? false,
303 threadRef,
304 repository: detail?.repository ?? null,
305 };
306 }
307
308 function pullRequestStackReference(
309 detail: Pick<PullRequestDetail, "url" | "capabilities"> | null,
310 reference: PullRequestRef,
311 supportsThreadPullRequests: boolean,
312 ) {
313 return detail === null || detail.capabilities.stacks !== true || !supportsThreadPullRequests
314 ? null
315 : {
316 ...reference,
317 host: reference.host ?? sourceControlClients.parseChangeRequestUrl(detail.url)?.link.host,
318 };
319 }
320
321 function linkedTab(anchor: PullRequestAnchor | null): PullRequestDetailTab | null {
322 switch (anchor?.kind) {
323 case "code":
324 case "diff":
325 return "code";
326 case "commits":
327 case "timeline":
328 return "timeline";
329 case "checks":
330 case "summary":
331 return "summary";
332 default:
333 return null;
334 }
335 }
336
337 export function PullRequestDetailPanel({
338 environmentId,
339 shortcutsEnabled,
340 getShortcutContext,
341 threadRef = null,
342 reference: requestedReference,
343 listEntry = null,
344 refreshToken: forcedRefreshToken = 0,
345 tabOnPage = false,
346 onActed,
347 onClose,
348 context = "page",
349 composerDraftTarget,
350 onBack,
351 onSelectPullRequest,
352 onGuideShown,
353 revealUrl,
354 onRevealSettled,
355 initialTab = "summary",
356 onTabChange,
357 }: {
358 environmentId: EnvironmentId;
359 shortcutsEnabled: boolean;
360 getShortcutContext: () => ShortcutMatchContext;
361 onSelectPullRequest?: ((reference: PullRequestRef) => void) | undefined;
362 threadRef?: ScopedThreadRef | null;
363 reference: PullRequestRef;
364 listEntry?: PullRequestListEntry | null;
365 refreshToken?: number;
366 /**
367 * The pull requests page's panel: its tab lives in the guide run store, where a review guide
368 * notification can switch it.
369 */
370 tabOnPage?: boolean;
371 onActed?: (
372 action?: PullRequestAction,
373 phase?: "sent" | "done" | "failed",
374 reply?: PullRequestSummary,
375 ) => void;
376 onClose?: () => void;
377 context?: "page" | "thread";
378 composerDraftTarget?: ScopedThreadRef | DraftId;
379 onBack?: (() => void) | undefined;
380 onGuideShown?: (() => void) | undefined;
381 /** A clicked link into this pull request, waiting to be shown. */
382 revealUrl?: string | undefined;
383 /** Reports the link it was given shown or missing, so a newer link stays pending. */
384 onRevealSettled?: ((revealUrl: string) => void) | undefined;
385 initialTab?: PullRequestDetailTab;
386 onTabChange?: ((tab: PullRequestDetailTab) => void) | undefined;
387 }) {
388 const gt = useGT();
389 const resolve = useMessages();
390 const environmentConfigs = useServerConfigs();
391 const projects = useProjects();
392 const project = projects.find(
393 (project) =>
394 project.id === requestedReference.projectId && project.environmentId === environmentId,
395 );
396 const repositoryIdentity = project?.repositoryIdentity;
397 const supportsThreadPullRequests = environmentConfigs.get(environmentId) !== undefined;
398 const reference = resolvePullRequestReference(
399 requestedReference,
400 repositoryIdentity,
401 supportsThreadPullRequests,
402 );
403 const loadingCheckoutCommand = loadingPullRequestCheckoutCommand(reference, repositoryIdentity);
404 const unavailableHostUrl = projectChangeRequestUrl(
405 repositoryIdentity,
406 reference.repository,
407 reference.number,
408 );
409 const pullRequestKey = pullRequestRefKey(reference);
410 const matchingListEntry =
411 listEntry?.projectId === reference.projectId &&
412 listEntry.repository.toLowerCase() === reference.repository.toLowerCase() &&
413 (reference.host === undefined ||
414 listEntry.host.toLowerCase() === reference.host.toLowerCase()) &&
415 listEntry.number === reference.number
416 ? listEntry
417 : null;
418 const linkedReference = sourceControlClients.parseChangeRequestUrl(
419 matchingListEntry?.url ?? unavailableHostUrl ?? "",
420 )?.link;
421 useEnvironmentQuery(
422 context === "page" &&
423 supportsThreadPullRequests &&
424 linkedReference &&
425 (reference.host === undefined ||
426 reference.host.toLowerCase() === linkedReference.host.toLowerCase())
427 ? pullRequestEnvironment.linkedThreads({
428 environmentId,
429 input: { ...reference, ...normalizeThreadPullRequestKey(linkedReference) },
430 })
431 : null,
432 );
433 useEnvironmentQuery(pullRequestEnvironment.changeBreakdown({ environmentId, input: reference }));
434 const [threadPickerOpen, setThreadPickerOpen] = useState(false);
435 const [openReviewRequest, setOpenReviewRequest] = useState(0);
436 const {
437 canWriteSourceControl,
438 detailQuery,
439 activityQuery,
440 activity,
441 sharedSummary,
442 coreDetail,
443 detail,
444 } = usePullRequestDetail(environmentId, reference, matchingListEntry);
445 const revealAnchor = parsePullRequestAnchor(revealUrl);
446 const [selectedTab, setTab] = useState<PullRequestDetailTab>(
447 () => linkedTab(revealAnchor) ?? initialTab,
448 );
449 const reviewGuidesEnabled = useEnvironmentSettings(
450 environmentId,
451 (settings) => settings.reviewGuidesEnabled,
452 );
453 const guideKey = guideRunKey(environmentId, reference);
454 const pageTab = useGuideRunStore((state) =>
455 tabOnPage && state.pageDetailTab?.key === guideKey ? state.pageDetailTab.tab : null,
456 );
457 const requestedTab = tabOnPage ? (pageTab ?? initialTab) : selectedTab;
458 const isTabAvailable = (value: PullRequestDetailTab) =>
459 (value !== "code" || detail === null || detail.capabilities.diff) &&
460 (value !== "guide" || reviewGuidesEnabled);
461 // An unavailable tab falls back without overwriting the saved selection.
462 const tab = isTabAvailable(requestedTab) ? requestedTab : "summary";
463 const selectTab = (next: PullRequestDetailTab) => {
464 if (tabOnPage) useGuideRunStore.getState().showPageDetailTab(guideKey, next);
465 else setTab(next);
466 onTabChange?.(next);
467 };
468 const [timelineOrder, setTimelineOrder] = useState<"newest" | "oldest">("newest");
469 const [codeCommitScope, setCodeCommitScope] = useState<{
470 readonly pullRequestKey: string;
471 readonly oid: string | null;
472 }>(() => ({ pullRequestKey, oid: pullRequestLinkCommit(revealUrl) }));
473 const selectedCodeCommitOid =
474 codeCommitScope.pullRequestKey === pullRequestKey ? codeCommitScope.oid : null;
475 const selectCodeCommit = (oid: string | null) => {
476 setCodeCommitScope({ pullRequestKey, oid });
477 };
478 const openCommit = (oid: string) => {
479 selectCodeCommit(oid);
480 selectTab("code");
481 };
482 const [codeRevealRequest, setCodeRevealRequest] = useState<{
483 readonly path: string;
484 readonly nonce: number;
485 } | null>(null);
486 const openFileInCode = (path: string) => {
487 selectCodeCommit(null);
488 setCodeRevealRequest((previous) => ({ path, nonce: (previous?.nonce ?? 0) + 1 }));
489 void loadCodeTab();
490 selectTab("code");
491 };
492 // Cached activity can predate a linked comment, so a miss waits for one host read. `after` is
493 // when that read's invalidation finished; null while it runs.
494 const revealHostRead = useRef<{ readonly url: string; readonly after: number | null } | null>(
495 null,
496 );
497 const settleReveal = (url: string) => {
498 revealHostRead.current = null;
499 onRevealSettled?.(url);
500 };
501 const followLink = useEffectEvent(() => {
502 if (revealUrl === undefined) return;
503 const next = linkedTab(revealAnchor);
504 if (next === null) return settleReveal(revealUrl);
505 if (next === "code") {
506 selectCodeCommit(pullRequestLinkCommit(revealUrl));
507 void loadCodeTab();
508 }
509 selectTab(next);
510 // These name a tab, not a place in it.
511 if (revealAnchor?.kind === "code" || revealAnchor?.kind === "commits") settleReveal(revealUrl);
512 });
513 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- a clicked link lives in the panel store and selects its tab even when the panel is already mounted
514 useEffect(() => {
515 // oxlint-disable-next-line react/set-state-in-effect -- link navigation selects the PR tab and commit scope
516 followLink();
517 // oxlint-disable-next-line react/exhaustive-effect-dependencies -- each clicked link is a navigation request
518 }, [revealUrl]);
519 const tabScopeKey = `${environmentId}:${pullRequestKey}`;
520 const [tabMountState, setTabMountState] = useState(() => ({
521 key: tabScopeKey,
522 tabs: new Set<PullRequestDetailTab>([tab]),
523 }));
524 // Hidden Code tabs must not fetch later pull requests' diffs.
525 const mountedTabs =
526 tabMountState.key === tabScopeKey ? tabMountState.tabs : new Set<PullRequestDetailTab>([tab]);
527 if (tabMountState.key !== tabScopeKey) {
528 setTabMountState({ key: tabScopeKey, tabs: new Set([tab]) });
529 } else if (!tabMountState.tabs.has(tab)) {
530 setTabMountState({ key: tabScopeKey, tabs: new Set(tabMountState.tabs).add(tab) });
531 }
532 // A pointer on the Code tab reads the page it opens on; only intent costs the host a read.
533 const [codeIntentKey, setCodeIntentKey] = useState<string | null>(null);
534 useEnvironmentQuery(
535 codeIntentKey === pullRequestKey && !mountedTabs.has("code")
536 ? pullRequestEnvironment.diff({ environmentId, input: { ...reference } })
537 : null,
538 );
539 // Each tab restores the condensed state its own scrolling left behind.
540 const [condensedByTab, setCondensedByTab] = useState<
541 Partial<Record<PullRequestDetailTab, boolean>>
542 >({});
543 const condensed = condensedByTab[tab] ?? false;
544 const scrollerByTab = useRef<Partial<Record<PullRequestDetailTab, HTMLElement | null>>>({});
545 // Fresh ref callbacks would detach and reattach every scroller on each render.
546 const [scrollerRefs] = useState(() => ({
547 summary: (node: HTMLElement | null) => {
548 scrollerByTab.current.summary = node;
549 },
550 timeline: (node: HTMLElement | null) => {
551 scrollerByTab.current.timeline = node;
552 },
553 code: (node: HTMLElement | null) => {
554 scrollerByTab.current.code = node;
555 },
556 }));
557 const foldRef = useRef<HTMLDivElement | null>(null);
558 const condensedRowRef = useRef<HTMLDivElement | null>(null);
559 // Save the target before collapse: the browser may clamp scrollTop as the viewport grows,
560 // so applying a delta afterward would compensate twice.
561 const compensationRef = useRef<{
562 tab: PullRequestDetailTab;
563 scroller: HTMLElement;
564 target: number;
565 } | null>(null);
566 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- restores the scroller's scrollTop before paint after the header condenses
567 useLayoutEffect(() => {
568 const compensation = compensationRef.current;
569 if (compensation === null) return;
570 compensationRef.current = null;
571 if (
572 !condensed ||
573 compensation.tab !== tab ||
574 scrollerByTab.current[tab] !== compensation.scroller
575 )
576 return;
577 compensation.scroller.scrollTop = Math.max(0, compensation.target);
578 }, [condensed, tab]);
579 const lastSelectedMergeMethod = useUiStateStore((state) => state.pullRequestMergeMethod);
580 const setLastSelectedMergeMethod = useUiStateStore((state) => state.setPullRequestMergeMethod);
581 const resolveProjectDefaultMergeMethod = usePullRequestDefaultMergeMethodResolver(
582 environmentId,
583 reference.projectId,
584 );
585 const projectDefaultMergeMethod = resolveProjectDefaultMergeMethod();
586 const [mergeMethodSelection, setMergeMethodSelection] = useState<{
587 readonly pullRequestKey: string;
588 readonly method: PullRequestMergeMethod;
589 } | null>(null);
590 const setMergeMethod = (method: PullRequestMergeMethod) => {
591 setMergeMethodSelection({ pullRequestKey, method });
592 };
593 const [handoff, setHandoff] = useState<string | null>(null);
594 const turnRefresh = usePullRequestTurnRefresh(environmentId);
595 const handoffSummary = detail ?? sharedSummary;
596 const terminology = sourceControlClients.get(
597 handoffSummary?.provider ?? listEntry?.provider ?? repositoryIdentity?.provider,
598 ).changeRequest;
599 const keybindings = useAtomValue(primaryServerKeybindingsAtom);
600 const { copyToClipboard: copyReference } = useCopyToClipboard<string>({
601 target: {
602 target: `${terminology.singular} reference`,
603 unavailableMessage: msg(
604 "Clipboard API is unavailable while copying {term, select, mr {merge request} cr {change request} other {pull request}} reference.",
605 { term: changeRequestTermKind(terminology) },
606 ),
607 failureMessage: msg(
608 "Failed to copy {term, select, mr {merge request} cr {change request} other {pull request}} reference to the clipboard.",
609 { term: changeRequestTermKind(terminology) },
610 ),
611 },
612 onError: (error, failureTitle) =>
613 toastManager.add({
614 type: "error",
615 title: failureTitle,
616 description: error.message,
617 }),
618 });
619 const copyFromShortcut = useEffectEvent((event: KeyboardEvent) => {
620 if (!shortcutsEnabled || event.defaultPrevented || isCommandPaletteOpen()) return;
621 const command = resolveShortcutCommand(event, keybindings, {
622 context: getShortcutContext(),
623 });
624 if (command !== "pullRequest.copyNumber") return;
625 event.preventDefault();
626 event.stopPropagation();
627 if (!event.repeat)
628 copyReference(
629 `#${reference.number}`,
630 m(
631 msg("Failed to copy {term, select, mr {MR} cr {change request} other {PR}} number", {
632 term: changeRequestTermKind(terminology),
633 }),
634 ),
635 );
636 });
637 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- window keydown capture listener for the copy-number shortcut
638 useEffect(() => {
639 const onKeyDown = (event: KeyboardEvent) => copyFromShortcut(event);
640 window.addEventListener("keydown", onKeyDown, true);
641 return () => window.removeEventListener("keydown", onKeyDown, true);
642 }, []);
643 const autoMergeKey = `${pullRequestKey}:${detail?.autoMergeMethod ?? ""}`;
644 const [seenAutoMergeKey, setSeenAutoMergeKey] = useState<string | null>(null);
645 if (seenAutoMergeKey !== autoMergeKey) {
646 setSeenAutoMergeKey(autoMergeKey);
647 if (detail?.autoMergeMethod !== undefined) setMergeMethod(detail.autoMergeMethod);
648 }
649 const repositoryUrl =
650 detail === null
651 ? null
652 : (sourceControlClients.parseChangeRequestUrl(detail.url)?.link.repositoryUrl ?? null);
653 const hostClient = sourceControlClients.get(detail?.provider);
654 const openOnHostText = openOnHostLabel(hostClient, resolve);
655 const markdownContext = pullRequestMarkdownContext(detail, threadRef);
656 const authorProfileUrl =
657 detail?.author && repositoryUrl !== null
658 ? hostClient.authorProfileUrl(detail.author.login, repositoryUrl)
659 : null;
660 const checkoutCommand = handoffSummary
661 ? pullRequestCheckoutCommand(
662 handoffSummary.provider,
663 handoffSummary.number,
664 handoffSummary.headBranch,
665 detail?.headRepositoryNameWithOwner,
666 sourceControlClients.parseChangeRequestUrl(handoffSummary.url)?.link.repositoryUrl ?? null,
667 )
668 : loadingCheckoutCommand;
669 const branchRefsQuery = useEnvironmentQuery(
670 detail === null
671 ? null
672 : vcsEnvironment.listRefs({
673 environmentId,
674 input: {
675 cwd: detail.workspaceRoot,
676 includeMatchingRemoteRefs: true,
677 limit: 2,
678 },
679 }),
680 );
681 const isStackedPullRequest =
682 detail !== null &&
683 isStackedPullRequestBase(detail.baseBranch, branchRefsQuery.data?.refs ?? []);
684 const stackReference = pullRequestStackReference(detail, reference, supportsThreadPullRequests);
685 const nativeStackQuery = usePullRequestStack(environmentId, stackReference);
686 const nativeStack = nativeStackQuery.data;
687 const supportsStackActions =
688 supportsThreadPullRequests &&
689 detail?.capabilities.stacks === true &&
690 detail.capabilities.stackActions === true;
691 const canMergeSinglePullRequest = allowsSinglePullRequestMerge({
692 supportsStackActions,
693 hasStack: nativeStack !== null,
694 stackPending: !nativeStackQuery.isFresh,
695 stackError: nativeStackQuery.error,
696 });
697 const stackOwnsMerge = supportsStackActions && nativeStack !== null;
698 const mergeBlockedReason = canMergeSinglePullRequest
699 ? null
700 : nativeStackQuery.error
701 ? gt("Couldn't check stack membership")
702 : gt("Checking stack membership…");
703 const activityPending = activityQuery.isPending && activity === null;
704 const activityError = activity === null ? activityQuery.error : null;
705 const refreshDetail = () => {
706 detailQuery.refresh();
707 activityQuery.refresh();
708 nativeStackQuery.refresh();
709 };
710 const [refreshToken, setRefreshToken] = useState(0);
711 const [activityRevision, setActivityRevision] = useState<{
712 readonly key: string;
713 readonly updatedAt: string;
714 } | null>(null);
715 const [activityRevalidations, setActivityRevalidations] = useState(0);
716 const coreUpdatedAt = coreDetail?.updatedAt ?? null;
717 if (
718 coreUpdatedAt !== null &&
719 (activityRevision?.key !== tabScopeKey || activityRevision.updatedAt !== coreUpdatedAt)
720 ) {
721 const next = { key: tabScopeKey, updatedAt: coreUpdatedAt };
722 if (!shouldRefreshPullRequestActivity(activityRevision, next)) {
723 setActivityRevision(next);
724 } else if (!activityQuery.isPending) {
725 // Interrupting a mutation's activity refresh can leave SWR displaying stale data.
726 setActivityRevision(next);
727 setActivityRevalidations((count) => count + 1);
728 setRefreshToken((token) => token + 1);
729 }
730 }
731 const revalidateActivity = useEffectEvent(() => activityQuery.refresh());
732 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- refreshes the activity query after commit when render counts a new detail revision
733 useEffect(() => {
734 if (activityRevalidations > 0) revalidateActivity();
735 }, [activityRevalidations]);
736 useLiveRefresh(
737 () => {
738 detailQuery.refresh();
739 },
740 { key: `pull-request:${environmentId}:${pullRequestKey}` },
741 );
742 const invalidate = useAtomCommand(pullRequestEnvironment.invalidate, { reportFailure: false });
743 const [isInvalidating, setIsInvalidating] = useState(false);
744 const refreshing = isInvalidating || detailQuery.isPending;
745 /** Resolves whether the host cache was invalidated before the refetch. */
746 const refetchFromHost = async () => {
747 setIsInvalidating(true);
748 // Atom commands settle without throwing, so reset always runs.
749 const invalidated = await invalidate({ environmentId, input: { reference } });
750 refreshDetail();
751 setRefreshToken((token) => token + 1);
752 setIsInvalidating(false);
753 return invalidated._tag === "Success";
754 };
755 const refreshFromHost = async () => {
756 await refetchFromHost();
757 };
758 const timelineAnchor =
759 revealAnchor?.kind !== "timeline"
760 ? null
761 : detail === null
762 ? revealAnchor.anchor
763 : resolvePullRequestReviewAnchor(
764 revealAnchor.anchor,
765 detail.comments,
766 detail.reviewThreads,
767 );
768 // Loaded activity without the linked item, keyed by load so a refetch is checked again.
769 const revealMissedAt =
770 timelineAnchor !== null &&
771 detail !== null &&
772 !activityQuery.isPending &&
773 !buildPullRequestTimeline(detail, resolve).some((event) =>
774 pullRequestTimelineEventMatches(event, timelineAnchor),
775 )
776 ? activityQuery.dataUpdatedAt
777 : null;
778 const revealReadFailed = revealMissedAt !== null && activityQuery.error !== null;
779 const readHostForReveal = useEffectEvent(() => {
780 if (revealUrl === undefined || revealMissedAt === null) return;
781 const read = revealHostRead.current;
782 if (read?.url !== revealUrl) {
783 const request = { url: revealUrl, after: null };
784 revealHostRead.current = request;
785 void refetchFromHost().then((invalidated) => {
786 if (revealHostRead.current !== request) return;
787 // Without an invalidation the refetch could only repeat the cached read.
788 if (!invalidated) return settleReveal(request.url);
789 revealHostRead.current = { url: request.url, after: Date.now() };
790 });
791 return;
792 }
793 // A read that finished before the invalidation cannot show the item is missing. `after` is
794 // stamped once the refetch was requested, so a read in that same millisecond is the new one.
795 if (read.after !== null && (revealReadFailed || revealMissedAt >= read.after)) {
796 settleReveal(revealUrl);
797 }
798 });
799 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- a linked comment missing from cached activity asks the host once before the link settles
800 useEffect(() => {
801 readHostForReveal();
802 // oxlint-disable-next-line react/exhaustive-effect-dependencies -- each load that misses the linked item is checked against the host read
803 }, [revealMissedAt, revealReadFailed, revealUrl]);
804 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- a host read outliving the panel must not settle a later link
805 useEffect(
806 () => () => {
807 revealHostRead.current = null;
808 },
809 [],
810 );
811 const refreshFromHostOnRequest = useEffectEvent(() => void refreshFromHost());
812 const appliedForcedToken = useRef(forcedRefreshToken);
813 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- a new forced refresh token invalidates the host cache and refetches
814 useEffect(() => {
815 if (appliedForcedToken.current === forcedRefreshToken) return;
816 appliedForcedToken.current = forcedRefreshToken;
817 refreshFromHostOnRequest();
818 }, [forcedRefreshToken]);
819 const runAction = useAtomCommand(pullRequestEnvironment.runAction, {
820 reportFailure: false,
821 });
822 const postComment = useAtomCommand(pullRequestEnvironment.comment, {
823 reportFailure: false,
824 });
825 const [pendingAction, setPendingAction] = useState<PullRequestAction | null>(null);
826 const actionPending = pendingAction !== null;
827 const newThread = useNewThreadHandler();
828 const { environments } = useEnvironments();
829 const pickableEnvironments =
830 context === "page"
831 ? resolvePickableEnvironments(
832 { environmentId, projectId: reference.projectId },
833 projects,
834 environments.map((environment) => ({
835 environmentId: environment.environmentId,
836 label: environment.label,
837 machine: resolveEnvironmentMachineKind(environment.serverConfig),
838 })),
839 )
840 : [];
841 const [actingScope, setActingScope] = useState<{
842 readonly pullRequestKey: string;
843 readonly environmentId: EnvironmentId;
844 } | null>(null);
845 const chosenEnvironmentId =
846 actingScope?.pullRequestKey === pullRequestKey ? actingScope.environmentId : environmentId;
847 const acting =
848 pickableEnvironments.find((entry) => entry.environmentId === chosenEnvironmentId) ?? null;
849 const actingEnvironmentId = acting?.environmentId ?? environmentId;
850 const checkoutRoot =
851 acting?.workspaceRoot ?? detail?.workspaceRoot ?? project?.workspaceRoot ?? null;
852 const canOperateThread = useEnvironmentScope(actingEnvironmentId, AuthOrchestrationOperateScope);
853 const prepareThread = usePreparePullRequestThreadAction({
854 environmentId: actingEnvironmentId,
855 cwd: checkoutRoot,
856 });
857
858 const finishAction = async (
859 action: PullRequestAction,
860 method?: PullRequestMergeMethod,
861 updateMethod?: PullRequestUpdateMethod,
862 ) => {
863 onActed?.(action, "sent");
864 const result = await runAction({
865 environmentId,
866 input: {
867 ...reference,
868 action,
869 ...(method ? { mergeMethod: method } : {}),
870 ...(updateMethod ? { updateMethod } : {}),
871 },
872 });
873 setPendingAction(null);
874 if (result._tag === "Failure") {
875 // Azure DevOps provides no strategy availability; explain policy failures after the attempt.
876 const failure = squashAtomCommandFailure(result);
877 const hint =
878 updateMethod === "rebase"
879 ? m(UPDATE_BRANCH_REBASE_FAILURE_HINT)
880 : actionFailureHints(changeRequestTermKind(terminology))[action];
881 toastManager.add({
882 type: "error",
883 title: actionFailureLabels(changeRequestTermKind(terminology))[action],
884 description: readableFailure(failure, hint),
885 });
886 onActed?.(action, "failed");
887 return false;
888 }
889 if (action === "revert") {
890 toastManager.add({
891 type: "success",
892 title: m(
893 msg(
894 "Revert {term, select, mr {merge request} cr {change request} other {pull request}} opened",
895 { term: changeRequestTermKind(terminology) },
896 ),
897 ),
898 });
899 }
900 if (action === "delete-branch") {
901 toastManager.add({ type: "success", title: m(msg("Branch deleted")) });
902 }
903 if (pullRequestActionNeedsHostRefresh(action)) {
904 void refreshFromHost();
905 } else {
906 // The action command already showed the reply in the detail or re-read it.
907 activityQuery.refresh();
908 nativeStackQuery.refresh();
909 }
910 onActed?.(action, "done", result.value);
911 return true;
912 };
913
914 const perform = async (
915 action: PullRequestAction,
916 method?: PullRequestMergeMethod,
917 updateMethod?: PullRequestUpdateMethod,
918 ) => {
919 if (!canWriteSourceControl || pendingAction !== null) return false;
920 setPendingAction(action);
921 return finishAction(action, method, updateMethod);
922 };
923
924 const performCommentAction = async (body: string, action: "close" | "reopen") => {
925 if (!canWriteSourceControl || pendingAction !== null) return { commentPosted: false };
926 setPendingAction(action);
927 const commentResult = await postComment({
928 environmentId,
929 input: { ...reference, body },
930 });
931 if (commentResult._tag === "Failure") {
932 setPendingAction(null);
933 toastManager.add({ type: "error", title: m(msg("Could not post the comment")) });
934 return { commentPosted: false };
935 }
936 const actionSucceeded = await finishAction(action);
937 // Refresh the posted comment even if the subsequent state change fails.
938 if (!actionSucceeded) refreshDetail();
939 return { commentPosted: true };
940 };
941
942 type ThreadTask = {
943 prompt: string;
944 reviewComments?: ReadonlyArray<ReviewCommentContext>;
945 };
946
947 const attachTarget = composerDraftTarget ?? null;
948 const canPrepareWorktree = prepareThread.isAllowed && canOperateThread;
949 const canFixFindings = attachTarget !== null || canPrepareWorktree;
950 const handoffLabels = pullRequestHandoffLabels(attachTarget !== null, resolve);
951 const guideWriter = useReviewGuideWriter({
952 environmentId,
953 reference,
954 title: detail?.title ?? null,
955 });
956 const writeGuide = () => {
957 void guideWriter.write();
958 if (guideWriter.data?.guide == null) selectTab("guide");
959 };
960
961 const openThreadWithTask = async (
962 projectRef: ReturnType<typeof scopeProjectRef>,
963 task: ThreadTask | null,
964 opened?: { draftId: DraftId },
965 ): Promise<{ draftId: DraftId } | null> => {
966 const session =
967 opened ??
968 (await newThread(projectRef).then(
969 (result) => result,
970 () => null,
971 ));
972 if (session === null) return null;
973 if (task === null) return session;
974 writeHandoffToComposer(session.draftId, task);
975 return session;
976 };
977
978 const startAsk = async (
979 kind: string,
980 task: ThreadTask,
981 options?: { readonly keepGuide?: boolean },
982 ) => {
983 if (!detail || handoff !== null) return;
984 if (attachTarget !== null) {
985 writeHandoffToComposer(attachTarget, task);
986 toastManager.add({
987 type: "success",
988 title: m(msg("Added to the composer")),
989 description:
990 task.prompt.length > 0
991 ? m(msg("The question is in the composer. Read it over, then send."))
992 : m(
993 msg(
994 "The {term, select, mr {merge request} cr {change request} other {pull request}} is in the composer. Type your question, then send.",
995 {
996 term: changeRequestTermKind(terminology),
997 },
998 ),
999 ),
1000 });
1001 return;
1002 }
1003 setHandoff(kind);
1004 const projectRef = scopeProjectRef(actingEnvironmentId, acting?.projectId ?? detail.projectId);
1005 const opened = await openThreadWithTask(projectRef, task);
1006 setHandoff(null);
1007 if (opened !== null && options?.keepGuide === true) {
1008 const draft = useComposerDraftStore.getState().getDraftSession(opened.draftId);
1009 if (draft !== null) {
1010 useRightPanelStore
1011 .getState()
1012 .openPullRequest(scopeThreadRef(draft.environmentId, draft.threadId), {
1013 environmentId,
1014 projectId: reference.projectId,
1015 ...(reference.host === undefined ? {} : { host: reference.host }),
1016 repository: reference.repository,
1017 number: reference.number,
1018 url: detail.url,
1019 detailTab: "guide",
1020 });
1021 }
1022 }
1023 if (opened === null) {
1024 toastManager.add({
1025 type: "error",
1026 title: m(msg("Could not open a thread")),
1027 description: m(msg("Try again from the project, or open a thread first.")),
1028 });
1029 return;
1030 }
1031 toastManager.add({
1032 type: "success",
1033 title: m(msg("Asked in a thread")),
1034 description:
1035 task.prompt.length > 0
1036 ? m(msg("The question is in the composer. Read it over, then send."))
1037 : m(
1038 msg(
1039 "The {term, select, mr {merge request} cr {change request} other {pull request}} is in the composer. Type your question, then send.",
1040 {
1041 term: changeRequestTermKind(terminology),
1042 },
1043 ),
1044 ),
1045 });
1046 };
1047
1048 const startHandoff = async (
1049 kind: string,
1050 task: { prompt: string; reviewComments?: ReadonlyArray<ReviewCommentContext> } | null,
1051 mode: "worktree" | "local" = "worktree",
1052 ) => {
1053 if (!handoffSummary || handoff !== null) return;
1054 if (attachTarget !== null && task !== null) {
1055 writeHandoffToComposer(attachTarget, task);
1056 toastManager.add({
1057 type: "success",
1058 title: m(msg("Added to the composer")),
1059 description: m(msg("The task is in the composer. Read it over, then send.")),
1060 });
1061 return;
1062 }
1063 if (checkoutRoot === null) return;
1064 if (
1065 !prepareThread.isAllowed ||
1066 !readEnvironmentScope(actingEnvironmentId, AuthSourceControlWriteScope)
1067 ) {
1068 return;
1069 }
1070 if (
1071 mode === "worktree" &&
1072 !readEnvironmentScope(actingEnvironmentId, AuthOrchestrationOperateScope)
1073 ) {
1074 return;
1075 }
1076 setHandoff(kind);
1077 const toastId = toastManager.add({
1078 type: "loading",
1079 title: m(
1080 msg(
1081 "Preparing the {term, select, mr {merge request} cr {change request} other {pull request}} checkout...",
1082 { term: changeRequestTermKind(terminology) },
1083 ),
1084 ),
1085 });
1086 const projectRef = scopeProjectRef(
1087 actingEnvironmentId,
1088 acting?.projectId ?? handoffSummary.projectId,
1089 );
1090 // Checkout setup requires the thread to exist first.
1091 const opened = await newThread(projectRef).then(
1092 (session) => session,
1093 () => null,
1094 );
1095 if (opened === null) {
1096 setHandoff(null);
1097 toastManager.update(toastId, {
1098 type: "error",
1099 title: m(msg("Could not open a thread for the checkout")),
1100 description: m(msg("Try again from the project, or open a thread first.")),
1101 });
1102 return;
1103 }
1104 const prepared = await prepareThread.run({
1105 reference: handoffSummary.url,
1106 mode,
1107 threadId: opened.threadId,
1108 });
1109 if (prepared._tag === "Failure") {
1110 setHandoff(null);
1111 toastManager.update(toastId, {
1112 type: "error",
1113 title: m(
1114 msg(
1115 "Could not prepare the {term, select, mr {merge request} cr {change request} other {pull request}} checkout",
1116 { term: changeRequestTermKind(terminology) },
1117 ),
1118 ),
1119 description: checkoutFailureDescription(
1120 isAtomCommandInterrupted(prepared) ? undefined : squashAtomCommandFailure(prepared),
1121 ),
1122 });
1123 return;
1124 }
1125 const pointed = await newThread(projectRef, {
1126 branch: prepared.value.branch,
1127 worktreePath: prepared.value.worktreePath,
1128 envMode: prepared.value.worktreePath === null ? "local" : "worktree",
1129 }).then(
1130 (session) => session,
1131 () => null,
1132 );
1133 if (pointed === null) {
1134 setHandoff(null);
1135 // Sending after failed rebinding would use the previous checkout.
1136 toastManager.update(toastId, {
1137 type: "error",
1138 title: m(msg("Checked out, but the thread stayed where it was")),
1139 description: m(
1140 msg(
1141 "The checkout is ready on `{branch}`. Point a thread at it from the branch picker, then ask again.",
1142 { branch: prepared.value.branch },
1143 ),
1144 ),
1145 });
1146 return;
1147 }
1148 // The draft carries the pull request until its first send makes it a thread, which links it.
1149 useComposerDraftStore.getState().setDraftThreadContext(pointed.draftId, {
1150 checkoutPullRequest: {
1151 url: prepared.value.pullRequest.url,
1152 branch: prepared.value.branch,
1153 },
1154 });
1155 setHandoff(null);
1156 if (task === null) {
1157 toastManager.update(
1158 toastId,
1159 prepared.value.isOnPullRequestHead
1160 ? {
1161 type: "success",
1162 title: mode === "local" ? m(msg("Checked out here")) : m(msg("Checked out")),
1163 description:
1164 mode === "local"
1165 ? m(
1166 msg(
1167 "This repository is on the {term, select, mr {merge request} cr {change request} other {pull request}}'s branch, with a thread open on it.",
1168 {
1169 term: changeRequestTermKind(terminology),
1170 },
1171 ),
1172 )
1173 : m(
1174 msg(
1175 "The {term, select, mr {merge request} cr {change request} other {pull request}} is in its own worktree, with a thread open on it.",
1176 {
1177 term: changeRequestTermKind(terminology),
1178 },
1179 ),
1180 ),
1181 }
1182 : offHeadPullRequestCheckoutToast(terminology),
1183 );
1184 return;
1185 }
1186 // The task goes on the checkout draft: if the user typed into `opened` while the
1187 // checkout ran, that is no longer the draft the user is looking at.
1188 await openThreadWithTask(projectRef, task, pointed);
1189 toastManager.update(
1190 toastId,
1191 prepared.value.isOnPullRequestHead
1192 ? {
1193 type: "success",
1194 title: m(msg("Checkout ready")),
1195 description: m(msg("The task is in the composer. Read it over, then send.")),
1196 }
1197 : offHeadPullRequestCheckoutToast(terminology),
1198 );
1199 };
1200
1201 const askAboutPullRequest = () => {
1202 if (!detail) return;
1203 void startAsk("ask", {
1204 ...buildAskAboutPullRequestHandoff({
1205 number: detail.number,
1206 title: detail.title,
1207 url: detail.url,
1208 headBranch: detail.headBranch,
1209 baseBranch: detail.baseBranch,
1210 state: detail.state,
1211 isDraft: detail.isDraft,
1212 }),
1213 });
1214 };
1215
1216 const explainPullRequest = () => {
1217 if (!detail) return;
1218 void startAsk("explain", {
1219 ...buildExplainPullRequestHandoff({
1220 number: detail.number,
1221 title: detail.title,
1222 url: detail.url,
1223 headBranch: detail.headBranch,
1224 baseBranch: detail.baseBranch,
1225 state: detail.state,
1226 isDraft: detail.isDraft,
1227 }),
1228 });
1229 };
1230
1231 const askAboutGuideStop = (stop: PullRequestReviewGuideStop, index: number, question: string) => {
1232 if (!detail) return;
1233 void startAsk(
1234 `guide-stop:${index}`,
1235 buildAskAboutGuideStopHandoff({
1236 number: detail.number,
1237 title: detail.title,
1238 url: detail.url,
1239 headBranch: detail.headBranch,
1240 baseBranch: detail.baseBranch,
1241 state: detail.state,
1242 isDraft: detail.isDraft,
1243 stop: {
1244 index,
1245 title: stop.title,
1246 summary: stop.summary,
1247 attention: stop.attention?.note ?? null,
1248 excerpts: stop.excerpts,
1249 },
1250 question,
1251 }),
1252 { keepGuide: true },
1253 );
1254 };
1255
1256 const addSelectionToAgent = (
1257 selection: PullRequestAgentSelectionInput,
1258 options?: { readonly keepGuide?: boolean },
1259 ) => {
1260 if (!detail) return;
1261 void startAsk(
1262 `selection:${selection.comment.id}`,
1263 buildAddSelectionToAgentHandoff({
1264 number: detail.number,
1265 title: detail.title,
1266 url: detail.url,
1267 headBranch: detail.headBranch,
1268 baseBranch: detail.baseBranch,
1269 state: detail.state,
1270 isDraft: detail.isDraft,
1271 comment: selection.comment,
1272 request: selection.request,
1273 }),
1274 options,
1275 );
1276 };
1277
1278 /**
1279 * Brings a remark into the composer beside this panel, with the pull request it belongs to,
1280 * and nothing else: what to ask about it is the reader's to write. A remark on a line travels
1281 * as its whole conversation, the way fixing one does.
1282 */
1283 const addCommentToChat = (subject: PullRequestChatSubject) => {
1284 if (!detail || attachTarget === null) return;
1285 const thread =
1286 subject.kind === "comment"
1287 ? detail.reviewThreads.find((candidate) =>
1288 candidate.comments.some((comment) => comment.id === subject.comment.id),
1289 )
1290 : undefined;
1291 const comment = buildPullRequestCommentContext(
1292 detail,
1293 thread === undefined ? subject : { kind: "thread", thread },
1294 );
1295 if (comment === null) return;
1296 const store = useComposerDraftStore.getState();
1297 const reference = buildPullRequestContext({
1298 number: detail.number,
1299 title: detail.title,
1300 url: detail.url,
1301 headBranch: detail.headBranch,
1302 baseBranch: detail.baseBranch,
1303 state: detail.state,
1304 isDraft: detail.isDraft,
1305 });
1306 const hasReference = (store.getComposerDraft(attachTarget)?.reviewComments ?? []).some(
1307 (existing) => existing.pullRequest?.url === detail.url,
1308 );
1309 // The active editor may be answering a provider question rather than editing this draft.
1310 if (!hasReference) store.addReviewComment(attachTarget, reference, { insertAtCaret: false });
1311 store.addReviewComment(attachTarget, comment, { insertAtCaret: false });
1312 toastManager.add({ type: "success", title: m(msg("Added to the composer")) });
1313 };
1314
1315 const startCheckout = (mode: "worktree" | "local") => {
1316 if (!handoffSummary) return;
1317 void startHandoff(`checkout:${mode}`, null, mode);
1318 };
1319
1320 const startFixFinding = (finding: PullRequestFinding) => {
1321 if (!detail) return;
1322 void startHandoff(
1323 pullRequestFindingKey(finding),
1324 buildFixFindingHandoff({
1325 number: detail.number,
1326 title: detail.title,
1327 url: detail.url,
1328 headBranch: detail.headBranch,
1329 baseBranch: detail.baseBranch,
1330 state: detail.state,
1331 isDraft: detail.isDraft,
1332 finding,
1333 inThisThread: attachTarget !== null,
1334 }),
1335 );
1336 };
1337
1338 const startFixFindings = () => {
1339 if (!detail) return;
1340 void startHandoff(
1341 "findings",
1342 buildFixFindingsHandoff({
1343 number: detail.number,
1344 title: detail.title,
1345 url: detail.url,
1346 headBranch: detail.headBranch,
1347 baseBranch: detail.baseBranch,
1348 state: detail.state,
1349 isDraft: detail.isDraft,
1350 reviewThreads: detail.reviewThreads,
1351 comments: detail.comments,
1352 checks: checksStale ? [] : detail.checks,
1353 commentsTruncated: detail.commentsTruncated,
1354 inThisThread: attachTarget !== null,
1355 }),
1356 );
1357 };
1358
1359 const startResolveConflicts = () => {
1360 if (!handoffSummary) return;
1361 void startHandoff("conflicts", {
1362 prompt: buildResolveConflictsPrompt({
1363 number: handoffSummary.number,
1364 url: handoffSummary.url,
1365 headBranch: handoffSummary.headBranch,
1366 baseBranch: handoffSummary.baseBranch,
1367 inThisThread: attachTarget !== null,
1368 }),
1369 });
1370 };
1371
1372 const selectMergeMethod = (method: PullRequestMergeMethod) => {
1373 setMergeMethod(method);
1374 setLastSelectedMergeMethod(method);
1375 };
1376 const selectActingEnvironment = (next: EnvironmentId) =>
1377 setActingScope({ pullRequestKey, environmentId: next });
1378 const allowedMergeMethods = allowedPullRequestMergeMethods(detail);
1379 const currentMergeMethod =
1380 mergeMethodSelection?.pullRequestKey === pullRequestKey ? mergeMethodSelection.method : null;
1381 const selectedMergeMethod = resolvePullRequestMergeMethod(
1382 allowedMergeMethods,
1383 currentMergeMethod,
1384 projectDefaultMergeMethod,
1385 lastSelectedMergeMethod,
1386 );
1387 const selectedMergeMethodLabel = resolve(PULL_REQUEST_MERGE_METHOD_LABELS[selectedMergeMethod]);
1388 const pendingAutoMergeLabel = resolve(AUTO_MERGE_LABELS[selectedMergeMethod]);
1389 const conflicting = isPullRequestConflicting(detail);
1390 const autoMergeArmed = detail?.state === "open" && detail.autoMergeEnabled === true;
1391 const armedMergeMethod = detail?.autoMergeMethod;
1392 const armedAutoMergeLabel = armedMergeMethod
1393 ? resolve(AUTO_MERGE_LABELS[armedMergeMethod])
1394 : gt("Auto-merge");
1395 const workflowApprovalsRequired =
1396 detail?.state === "open" ? (detail.workflowApprovalsRequired ?? 0) : 0;
1397 const freshness = detail === null ? null : resolveBaseFreshness(detail);
1398 const visibleTabs = resolveFilterOptions(
1399 TABS.filter((item) => isTabAvailable(item.value)),
1400 resolve,
1401 );
1402 const can = (action: PullRequestAction) =>
1403 detail?.capabilities.actions.includes(action) === true &&
1404 detail.viewerPermissions.actions.includes(action);
1405 const detailChecksState = detail ? pullRequestChecksState(detail.checks) : null;
1406 const latestChecksState =
1407 sharedSummary?.checksState === undefined ? detailChecksState : sharedSummary.checksState;
1408 // List rollups can omit workflows awaiting approval. Only refreshed detail can clear those.
1409 const checksState =
1410 latestChecksState !== "failing" &&
1411 detail?.checks.some((check) => check.status === "action-required")
1412 ? "pending"
1413 : latestChecksState;
1414 const checksStale = checksState !== detailChecksState;
1415 const primaryAction = detail
1416 ? resolvePullRequestPrimaryControl({
1417 state: detail.state,
1418 isDraft: detail.isDraft,
1419 mergeability: detail.mergeability,
1420 checksState,
1421 autoMergeEnabled: detail.autoMergeEnabled,
1422 hasMergeMethod: allowedMergeMethods.length > 0,
1423 canMerge: !stackOwnsMerge && can("merge"),
1424 canMarkReady: can("ready"),
1425 canEnableAutoMerge: !stackOwnsMerge && can("enable-auto-merge"),
1426 })
1427 : null;
1428 const showsDraftToggle =
1429 detail?.state === "open" &&
1430 can(detail.isDraft ? "ready" : "draft") &&
1431 !(detail.isDraft && primaryAction === "ready");
1432 const showsAutoMerge =
1433 canMergeSinglePullRequest &&
1434 detail?.state === "open" &&
1435 ((autoMergeArmed && can("disable-auto-merge")) ||
1436 (!autoMergeArmed &&
1437 primaryAction !== "enable-auto-merge" &&
1438 !detail.isDraft &&
1439 !conflicting &&
1440 can("enable-auto-merge") &&
1441 allowedMergeMethods.length > 0));
1442 const showsMergeNow =
1443 canMergeSinglePullRequest &&
1444 detail?.state === "open" &&
1445 (primaryAction === "enable-auto-merge" || primaryAction === "auto-merge-armed") &&
1446 can("merge") &&
1447 !detail.isDraft &&
1448 !conflicting &&
1449 allowedMergeMethods.length > 0;
1450 const showsMergeMethods =
1451 detail?.state === "open" &&
1452 can("merge") &&
1453 !detail.isDraft &&
1454 !conflicting &&
1455 allowedMergeMethods.length > 1;
1456 const statePresentation = detail
1457 ? resolvePullRequestState({ state: detail.state, isDraft: detail.isDraft }, resolve)
1458 : null;
1459 const showsDeleteBranch = detail !== null && canDeletePullRequestBranch(detail);
1460 const environmentConnected = environments.some(
1461 (environment) =>
1462 environment.environmentId === environmentId && environment.connection.phase === "connected",
1463 );
1464 const confirmDeleteBranch = async () => {
1465 if (detail === null) return;
1466 const confirmed = await readLocalApi()?.dialogs.confirm(
1467 [
1468 m(msg("Delete branch {branch}?", { branch: detail.headBranch })),
1469 m(
1470 msg(
1471 "This deletes {branch} from {repository}. Local branches and worktrees are not changed.",
1472 {
1473 branch: detail.headBranch,
1474 repository: detail.headRepositoryNameWithOwner ?? detail.repository,
1475 },
1476 ),
1477 ),
1478 ].join("\n"),
1479 { variant: "destructive" },
1480 );
1481 if (confirmed) void perform("delete-branch");
1482 };
1483 const showsApproveWorkflows =
1484 workflowApprovalsRequired > 0 && !checksStale && can("approve-workflows");
1485 const checksSummary = checksStale
1486 ? checksState === null
1487 ? gt("No checks reported")
1488 : pullRequestChecksStatePresentation(checksState, resolve).label
1489 : detail
1490 ? summarizePullRequestChecks(detail.checks, resolve)
1491 : null;
1492 const approvalCount =
1493 detail && !detail.commentsTruncated
1494 ? latestPullRequestReviewOutcomes(detail.comments, detail.commits).filter(
1495 (entry) => entry.outcome === "approved" && !entry.stale,
1496 ).length
1497 : 0;
1498
1499 const checkoutControl =
1500 context === "page" ? (
1501 <PullRequestCheckoutMenu
1502 term={changeRequestTermKind(terminology)}
1503 handoff={handoff}
1504 checkoutRoot={checkoutRoot}
1505 canPrepareWorktree={canPrepareWorktree}
1506 canCheckoutHere={prepareThread.isAllowed}
1507 onCheckout={startCheckout}
1508 pickableEnvironments={pickableEnvironments}
1509 actingEnvironmentId={actingEnvironmentId}
1510 onActingEnvironmentChange={selectActingEnvironment}
1511 />
1512 ) : null;
1513
1514 const resolveConflictsControl = (
1515 <PullRequestResolveConflictsButton
1516 handoff={handoff}
1517 unavailable={attachTarget === null && (checkoutRoot === null || !canPrepareWorktree)}
1518 onResolve={startResolveConflicts}
1519 />
1520 );
1521
1522 if (detailQuery.isPending && !detail) {
1523 return (
1524 <PullRequestDetailGhost
1525 seed={matchingListEntry}
1526 summary={sharedSummary}
1527 checkoutCommand={checkoutCommand}
1528 onCheckoutError={reportCheckoutCommandError}
1529 number={reference.number}
1530 tabs={visibleTabs}
1531 activeTab={tab}
1532 threadRef={threadRef}
1533 {...(onBack ? { onBack } : {})}
1534 {...(onClose ? { onClose } : {})}
1535 actions={
1536 handoffSummary ? (
1537 <TooltipProvider delay={150} closeDelay={150} timeout={400}>
1538 {handoffSummary.state === "open" && handoffSummary.mergeability === "conflicting"
1539 ? resolveConflictsControl
1540 : null}
1541 {checkoutControl}
1542 </TooltipProvider>
1543 ) : undefined
1544 }
1545 />
1546 );
1547 }
1548
1549 return (
1550 <div className="relative flex h-full min-h-0 w-full flex-col bg-background">
1551 {threadPickerOpen && detail ? (
1552 <PullRequestThreadLinks
1553 key={`${environmentId}:${detail.url}`}
1554 display="picker"
1555 environmentId={environmentId}
1556 reference={reference}
1557 url={detail.url}
1558 threadRef={null}
1559 onPickerOpenChange={setThreadPickerOpen}
1560 />
1561 ) : null}
1562 <div
1563 className={cn(
1564 "@container/pr-header grid min-w-0 shrink-0 grid-cols-[minmax(0,1fr)_auto] items-start gap-x-2",
1565 detail && "border-b border-border/60",
1566 !detail && !onClose && "hidden",
1567 )}
1568 >
1569 <PullRequestDetailCrumbs
1570 detail={detail}
1571 threadRef={threadRef}
1572 toneClassName={statePresentation?.toneClassName ?? null}
1573 condensed={condensed}
1574 repositoryUrl={repositoryUrl}
1575 openOnHostText={openOnHostText}
1576 onBack={onBack}
1577 />
1578 <div className="mr-4 flex h-7 shrink-0 select-none items-center justify-end gap-1">
1579 {detail ? (
1580 <TooltipProvider delay={150} closeDelay={150} timeout={400}>
1581 {context === "page" ? (
1582 <PullRequestThreadLinks
1583 display="count"
1584 environmentId={environmentId}
1585 reference={reference}
1586 url={detail.url}
1587 threadRef={null}
1588 />
1589 ) : null}
1590 {!nativeStack && supportsStackActions && nativeStackQuery.error ? (
1591 <Button variant="ghost" size="xs" onClick={nativeStackQuery.refresh}>
1592 <T>Retry stack lookup</T>
1593 </Button>
1594 ) : null}
1595 {nativeStack ? (
1596 <PullRequestStackMenu
1597 hostLabel={hostClient.label}
1598 terminology={terminology}
1599 stack={nativeStack}
1600 notice={nativeStackQuery.notice}
1601 onRetry={nativeStackQuery.error ? nativeStackQuery.refresh : undefined}
1602 reference={reference}
1603 environmentId={environmentId}
1604 onSelect={onSelectPullRequest}
1605 mergeMethod={selectedMergeMethod}
1606 stale={!nativeStackQuery.isFresh}
1607 canMerge={supportsStackActions && can("merge") && allowedMergeMethods.length > 0}
1608 canRebase={supportsStackActions && detail.viewerPermissions.stackRebase === true}
1609 onActed={() => {
1610 refreshDetail();
1611 onActed?.();
1612 }}
1613 />
1614 ) : null}
1615 <PullRequestPrimaryAction
1616 mergeBlockedReason={mergeBlockedReason}
1617 pullRequestKey={pullRequestKey}
1618 primaryAction={primaryAction}
1619 autoMergeArmed={autoMergeArmed}
1620 armedAutoMergeLabel={armedAutoMergeLabel}
1621 pendingAutoMergeLabel={pendingAutoMergeLabel}
1622 selectedMergeMethod={selectedMergeMethod}
1623 selectedMergeMethodLabel={selectedMergeMethodLabel}
1624 statePresentation={statePresentation}
1625 pendingAction={pendingAction}
1626 perform={perform}
1627 resolveConflicts={resolveConflictsControl}
1628 />
1629 {checkoutControl}
1630 <PullRequestActionsMenu
1631 environmentId={environmentId}
1632 reference={reference}
1633 pullRequestKey={pullRequestKey}
1634 detail={detail}
1635 terminology={terminology}
1636 threadRef={threadRef}
1637 linkThreadRef={
1638 threadRef ??
1639 (typeof composerDraftTarget === "object" ? composerDraftTarget : null)
1640 }
1641 onThreadPickerOpenChange={setThreadPickerOpen}
1642 refreshing={refreshing}
1643 refreshFromHost={refreshFromHost}
1644 handoff={handoff}
1645 attachesToComposer={attachTarget !== null}
1646 askAboutPullRequest={askAboutPullRequest}
1647 explainPullRequest={explainPullRequest}
1648 canFixFindings={canFixFindings}
1649 startFixFindings={startFixFindings}
1650 handoffLabels={handoffLabels}
1651 canWriteGuide={reviewGuidesEnabled && guideWriter.canWrite}
1652 guideRunning={guideWriter.running}
1653 guideWritten={guideWriter.data?.guide != null}
1654 writeGuide={writeGuide}
1655 pickableEnvironments={pickableEnvironments}
1656 actingEnvironmentId={actingEnvironmentId}
1657 onActingEnvironmentChange={selectActingEnvironment}
1658 can={can}
1659 autoMergeArmed={autoMergeArmed}
1660 showsDraftToggle={showsDraftToggle}
1661 showsMergeNow={showsMergeNow}
1662 showsAutoMerge={showsAutoMerge}
1663 showsMergeMethods={showsMergeMethods}
1664 allowedMergeMethods={allowedMergeMethods}
1665 selectedMergeMethod={selectedMergeMethod}
1666 onSelectMergeMethod={selectMergeMethod}
1667 showsDeleteBranch={showsDeleteBranch}
1668 environmentConnected={environmentConnected}
1669 canWriteSourceControl={canWriteSourceControl}
1670 onMaintainerEditsSaved={refreshDetail}
1671 confirmDeleteBranch={confirmDeleteBranch}
1672 pendingAction={pendingAction}
1673 perform={perform}
1674 openOnHostText={openOnHostText}
1675 copyReference={copyReference}
1676 />
1677 </TooltipProvider>
1678 ) : null}
1679 {onClose ? (
1680 <Button
1681 size="icon-xs"
1682 variant="ghost"
1683 aria-label={gt(
1684 "Collapse {term, select, mr {merge request} cr {change request} other {pull request}} panel",
1685 { term: changeRequestTermKind(terminology) },
1686 )}
1687 onClick={onClose}
1688 >
1689 <PanelRightIcon className="size-3.5" />
1690 </Button>
1691 ) : null}
1692 </div>
1693
1694 <div
1695 className={cn(
1696 "col-span-2 grid",
1697 condensed
1698 ? "grid-rows-[1fr]"
1699 : "grid-rows-[0fr] transition-[grid-template-rows] duration-200 ease-out motion-reduce:transition-none",
1700 )}
1701 >
1702 <div
1703 ref={condensedRowRef}
1704 className={cn(
1705 "min-h-0 overflow-hidden transition-[opacity,transform] duration-150 ease-out motion-reduce:transform-none motion-reduce:transition-none",
1706 condensed
1707 ? "translate-y-0 opacity-100 delay-50"
1708 : "translate-y-1 opacity-0 duration-100",
1709 )}
1710 inert={!condensed}
1711 data-workspace-scroll-swap
1712 >
1713 {detail ? (
1714 <div className="col-span-2 min-w-0 px-4 pb-2 pt-1">
1715 <div className="flex min-w-0 items-center gap-2 text-xs text-muted-foreground">
1716 <span className="flex min-w-0 shrink items-center gap-1.5 overflow-hidden text-xs text-muted-foreground">
1717 <PullRequestActorLabel
1718 actor={detail.author}
1719 profileUrl={authorProfileUrl}
1720 variant="avatar"
1721 className="shrink-0"
1722 />
1723 <span className="shrink-0">
1724 <RelativeTime timestamp={detail.updatedAt} />
1725 </span>
1726 </span>
1727 <span aria-hidden className="h-3 w-px shrink-0 bg-border/70" />
1728 <span className="flex min-w-0 flex-1 items-center gap-1.5 font-mono text-2xs text-muted-foreground/65">
1729 <PullRequestBaseBranch
1730 baseBranch={detail.baseBranch}
1731 freshness={freshness}
1732 stacked={isStackedPullRequest}
1733 pending={actionPending}
1734 onUpdate={(method) => void perform("update-branch", undefined, method)}
1735 iconClassName="size-3"
1736 />
1737 <ArrowLeftIcon
1738 aria-label={gt("receives changes from", {
1739 $context:
1740 "screen reader label for an arrow between the base branch, read before it, and the head branch, read after it",
1741 })}
1742 className="size-3 shrink-0 opacity-60"
1743 />
1744 <Tooltip>
1745 <TooltipTrigger
1746 render={
1747 <code className="flex min-w-0 flex-1">
1748 <MiddleTruncate value={detail.headBranch} showTitle={false} />
1749 </code>
1750 }
1751 />
1752 <TooltipPopup side="top">{detail.headBranch}</TooltipPopup>
1753 </Tooltip>
1754 </span>
1755 <span className="ml-auto inline-flex shrink-0 items-baseline justify-end gap-2 text-2xs">
1756 <span
1757 className="inline-flex items-baseline gap-1 tabular-nums"
1758 aria-label={gt(
1759 "{count, plural, one {{formatted} changed file} other {{formatted} changed files}}",
1760 {
1761 count: detail.changedFiles,
1762 formatted: detail.changedFiles.toLocaleString(),
1763 },
1764 )}
1765 >
1766 <FileDiffIcon aria-hidden className="size-3 self-center" />
1767 {detail.changedFiles.toLocaleString()}
1768 </span>
1769 <PullRequestChangeBreakdownStat
1770 environmentId={environmentId}
1771 reference={reference}
1772 additions={detail.additions}
1773 deletions={detail.deletions}
1774 className="shrink-0 font-mono text-2xs"
1775 eager
1776 />
1777 </span>
1778 </div>
1779 </div>
1780 ) : null}
1781 </div>
1782 </div>
1783
1784 <div
1785 className={cn(
1786 "col-span-2 grid",
1787 condensed
1788 ? "grid-rows-[0fr]"
1789 : "grid-rows-[1fr] transition-[grid-template-rows] duration-200 ease-out motion-reduce:transition-none",
1790 )}
1791 >
1792 <div
1793 ref={foldRef}
1794 className={cn(
1795 "min-h-0 overflow-hidden transition-[opacity,transform] duration-150 ease-out motion-reduce:transform-none motion-reduce:transition-none",
1796 condensed
1797 ? "-translate-y-1 opacity-0 duration-100"
1798 : "translate-y-0 opacity-100 delay-50",
1799 )}
1800 inert={condensed}
1801 data-workspace-scroll-swap
1802 >
1803 {detail ? (
1804 <PullRequestDetailHeaderBody
1805 title={
1806 <PullRequestTitleEditor
1807 environmentId={environmentId}
1808 reference={reference}
1809 pullRequestKey={pullRequestKey}
1810 detail={detail}
1811 canWriteSourceControl={canWriteSourceControl}
1812 />
1813 }
1814 author={
1815 <PullRequestActorLabel actor={detail.author} profileUrl={authorProfileUrl} />
1816 }
1817 updated={
1818 <span>
1819 <T context="followed by a relative time such as 5m ago or just now">
1820 updated{" "}
1821 <Var>
1822 <RelativeTime timestamp={detail.updatedAt} />
1823 </Var>
1824 </T>
1825 </span>
1826 }
1827 checkout={
1828 checkoutCommand ? (
1829 <PullRequestCopyableCode
1830 key={checkoutCommand}
1831 value={checkoutCommand}
1832 target={{
1833 target: `${terminology.singular} checkout command`,
1834 unavailableMessage: msg(
1835 "Clipboard API is unavailable while copying {term, select, mr {merge request} cr {change request} other {pull request}} checkout command.",
1836 { term: changeRequestTermKind(terminology) },
1837 ),
1838 failureMessage: msg(
1839 "Failed to copy {term, select, mr {merge request} cr {change request} other {pull request}} checkout command to the clipboard.",
1840 { term: changeRequestTermKind(terminology) },
1841 ),
1842 }}
1843 copyLabel={gt("Copy checkout command")}
1844 copiedLabel={gt("Checkout command copied")}
1845 className="ml-auto font-mono"
1846 tooltipSide="bottom"
1847 onError={reportCheckoutCommandError}
1848 />
1849 ) : null
1850 }
1851 base={
1852 <PullRequestBaseBranch
1853 baseBranch={detail.baseBranch}
1854 freshness={freshness}
1855 stacked={isStackedPullRequest}
1856 pending={actionPending}
1857 onUpdate={(method) => void perform("update-branch", undefined, method)}
1858 />
1859 }
1860 head={
1861 <PullRequestCopyableCode
1862 key={detail.headBranch}
1863 value={detail.headBranch}
1864 target={{
1865 target: "branch name",
1866 unavailableMessage: msg(
1867 "Clipboard API is unavailable while copying branch name.",
1868 ),
1869 failureMessage: msg("Failed to copy branch name to the clipboard."),
1870 }}
1871 copyLabel={gt(
1872 "Copy {term, select, mr {merge request} cr {change request} other {pull request}} branch",
1873 { term: changeRequestTermKind(terminology) },
1874 )}
1875 copiedLabel={gt("Branch name copied")}
1876 />
1877 }
1878 files={gt("{count, plural, one {{formatted} file} other {{formatted} files}}", {
1879 count: detail.changedFiles,
1880 formatted: detail.changedFiles.toLocaleString(),
1881 })}
1882 diffStat={
1883 <PullRequestChangeBreakdownStat
1884 environmentId={environmentId}
1885 reference={reference}
1886 additions={detail.additions}
1887 deletions={detail.deletions}
1888 className="shrink-0 font-mono text-xs"
1889 eager
1890 />
1891 }
1892 />
1893 ) : null}
1894 </div>
1895 </div>
1896
1897 {detail ? (
1898 <PullRequestDetailTabBar
1899 tabs={visibleTabs}
1900 value={tab}
1901 onValueChange={selectTab}
1902 onTabIntent={(item) => {
1903 if (item !== "code") return;
1904 void loadCodeTab();
1905 setCodeIntentKey(pullRequestKey);
1906 }}
1907 >
1908 {tab === "summary" ? (
1909 showsApproveWorkflows ? (
1910 <PullRequestApproveWorkflowsButton
1911 pullRequestKey={pullRequestKey}
1912 pendingAction={pendingAction}
1913 perform={perform}
1914 />
1915 ) : (
1916 <PullRequestChecksStatusLine
1917 className="text-muted-foreground"
1918 aria-label={
1919 checksSummary
1920 ? gt("Checks: {summary}", { summary: checksSummary })
1921 : gt("Checks", { $context: "CI checks section" })
1922 }
1923 icon={
1924 checksState !== null ? (
1925 <PullRequestChecksPopover
1926 checks={detail.checks}
1927 stale={checksStale}
1928 checksState={checksState}
1929 threadRef={threadRef}
1930 />
1931 ) : (
1932 <CircleDotIcon aria-hidden className="size-3.5" />
1933 )
1934 }
1935 label={checksSummary}
1936 />
1937 )
1938 ) : tab === "timeline" ? (
1939 <div className="ml-auto flex shrink-0 items-center gap-2 text-xs text-muted-foreground">
1940 <PullRequestMetaLine
1941 className={cn(
1942 "whitespace-nowrap text-2xs transition-opacity",
1943 (activityPending || activityError) && "opacity-35",
1944 )}
1945 >
1946 <span
1947 className="inline-flex items-center gap-1"
1948 aria-label={
1949 activityError
1950 ? gt("Comments unavailable")
1951 : gt(
1952 "{count, plural, one {{formatted} comment} other {{formatted} comments}}",
1953 {
1954 count: detail.commentCount,
1955 formatted: detail.commentCount.toLocaleString(),
1956 },
1957 )
1958 }
1959 >
1960 <MessageSquareIcon aria-hidden className="size-3" />
1961 {activityError
1962 ? "-"
1963 : activityPending
1964 ? "…"
1965 : detail.commentCount.toLocaleString()}
1966 </span>
1967 <span
1968 className="inline-flex items-center gap-1"
1969 aria-label={
1970 activityError
1971 ? gt("Commits unavailable")
1972 : gt(
1973 "{count, plural, one {{formatted} commit} other {{formatted} commits}}",
1974 {
1975 count: detail.commits.length,
1976 formatted: detail.commits.length.toLocaleString(),
1977 },
1978 )
1979 }
1980 >
1981 <GitCommitHorizontalIcon aria-hidden className="size-3" />
1982 {activityError
1983 ? "-"
1984 : activityPending
1985 ? "…"
1986 : detail.commits.length.toLocaleString()}
1987 </span>
1988 {approvalCount > 0 ? (
1989 <span
1990 className={cn(
1991 "inline-flex items-center gap-1",
1992 pullRequestReviewOutcomeToneClassName("approved"),
1993 )}
1994 >
1995 <PullRequestReviewOutcomeIcon outcome="approved" className="size-3" />
1996 <span aria-hidden>{approvalCount.toLocaleString()}</span>
1997 <span className="sr-only">
1998 {gt(
1999 "{count, plural, one {{formatted} approval} other {{formatted} approvals}}",
2000 { count: approvalCount, formatted: approvalCount.toLocaleString() },
2001 )}
2002 </span>
2003 </span>
2004 ) : null}
2005 </PullRequestMetaLine>
2006 <Button
2007 size="xs"
2008 variant="ghost-muted"
2009 aria-label={
2010 timelineOrder === "newest"
2011 ? gt("Show oldest activity first")
2012 : gt("Show newest activity first")
2013 }
2014 onClick={() =>
2015 setTimelineOrder((value) => (value === "newest" ? "oldest" : "newest"))
2016 }
2017 >
2018 <ArrowDownUpIcon aria-hidden className="size-3" />
2019 {timelineOrder === "newest" ? gt("Newest first") : gt("Oldest first")}
2020 </Button>
2021 </div>
2022 ) : null}
2023 </PullRequestDetailTabBar>
2024 ) : null}
2025 </div>
2026
2027 <SourceControlAppAccessNotice
2028 environmentId={environmentId}
2029 provider={detail?.provider ?? repositoryIdentity?.provider}
2030 host={reference.host}
2031 repository={reference.repository}
2032 className="border-b border-border/60"
2033 />
2034 <div
2035 className="relative flex min-h-0 flex-1 flex-col overflow-hidden"
2036 onScrollCapture={(event) => {
2037 const scroller = scrollerByTab.current[tab];
2038 if (event.target !== scroller || scroller === null || scroller === undefined) return;
2039 const top = scroller.scrollTop;
2040 const previous = condensedByTab[tab] ?? false;
2041 const foldHeight = foldRef.current?.scrollHeight ?? 0;
2042 let next = previous;
2043 if (previous) {
2044 if (top < 4 && foldHeight > 0) next = false;
2045 } else if (foldHeight > 0 && top > foldHeight + 32) {
2046 const chromeDelta = foldHeight - (condensedRowRef.current?.scrollHeight ?? 0);
2047 compensationRef.current = { tab, scroller, target: top - chromeDelta };
2048 next = true;
2049 }
2050 if (next !== previous) setCondensedByTab({ ...condensedByTab, [tab]: next });
2051 }}
2052 >
2053 {detailQuery.error && !detail ? (
2054 <PullRequestsUnavailableState
2055 {...(isPullRequestNotFound(detailQuery.failure)
2056 ? {
2057 title: gt(
2058 "{term, select, mr {Merge request} cr {Change request} other {Pull request}} #{number} not found",
2059 {
2060 term: changeRequestTermKind(terminology),
2061 number: reference.number,
2062 },
2063 ),
2064 error: gt(
2065 "It may be an issue rather than a {term, select, mr {merge request} cr {change request} other {pull request}}, or this account can't see it.",
2066 { term: changeRequestTermKind(terminology) },
2067 ),
2068 }
2069 : { error: detailQuery.error })}
2070 refreshing={detailQuery.isPending}
2071 onRetry={refreshDetail}
2072 {...(unavailableHostUrl
2073 ? {
2074 host: {
2075 url: unavailableHostUrl,
2076 openLabel: openOnHostLabel(
2077 sourceControlClients.get(repositoryIdentity?.provider),
2078 resolve,
2079 ),
2080 },
2081 }
2082 : {})}
2083 />
2084 ) : detail ? (
2085 <PullRequestMarkdownContext value={markdownContext}>
2086 {mountedTabs.has("summary") ? (
2087 <div className={cn("absolute inset-0", tab !== "summary" && "invisible")}>
2088 <PullRequestSummaryTab
2089 scrollerRef={scrollerRefs.summary}
2090 revealUrl={tab === "summary" ? revealUrl : undefined}
2091 onRevealSettled={settleReveal}
2092 environmentId={environmentId}
2093 threadRef={threadRef}
2094 reference={reference}
2095 detail={detail}
2096 activityPending={activityPending}
2097 checksStale={checksStale}
2098 activityError={activityError}
2099 pendingFinding={handoff}
2100 fixFindingLabel={handoffLabels.fixFinding}
2101 fixCheckLabel={handoffLabels.fixCheck}
2102 {...(canFixFindings ? { onFixFinding: startFixFinding } : {})}
2103 {...(attachTarget === null ? {} : { onAddToChat: addCommentToChat })}
2104 onRefresh={refreshDetail}
2105 onRefreshChecks={refreshFromHost}
2106 />
2107 </div>
2108 ) : null}
2109 {mountedTabs.has("guide") ? (
2110 <div
2111 className={cn("absolute inset-0", tab !== "guide" && "invisible")}
2112 // Read by the guide run notifier, which stays quiet for a guide on screen.
2113 data-guide-shown={tab === "guide" ? guideKey : undefined}
2114 >
2115 <PullRequestGuideTab
2116 environmentId={environmentId}
2117 reference={reference}
2118 active={tab === "guide"}
2119 title={detail.title}
2120 workspaceRoot={detail.workspaceRoot}
2121 canComment={
2122 detail.capabilities.review.inlineComment && detail.viewerPermissions.comment
2123 }
2124 rangeComments={detail.capabilities.review.rangeComment === true}
2125 completionScope={pullRequestCompletionScope(detail, environmentId, reference)}
2126 onAskAboutLines={(comment, request) =>
2127 addSelectionToAgent({ comment, request }, { keepGuide: true })
2128 }
2129 onAskAboutStop={askAboutGuideStop}
2130 onFinishReview={
2131 detail.capabilities.review.verdicts.some((verdict) =>
2132 detail.viewerPermissions.verdicts.includes(verdict),
2133 )
2134 ? () => setOpenReviewRequest((count) => count + 1)
2135 : null
2136 }
2137 onOpenFile={openFileInCode}
2138 onTourShown={onGuideShown}
2139 />
2140 </div>
2141 ) : null}
2142 {mountedTabs.has("timeline") ? (
2143 <div className={cn("absolute inset-0", tab !== "timeline" && "invisible")}>
2144 {activityPending ? (
2145 <PullRequestTimelineGhost />
2146 ) : activityError ? (
2147 <PullRequestActivityUnavailableState
2148 error={activityError}
2149 term={changeRequestTermKind(terminology)}
2150 onRetry={activityQuery.refresh}
2151 />
2152 ) : (
2153 <PullRequestTimelineTab
2154 scrollerRef={scrollerRefs.timeline}
2155 revealUrl={tab === "timeline" ? revealUrl : undefined}
2156 onRevealSettled={settleReveal}
2157 detail={detail}
2158 environmentId={environmentId}
2159 threadRef={threadRef}
2160 reference={reference}
2161 order={timelineOrder}
2162 onOpenCommit={openCommit}
2163 {...(attachTarget === null ? {} : { onAddToChat: addCommentToChat })}
2164 onRefresh={refreshDetail}
2165 />
2166 )}
2167 </div>
2168 ) : null}
2169 {mountedTabs.has("code") ? (
2170 <div className={cn("absolute inset-0", tab !== "code" && "invisible")}>
2171 <Suspense
2172 fallback={
2173 <DiffPanelLoadingState
2174 label={gt(
2175 "Loading {term, select, mr {merge request} cr {change request} other {pull request}} diff...",
2176 { term: changeRequestTermKind(terminology) },
2177 )}
2178 />
2179 }
2180 >
2181 <PullRequestCodeTab
2182 scrollerRef={scrollerRefs.code}
2183 onAddToAgentSelection={addSelectionToAgent}
2184 environmentId={environmentId}
2185 reference={reference}
2186 detail={detail}
2187 selectedCommitOid={selectedCodeCommitOid}
2188 onSelectedCommitChange={selectCodeCommit}
2189 pendingFinding={handoff}
2190 fixFindingLabel={handoffLabels.fixFinding}
2191 {...(canFixFindings ? { onFixFinding: startFixFinding } : {})}
2192 {...(attachTarget === null ? {} : { onAddToChat: addCommentToChat })}
2193 onRefresh={refreshDetail}
2194 refreshToken={refreshToken}
2195 backgroundRefreshToken={turnRefresh ?? 0}
2196 revealRequest={codeRevealRequest}
2197 revealUrl={tab === "code" ? revealUrl : undefined}
2198 onRevealSettled={settleReveal}
2199 />
2200 </Suspense>
2201 </div>
2202 ) : null}
2203 </PullRequestMarkdownContext>
2204 ) : null}
2205 </div>
2206
2207 {detail ? (
2208 <div className="absolute right-4 bottom-3 z-20">
2209 <PullRequestComposer
2210 key={JSON.stringify([
2211 environmentId,
2212 reference.projectId,
2213 reference.host,
2214 reference.repository,
2215 reference.number,
2216 ])}
2217 environmentId={environmentId}
2218 reference={reference}
2219 detail={detail}
2220 actionPending={actionPending}
2221 onCommentAction={performCommentAction}
2222 onCommented={refreshDetail}
2223 onReviewSubmitted={refreshDetail}
2224 openReviewRequest={openReviewRequest}
2225 />
2226 </div>
2227 ) : null}
2228 </div>
2229 );
2230 }