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