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

ThreadPullRequestsPanel.tsx

323 lines12.3 KB

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