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

ThreadPullRequestsPanel.tsx

372 lines14.2 KB

1import type { ScopedThreadRef, ThreadPullRequestLink } from "@t3tools/contracts";
2import {
3 resolveThreadPullRequestChains,
4 visibleThreadPullRequests,
5} from "@t3tools/shared/threadPullRequests";
6import {
7 ArrowUpRightIcon,
8 EyeIcon,
9 EyeOffIcon,
10 LinkIcon,
11 MoreHorizontalIcon,
12 PlusIcon,
13} from "lucide-react";
14import { useCallback, useMemo } from "react";
15​
16import { writeTextToClipboard } from "~/hooks/useCopyToClipboard";
17import { useOpenPrLink } from "~/lib/openPullRequestLink";
18import { cn } from "~/lib/utils";
19import { useServerConfigs, useThreadShell } from "~/state/entities";
20import { PullRequestsUnavailableState } from "./PullRequestsUnavailableState";
21import { threadEnvironment } from "~/state/threads";
22import { useAtomCommand } from "~/state/use-atom-command";
23import { formatRelativeTimeLabel } from "~/timestampFormat";
24import { Button } from "../ui/button";
25import { Menu, MenuItem, MenuPopup, MenuTrigger } from "../ui/menu";
26import { MiddleTruncate } from "../ui/middle-truncate";
27import { ScrollArea } from "../ui/scroll-area";
28import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";
29import { openLinkPullRequestDialog } from "./LinkPullRequestDialog";
30import { pullRequestListLines, type PullRequestListLine } from "./pullRequestListLines";
31import {
32 PULL_REQUEST_ROW_CLASS,
33 PULL_REQUEST_ROW_NUMBER_CLASS,
34 PullRequestRowAuthor,
35 PullRequestRowBranches,
36 PullRequestRowGlyph,
37 PullRequestRowLines,
38} from "./PullRequestListRow";
39import {
40 PullRequestDiffStat,
41 PullRequestReviewDecisionGlyph,
42 pullRequestChecksStatePresentation,
43} from "./pullRequestPresentation";
44import { PullRequestGlyph } from "./pullRequestIcons";
45​
46const SOURCE_LABELS: Record<ThreadPullRequestLink["source"], string> = {
47 manual: "Linked by you",
48 created: "Created from this thread",
49 agent: "Linked by the agent",
50 stack: "Found in the stack",
51 "stack-dismissed": "Dismissed",
52};
53​
54function ChecksGlyph({
55 state,
56}: {
57 state: NonNullable<ThreadPullRequestLink["snapshot"]>["checksState"] & string;
58}) {
59 const presentation = pullRequestChecksStatePresentation(state);
60 return (
61 <Tooltip>
62 <TooltipTrigger render={<span className="inline-flex shrink-0" />}>
63 <presentation.Icon
64 role="img"
65 aria-label={presentation.label}
66 className={cn("size-3.5", presentation.toneClassName)}
67 />
68 </TooltipTrigger>
69 <TooltipPopup>{presentation.label}</TooltipPopup>
70 </Tooltip>
71 );
73​
74function LinkRow({
75 line,
76 threadRef,
77 onUnlink,
78 onSetWatching,
79}: {
80 line: PullRequestListLine;
81 threadRef: ScopedThreadRef;
82 onUnlink: (link: ThreadPullRequestLink) => void;
83 /** Null when the environment cannot watch pull requests. */
84 onSetWatching: ((link: ThreadPullRequestLink, watching: boolean) => void) | null;
85}) {
86 const openPrLink = useOpenPrLink(threadRef);
87 const { link, depth, stack } = line;
88 const snapshot = link.snapshot;
89 const open = snapshot === null || snapshot.state === "open";
90 const watching = link.watch !== undefined;
91 return (
92 <div
93 className={cn(PULL_REQUEST_ROW_CLASS, "relative hover:bg-accent/60")}
94 // Each layer steps in under the one it targets. The step is capped: beyond a few layers
95 // the indent only says "still in the stack", which the connector line already does, and
96 // a sixteen-layer stack would otherwise stair-step off the right edge.
97 style={{ paddingLeft: `${0.5 + Math.min(depth, 3) * 1.25}rem` }}
98 >
99 {depth > 0 ? <span aria-hidden className="-ml-2 h-6 w-px shrink-0 bg-border/70" /> : null}
100 {snapshot === null ? (
101 <PullRequestGlyph.pullRequest
102 aria-label="Waiting for host state"
103 className="size-4 shrink-0 text-muted-foreground"
104 />
105 ) : (
106 <PullRequestRowGlyph
107 state={snapshot.state}
108 isDraft={snapshot.isDraft}
109 mergeability={snapshot.mergeability}
110 baseBranch={snapshot.baseBranch}
111 />
112 )}
113 <a
114 href={link.url}
115 onClick={(event) => openPrLink(event, link.url, threadRef)}
116 className="flex min-w-0 flex-1"
117 >
118 <PullRequestRowLines
119 number={
120 <Tooltip>
121 <TooltipTrigger render={<span className={PULL_REQUEST_ROW_NUMBER_CLASS} />}>
122 #{link.number}
123 </TooltipTrigger>
124 <TooltipPopup>
125 {SOURCE_LABELS[link.source]} · {formatRelativeTimeLabel(link.linkedAt)}
126 </TooltipPopup>
127 </Tooltip>
128 }
129 title={snapshot?.title ?? link.repository}
130 signals={
131 open ? (
132 <>
133 {watching ? (
134 <Tooltip>
135 <TooltipTrigger render={<span className="inline-flex shrink-0" />}>
136 <EyeIcon role="img" aria-label="Watching" className="size-3.5" />
137 </TooltipTrigger>
138 <TooltipPopup>
139 Watching: the agent wakes when checks finish, someone comments, or the branch
140 conflicts
141 </TooltipPopup>
142 </Tooltip>
143 ) : null}
144 {snapshot?.checksState ? <ChecksGlyph state={snapshot.checksState} /> : null}
145 {snapshot?.reviewDecision ? (
146 <PullRequestReviewDecisionGlyph decision={snapshot.reviewDecision} />
147 ) : null}
148 </>
149 ) : null
150 }
151 // Match the full PR list: diff counts up top, checks under the lifecycle glyph, the
152 // verdict by the author. Each is absent rather than neutral when the host said
153 // nothing, so a row without them reads as unknown, not as fine.
154 status={
155 <PullRequestDiffStat
156 additions={snapshot?.additions ?? 0}
157 deletions={snapshot?.deletions ?? 0}
158 className="font-mono"
159 />
160 }
161 meta={
162 <>
163 {stack ? (
164 <Tooltip>
165 <TooltipTrigger
166 render={
167 <span className="inline-flex shrink-0 items-center gap-0.5 text-foreground/70" />
168 }
169 >
170 <PullRequestGlyph.stack aria-hidden className="size-3" />
171 {stack.size}
172 </TooltipTrigger>
173 <TooltipPopup>
174 {stack.kind === "native"
175 ? `GitHub stack of ${stack.size}: merging a layer lands the ones below it.`
176 : `${stack.size} pull requests chained by base branch.`}
177 </TooltipPopup>
178 </Tooltip>
179 ) : null}
180 {snapshot?.author ? (
181 <PullRequestRowAuthor
182 actor={snapshot.author}
183 className="shrink-0"
184 labelClassName="max-w-28"
185 />
186 ) : null}
187 {snapshot !== null ? (
188 <>
189 {/* Cut in the middle: rows from one owner differ in the repository name at the
190 end, which a tail cut would hide. */}
191 <Tooltip>
192 <TooltipTrigger render={<span className="flex min-w-0 max-w-32 font-mono" />}>
193 <MiddleTruncate value={link.repository} showTitle={false} />
194 </TooltipTrigger>
195 <TooltipPopup>{link.repository}</TooltipPopup>
196 </Tooltip>
197 <PullRequestRowBranches head={snapshot.headBranch} base={snapshot.baseBranch} />
198 </>
199 ) : (
200 <span className="truncate font-mono">
201 {link.host}/{link.repository}
202 </span>
203 )}
204 </>
205 }
206 updatedAt={snapshot?.updatedAt}
207 />
208 </a>
209 {/* Out of the row's flow, so no row reserves a column for a button only the hovered one
210 shows. It sits over the right end of the second line on the row's own hover color,
211 fading in from the left, so it covers the time and leaves the diff counts alone. */}
212 <span
213 className={cn(
214 "absolute right-0 bottom-0.5 flex items-center rounded-r-md bg-background pr-1 pl-5",
215 "[mask-image:linear-gradient(to_right,transparent,black_1rem)]",
216 // Hidden means untouchable too: on a touch screen there is no hover, and an invisible
217 // layer over the right of the row would otherwise swallow the tap meant for the link.
218 "pointer-events-none opacity-0 group-hover/pr-row:pointer-events-auto group-hover/pr-row:opacity-100",
219 "has-[[data-popup-open]]:pointer-events-auto has-[[data-popup-open]]:opacity-100",
220 "has-[:focus-visible]:pointer-events-auto has-[:focus-visible]:opacity-100",
221 )}
222 >
223 <span aria-hidden className="absolute inset-0 bg-accent/60" />
224 <Menu>
225 <MenuTrigger
226 render={
227 <Button
228 variant="ghost"
229 size="icon-micro"
230 aria-label={`Actions for #${link.number}`}
231 className="relative"
232 >
233 <MoreHorizontalIcon className="size-3.5" />
234 </Button>
235 }
236 />
237 <MenuPopup align="end" side="bottom">
238 <MenuItem onClick={() => void writeTextToClipboard(link.url, "link")}>
239 <LinkIcon className="size-3.5" />
240 Copy link
241 </MenuItem>
242 <MenuItem onClick={(event) => openPrLink(event, link.url, threadRef)}>
243 <ArrowUpRightIcon className="size-3.5" />
244 Open
245 </MenuItem>
246 {onSetWatching !== null && open ? (
247 <MenuItem onClick={() => onSetWatching(link, !watching)}>
248 {watching ? <EyeOffIcon className="size-3.5" /> : <EyeIcon className="size-3.5" />}
249 {watching ? "Stop watching" : "Watch for changes"}
250 </MenuItem>
251 ) : null}
252 <MenuItem onClick={() => onUnlink(link)}>
253 <PullRequestGlyph.unlink className="size-3.5" />
254 {link.source === "stack" ? "Dismiss from thread" : "Unlink from thread"}
255 </MenuItem>
256 </MenuPopup>
257 </Menu>
258 </span>
259 </div>
260 );
262​
263export function ThreadPullRequestsPanel({ threadRef }: { threadRef: ScopedThreadRef }) {
264 const configs = useServerConfigs();
265 if (configs.get(threadRef.environmentId)?.environment.capabilities.threadPullRequests !== true) {
266 return (
267 <PullRequestsUnavailableState
268 title="Linked pull requests unavailable"
269 error="This environment does not support multiple linked pull requests."
270 />
271 );
272 }
273 return <EnabledThreadPullRequestsPanel threadRef={threadRef} />;
275​
276function EnabledThreadPullRequestsPanel({ threadRef }: { threadRef: ScopedThreadRef }) {
277 const thread = useThreadShell(threadRef);
278 const openLinkDialog = useCallback(() => openLinkPullRequestDialog(threadRef), [threadRef]);
279 const unlink = useAtomCommand(threadEnvironment.unlinkPullRequest, { reportFailure: true });
280 const watch = useAtomCommand(threadEnvironment.watchPullRequest, { reportFailure: true });
281 const supportsWatch =
282 useServerConfigs().get(threadRef.environmentId)?.environment.capabilities
283 .threadPullRequestWatch === true;
284 const links = useMemo(() => visibleThreadPullRequests(thread?.pullRequests ?? []), [thread]);
285 const lines = useMemo(() => pullRequestListLines(resolveThreadPullRequestChains(links)), [links]);
286 const handleUnlink = useCallback(
287 (link: ThreadPullRequestLink) => {
288 void unlink({
289 environmentId: threadRef.environmentId,
290 input: {
291 threadId: threadRef.threadId,
292 host: link.host,
293 repository: link.repository,
294 number: link.number,
295 },
296 });
297 },
298 [threadRef, unlink],
299 );
300 const handleSetWatching = useCallback(
301 (link: ThreadPullRequestLink, watching: boolean) => {
302 void watch({
303 environmentId: threadRef.environmentId,
304 input: {
305 threadId: threadRef.threadId,
306 host: link.host,
307 repository: link.repository,
308 number: link.number,
309 watching,
310 },
311 });
312 },
313 [threadRef, watch],
314 );
315 const openCount = useMemo(
316 () => links.filter((link) => link.snapshot === null || link.snapshot.state === "open").length,
317 [links],
318 );
319 const lastSynced = useMemo(() => {
320 let latest: string | null = null;
321 for (const link of links) {
322 const at = link.snapshot?.syncedAt;
323 if (at !== undefined && (latest === null || at > latest)) latest = at;
324 }
325 return latest;
326 }, [links]);
327​
328 if (links.length === 0) {
329 return (
330 <div className="flex h-full flex-col items-center justify-center gap-2 p-6 text-center">
331 <PullRequestGlyph.link aria-hidden className="size-6 text-muted-foreground/60" />
332 <p className="text-sm font-medium">No linked pull requests</p>
333 <p className="max-w-60 text-xs text-muted-foreground">
334 Pull requests the agent opens from this thread land here. Link one yourself from a URL or
335 a number.
336 </p>
337 <Button size="sm" variant="outline" onClick={openLinkDialog}>
338 <PlusIcon className="size-3.5" />
339 Link pull request
340 </Button>
341 </div>
342 );
343 }
344​
345 return (
346 <div className="flex h-full min-h-0 flex-col">
347 <ScrollArea className="min-h-0 flex-1">
348 <div className="flex flex-col p-1.5">
349 {lines.map((line) => (
350 <LinkRow
351 key={`${line.link.host}/${line.link.repository}#${line.link.number}`}
352 line={line}
353 threadRef={threadRef}
354 onUnlink={handleUnlink}
355 onSetWatching={supportsWatch ? handleSetWatching : null}
356 />
357 ))}
358 </div>
359 </ScrollArea>
360 <footer className="flex items-center justify-between border-t border-border/60 px-2 py-1.5 text-2xs text-muted-foreground">
361 <span>
362 {openCount} open · {links.length} linked
363 {lastSynced ? ` · synced ${formatRelativeTimeLabel(lastSynced)}` : ""}
364 </span>
365 <Button size="xs" variant="ghost" onClick={openLinkDialog}>
366 <PlusIcon className="size-3.5" />
367 Link
368 </Button>
369 </footer>
370 </div>
371 );