Open History to see the last commit
1import type { EnvironmentId, PullRequestRef, PullRequestReviewGuideStop } from "@t3tools/contracts";
2import { msg, T, useGT, useMessages } from "gt-react";
3import { ScrollTextIcon, TriangleAlertIcon } from "lucide-react";
4import { useEffect, useEffectEvent } from "react";
5
6import type { ReviewCommentContext } from "~/reviewCommentContext";
7
8import { Alert, AlertAction, AlertDescription } from "../ui/alert";
9import { Button } from "../ui/button";
10import { Spinner } from "../ui/spinner";
11import type { ExcerptCommenting } from "./guide/GuideExcerpt";
12import { GuideProseContext } from "./guide/GuideProse";
13import { GuideTour } from "./guide/GuideTour";
14import { useReviewGuideWriter } from "./guide/useReviewGuideWriter";
15import {
16 nextPendingReviewCommentId,
17 pullRequestReviewKey,
18 usePendingReviewComments,
19 usePullRequestReviewStore,
20} from "./pullRequestReviewStore";
21import type { PullRequestCompletionScope } from "./PullRequestMarkdownTextarea";
22
23export function PullRequestGuideTab({
24 environmentId,
25 reference,
26 title,
27 workspaceRoot,
28 active,
29 canComment,
30 rangeComments,
31 completionScope,
32 onAskAboutLines,
33 onAskAboutStop,
34 onFinishReview,
35 onOpenFile,
36 onTourShown,
37}: {
38 environmentId: EnvironmentId;
39 reference: PullRequestRef;
40 title: string | null;
41 workspaceRoot: string;
42 active: boolean;
43 canComment: boolean;
44 rangeComments: boolean;
45 completionScope: PullRequestCompletionScope | null;
46 onAskAboutLines: ((comment: ReviewCommentContext, request: string) => void) | null;
47 onAskAboutStop:
48 | ((stop: PullRequestReviewGuideStop, index: number, question: string) => void)
49 | null;
50 onFinishReview: (() => void) | null;
51 onOpenFile: (path: string) => void;
52 onTourShown?: (() => void) | undefined;
53}) {
54 const gt = useGT();
55 const resolve = useMessages();
56 const { query, data, running, canWrite, write } = useReviewGuideWriter({
57 environmentId,
58 reference,
59 title,
60 });
61 const reviewKey = pullRequestReviewKey(reference);
62 const pending = usePendingReviewComments(reference);
63 const addComment = usePullRequestReviewStore((store) => store.addComment);
64 const removeComment = usePullRequestReviewStore((store) => store.removeComment);
65 const commenting: ExcerptCommenting | null =
66 !canComment && onAskAboutLines === null
67 ? null
68 : {
69 canComment,
70 rangeComments,
71 completionScope,
72 pending,
73 onComment: ({ path, oldPath, position, startPosition, body }) =>
74 addComment(reviewKey, {
75 id: nextPendingReviewCommentId(),
76 path,
77 ...(oldPath === null ? {} : { oldPath }),
78 ...(startPosition === undefined ? {} : { startPosition }),
79 position,
80 body,
81 }),
82 onRemove: (commentId) => removeComment(reviewKey, commentId),
83 onAskAgent: onAskAboutLines,
84 };
85 const guide = data?.guide ?? null;
86 const tourShown = active && guide !== null;
87 const reportTourShown = useEffectEvent(() => onTourShown?.());
88 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- tells the parent once the loaded guide tour is on screen, which data arrival can cause
89 useEffect(() => {
90 if (tourShown) reportTourShown();
91 }, [tourShown]);
92 const runState = data?.run ?? null;
93 const currentHeadSha = data?.currentHeadSha ?? null;
94 const stale = guide !== null && currentHeadSha !== null && currentHeadSha !== guide.headSha;
95 const failure =
96 runState?._tag === "Failed" && runState.headSha === currentHeadSha ? runState.detail : null;
97 const writeButton = (label: string, size: "sm" | "xs") =>
98 canWrite ? (
99 <Button size={size} variant="outline" disabled={running} onClick={() => void write()}>
100 {running ? <Spinner /> : <ScrollTextIcon aria-hidden className="size-3.5" />}
101 {running ? gt("Reading the change...") : label}
102 </Button>
103 ) : null;
104
105 if (guide === null) {
106 if (query.isPending && data === null) {
107 return (
108 <div
109 tabIndex={-1}
110 data-workspace-focus-default
111 className="flex min-h-48 items-center justify-center outline-none"
112 >
113 <Spinner />
114 </div>
115 );
116 }
117 return (
118 <div
119 tabIndex={-1}
120 data-workspace-focus-default
121 className="scrollbar-gutter-both flex h-full flex-col items-center justify-center-safe gap-2 overflow-y-auto px-4 py-10 text-center outline-none"
122 >
123 <p className="text-sm font-medium text-foreground">
124 {running
125 ? gt("Writing a review guide")
126 : failure === null
127 ? gt("No review guide yet")
128 : gt("Could not write a review guide")}
129 </p>
130 <p className="max-w-md text-xs text-muted-foreground">
131 {running
132 ? gt(
133 "An agent is reading the change. A large one takes a few minutes. You can leave; you will be told when it is ready.",
134 )
135 : failure === null
136 ? (query.error ??
137 gt(
138 "A guide is a tour of the change: stops through the code in reading order, with the calls only a maintainer can make.",
139 ))
140 : resolve(FAILURE_HINT)}
141 </p>
142 {writeButton(failure === null ? gt("Write guide") : gt("Try again"), "sm")}
143 {failure === null || running ? null : <FailureDetails detail={failure} />}
144 </div>
145 );
146 }
147
148 const banner =
149 stale || failure !== null || running ? (
150 <Alert variant={running ? "info" : "warning"}>
151 {running ? <Spinner /> : <TriangleAlertIcon />}
152 <AlertDescription>
153 {running ? (
154 gt("Rewriting this guide. You will be told when the new one is ready.")
155 ) : failure === null ? (
156 gt("Written before the latest push.")
157 ) : (
158 <>
159 {gt(
160 "Could not rewrite this guide. Check the review guide model in Settings → Source control.",
161 )}
162 <FailureDetails detail={failure} />
163 </>
164 )}
165 </AlertDescription>
166 {!running && canWrite ? (
167 <AlertAction>{writeButton(gt("Rewrite"), "xs")}</AlertAction>
168 ) : null}
169 </Alert>
170 ) : null;
171
172 return (
173 <GuideProseContext value={{ environmentId, cwd: workspaceRoot }}>
174 <GuideTour
175 environmentId={environmentId}
176 reference={reference}
177 guide={guide}
178 banner={banner}
179 active={active}
180 commenting={commenting}
181 onAsk={
182 onAskAboutStop === null
183 ? null
184 : (index, question) => {
185 const stop = guide.stops[index];
186 if (stop !== undefined) onAskAboutStop(stop, index, question);
187 }
188 }
189 onFinish={onFinishReview}
190 onOpenFile={onOpenFile}
191 />
192 </GuideProseContext>
193 );
194}
195
196const FAILURE_HINT = msg("Check the review guide model in Settings → Source control & issues.");
197
198function FailureDetails({ detail }: { detail: string }) {
199 return (
200 <details className="w-full max-w-lg text-xs text-muted-foreground">
201 <summary className="cursor-pointer rounded-sm -outline-offset-2 hover:text-foreground focus-visible:outline-2 focus-visible:outline-ring">
202 <T>Technical details</T>
203 </summary>
204 <pre className="scrollbar-gutter-both mt-2 max-h-40 overflow-auto whitespace-pre-wrap break-words rounded-lg border border-border bg-muted/40 p-3 text-left font-mono text-xs">
205 {detail}
206 </pre>
207 </details>
208 );
209}