Open History to see the last commit
1import type { ProjectId, ScopedThreadRef, ThreadPullRequestLink } from "@t3tools/contracts";
2import {
3 sourceControlClients,
4 UNKNOWN_SOURCE_CONTROL_CLIENT,
5} from "@t3tools/client-runtime/source-control-clients";
6import {
7 type PullRequestListLine,
8 pullRequestListLines,
9 resolveThreadPullRequestChains,
10 visibleThreadPullRequests,
11} from "@t3tools/shared/threadPullRequests";
12import {
13 ArrowUpRightIcon,
14 EyeIcon,
15 EyeOffIcon,
16 LinkIcon,
17 MoreHorizontalIcon,
18 PlusIcon,
19} from "lucide-react";
20import { LegendList } from "@legendapp/list/react";
21import { memo, useState } from "react";
22
23import {
24 COMPOSER_PULL_REQUEST_DRAG_TYPE,
25 encodePullRequestDragPayload,
26} from "~/components/chat/composerMentionDrag";
27import { writeTextToClipboard } from "~/hooks/useCopyToClipboard";
28import { findProjectForChangeRequest, useOpenPrLink } from "~/lib/openPullRequestLink";
29import { cn } from "~/lib/utils";
30import { useShortcutModifierState } from "~/shortcutModifierState";
31import { useProjects, useServerConfigs, useThreadShell } from "~/state/entities";
32import { PullRequestChangeBreakdownStat } from "./PullRequestChangeBreakdownStat";
33import { PullRequestsUnavailableState } from "./PullRequestsUnavailableState";
34import { threadEnvironment } from "~/state/threads";
35import { useAtomCommand } from "~/state/use-atom-command";
36import { RelativeTime } from "~/components/RelativeTime";
37import { Button } from "../ui/button";
38import { Menu, MenuItem, MenuPopup, MenuTrigger } from "../ui/menu";
39import { MiddleTruncate } from "../ui/middle-truncate";
40import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";
41import { openLinkPullRequestDialog } from "./LinkPullRequestDialog";
42import {
43 PULL_REQUEST_ROW_CLASS,
44 PULL_REQUEST_ROW_NUMBER_CLASS,
45 PullRequestRowAuthor,
46 PullRequestRowBranches,
47 PullRequestRowGlyph,
48 PullRequestRowLines,
49} from "./PullRequestListRow";
50import {
51 PullRequestDiffStat,
52 PullRequestReviewDecisionGlyph,
53 pullRequestChecksStatePresentation,
54} from "./pullRequestPresentation";
55import { PullRequestGlyph } from "./pullRequestIcons";
56import { pullRequestQuickActions } from "./pullRequestList.logic";
57import { PullRequestSpeedActions, PullRequestSpeedModeContext } from "./PullRequestSpeedActions";
58
59const SOURCE_LABELS: Record<ThreadPullRequestLink["source"], string> = {
60 manual: "Linked by you",
61 created: "Created from this thread",
62 agent: "Linked by the agent",
63 stack: "Found in the stack",
64 "stack-dismissed": "Dismissed",
65};
66
67function ChecksGlyph({
68 state,
69}: {
70 state: NonNullable<ThreadPullRequestLink["snapshot"]>["checksState"] & string;
71}) {
72 const presentation = pullRequestChecksStatePresentation(state);
73 return (
74 <Tooltip>
75 <TooltipTrigger render={<span className="inline-flex shrink-0" />}>
76 <presentation.Icon
77 role="img"
78 aria-label={presentation.label}
79 className={cn("size-3.5", presentation.toneClassName)}
80 />
81 </TooltipTrigger>
82 <TooltipPopup>{presentation.label}</TooltipPopup>
83 </Tooltip>
84 );
85}
86
87function LinkRowImpl({
88 line,
89 threadRef,
90 projectId,
91 speedMode,
92 onUnlink,
93 onSetWatching,
94}: {
95 line: PullRequestListLine;
96 threadRef: ScopedThreadRef;
97 projectId: ProjectId | null;
98 speedMode: boolean;
99 onUnlink: (link: ThreadPullRequestLink) => void;
100 onSetWatching: ((link: ThreadPullRequestLink, watching: boolean) => void) | null;
101}) {
102 const openPrLink = useOpenPrLink(threadRef);
103 const [menuOpen, setMenuOpen] = useState(false);
104 const [menuPosition, setMenuPosition] = useState<{ x: number; y: number } | null>(null);
105 const menuAnchor = menuPosition
106 ? { getBoundingClientRect: () => new DOMRect(menuPosition.x, menuPosition.y, 0, 0) }
107 : undefined;
108 const { link, depth, stack } = line;
109 const snapshot = link.snapshot;
110 const open = snapshot === null || snapshot.state === "open";
111 const watching = link.watch !== undefined;
112 const linkHostActions = (
113 sourceControlClients.findByChangeRequestUrl(link.url) ?? UNKNOWN_SOURCE_CONTROL_CLIENT
114 ).changeRequestActions;
115 const actionEntry =
116 projectId !== null && snapshot !== null && snapshot.state !== "merged"
117 ? {
118 environmentId: threadRef.environmentId,
119 projectId,
120 host: link.host,
121 repository: link.repository,
122 number: link.number,
123 state: snapshot.state,
124 isDraft: snapshot.isDraft,
125 ...(link.stack === null ? {} : { stack: link.stack }),
126 }
127 : null;
128 const hasQuickActions =
129 actionEntry !== null && pullRequestQuickActions(actionEntry, linkHostActions).length > 0;
130 return (
131 <div
132 className={cn(PULL_REQUEST_ROW_CLASS, "relative hover:bg-accent/60")}
133 onContextMenu={(event) => {
134 event.preventDefault();
135 event.stopPropagation();
136 setMenuPosition({ x: event.clientX, y: event.clientY });
137 setMenuOpen(true);
138 }}
139 style={{ paddingLeft: `${0.5 + Math.min(depth, 3) * 1.25}rem` }}
140 >
141 {depth > 0 ? <span aria-hidden className="-ml-2 h-6 w-px shrink-0 bg-border/70" /> : null}
142 {snapshot === null ? (
143 <PullRequestGlyph.pullRequest
144 aria-label="Waiting for host state"
145 className="size-4 shrink-0 text-muted-foreground"
146 />
147 ) : (
148 <PullRequestRowGlyph
149 state={snapshot.state}
150 isDraft={snapshot.isDraft}
151 mergeability={snapshot.mergeability}
152 baseBranch={snapshot.baseBranch}
153 />
154 )}
155 <a
156 href={link.url}
157 onClick={(event) => openPrLink(event, link.url, threadRef)}
158 // The link's own URL still rides along for drops outside the app; the composer takes
159 // this payload instead and adds the pull request as a context chip.
160 onDragStart={
161 snapshot === null
162 ? undefined
163 : (event) =>
164 event.dataTransfer.setData(
165 COMPOSER_PULL_REQUEST_DRAG_TYPE,
166 encodePullRequestDragPayload({
167 number: link.number,
168 title: snapshot.title,
169 url: link.url,
170 headBranch: snapshot.headBranch,
171 baseBranch: snapshot.baseBranch,
172 state: snapshot.state,
173 isDraft: snapshot.isDraft,
174 }),
175 )
176 }
177 className="flex min-w-0 flex-1"
178 >
179 <PullRequestRowLines
180 number={
181 <Tooltip>
182 <TooltipTrigger render={<span className={PULL_REQUEST_ROW_NUMBER_CLASS} />}>
183 #{link.number}
184 </TooltipTrigger>
185 <TooltipPopup>
186 {SOURCE_LABELS[link.source]} · <RelativeTime timestamp={link.linkedAt} />
187 </TooltipPopup>
188 </Tooltip>
189 }
190 title={snapshot?.title ?? link.repository}
191 signals={
192 open ? (
193 <>
194 {watching ? (
195 <Tooltip>
196 <TooltipTrigger render={<span className="inline-flex shrink-0" />}>
197 <EyeIcon role="img" aria-label="Watching" className="size-3.5" />
198 </TooltipTrigger>
199 <TooltipPopup>
200 Watching: the agent wakes when checks finish, someone comments, or the branch
201 conflicts
202 </TooltipPopup>
203 </Tooltip>
204 ) : null}
205 {snapshot?.checksState ? <ChecksGlyph state={snapshot.checksState} /> : null}
206 {snapshot?.reviewDecision ? (
207 <PullRequestReviewDecisionGlyph decision={snapshot.reviewDecision} />
208 ) : null}
209 </>
210 ) : null
211 }
212 status={
213 projectId === null ? (
214 <PullRequestDiffStat
215 additions={snapshot?.additions ?? 0}
216 deletions={snapshot?.deletions ?? 0}
217 className="font-mono"
218 />
219 ) : (
220 <PullRequestChangeBreakdownStat
221 environmentId={threadRef.environmentId}
222 reference={{
223 projectId,
224 host: link.host,
225 repository: link.repository,
226 number: link.number,
227 }}
228 additions={snapshot?.additions ?? 0}
229 deletions={snapshot?.deletions ?? 0}
230 className="font-mono"
231 />
232 )
233 }
234 meta={
235 <>
236 {stack ? (
237 <Tooltip>
238 <TooltipTrigger
239 render={
240 <span className="inline-flex shrink-0 items-center gap-0.5 text-foreground/70" />
241 }
242 >
243 <PullRequestGlyph.stack aria-hidden className="size-3" />
244 {stack.size}
245 </TooltipTrigger>
246 <TooltipPopup>
247 {stack.kind === "native"
248 ? `${sourceControlClients.hostLabelForChangeRequestUrl(link.url)} stack of ${stack.size}: merging a layer lands the ones below it.`
249 : `${stack.size} pull requests chained by base branch.`}
250 </TooltipPopup>
251 </Tooltip>
252 ) : null}
253 {snapshot?.author ? (
254 <PullRequestRowAuthor
255 actor={snapshot.author}
256 className="shrink-0"
257 labelClassName="max-w-28"
258 />
259 ) : null}
260 {snapshot !== null ? (
261 <>
262 <Tooltip>
263 <TooltipTrigger render={<span className="flex min-w-0 max-w-32 font-mono" />}>
264 <MiddleTruncate value={link.repository} showTitle={false} />
265 </TooltipTrigger>
266 <TooltipPopup>{link.repository}</TooltipPopup>
267 </Tooltip>
268 <PullRequestRowBranches head={snapshot.headBranch} base={snapshot.baseBranch} />
269 </>
270 ) : (
271 <span className="truncate font-mono">
272 {link.host}/{link.repository}
273 </span>
274 )}
275 </>
276 }
277 updatedAt={snapshot?.updatedAt}
278 />
279 </a>
280 {actionEntry !== null ? (
281 <PullRequestSpeedActions entry={actionEntry} hostActions={linkHostActions} />
282 ) : null}
283 <span
284 className={cn(
285 "absolute right-0 bottom-0.5 flex items-center rounded-r-md bg-background pr-1 pl-5",
286 "[mask-image:linear-gradient(to_right,transparent,black_1rem)]",
287 // Hidden means untouchable too: on a touch screen there is no hover, and an invisible
288 // layer over the right of the row would otherwise swallow the tap meant for the link.
289 "pointer-events-none opacity-0 group-hover/pr-row:pointer-events-auto group-hover/pr-row:opacity-100",
290 "has-[[data-popup-open]]:pointer-events-auto has-[[data-popup-open]]:opacity-100",
291 "has-[:focus-visible]:pointer-events-auto has-[:focus-visible]:opacity-100",
292 "group-has-[[data-pull-request-action-pending=true]]/pr-row:hidden",
293 speedMode && hasQuickActions && "hidden",
294 )}
295 >
296 <span aria-hidden className="absolute inset-0 bg-accent/60" />
297 <Menu
298 open={menuOpen}
299 onOpenChange={(open) => {
300 setMenuOpen(open);
301 if (!open) setMenuPosition(null);
302 }}
303 >
304 <MenuTrigger
305 render={
306 <Button
307 variant="ghost"
308 size="icon-micro"
309 aria-label={`Actions for #${link.number}`}
310 className="relative"
311 >
312 <MoreHorizontalIcon className="size-3.5" />
313 </Button>
314 }
315 />
316 <MenuPopup
317 anchor={menuAnchor}
318 align={menuPosition ? "start" : "end"}
319 side="bottom"
320 sideOffset={menuPosition ? 0 : 4}
321 >
322 <MenuItem onClick={() => void writeTextToClipboard(link.url, "link")}>
323 <LinkIcon className="size-3.5" />
324 Copy link
325 </MenuItem>
326 <MenuItem onClick={(event) => openPrLink(event, link.url, threadRef)}>
327 <ArrowUpRightIcon className="size-3.5" />
328 Open
329 </MenuItem>
330 {onSetWatching !== null && open ? (
331 <MenuItem onClick={() => onSetWatching(link, !watching)}>
332 {watching ? <EyeOffIcon className="size-3.5" /> : <EyeIcon className="size-3.5" />}
333 {watching ? "Stop watching" : "Watch for changes"}
334 </MenuItem>
335 ) : null}
336 <MenuItem onClick={() => onUnlink(link)}>
337 <PullRequestGlyph.unlink className="size-3.5" />
338 {link.source === "stack" ? "Dismiss from thread" : "Unlink from thread"}
339 </MenuItem>
340 </MenuPopup>
341 </Menu>
342 </span>
343 </div>
344 );
345}
346
347/** Memoized so a modifier key or a sync of one link re-renders only the rows that changed. */
348const LinkRow = memo(LinkRowImpl);
349
350function latestSyncedAt(links: ReadonlyArray<ThreadPullRequestLink>): string | null {
351 let latest: string | null = null;
352 for (const link of links) {
353 const at = link.snapshot?.syncedAt;
354 if (at !== undefined && (latest === null || at > latest)) latest = at;
355 }
356 return latest;
357}
358
359const lineKey = (line: PullRequestListLine) =>
360 `${line.link.host}/${line.link.repository}#${line.link.number}`;
361
362export function ThreadPullRequestsPanel({ threadRef }: { threadRef: ScopedThreadRef }) {
363 const configs = useServerConfigs();
364 if (configs.get(threadRef.environmentId)?.environment.capabilities.threadPullRequests !== true) {
365 return (
366 <PullRequestsUnavailableState
367 title="Linked pull requests unavailable"
368 error="This environment does not support multiple linked pull requests."
369 />
370 );
371 }
372 return <EnabledThreadPullRequestsPanel threadRef={threadRef} />;
373}
374
375function EnabledThreadPullRequestsPanel({ threadRef }: { threadRef: ScopedThreadRef }) {
376 const thread = useThreadShell(threadRef);
377 const projects = useProjects();
378 const environmentProjects = projects
379 .filter((project) => project.environmentId === threadRef.environmentId)
380 .toSorted((left, right) =>
381 left.id === thread?.projectId ? -1 : right.id === thread?.projectId ? 1 : 0,
382 );
383 // LegendList re-renders its rows when `data` changes identity. `links` and values derived
384 // from it go through plain functions only here, before the next hook, so the compiler keeps
385 // `lines` in its own cache scope.
386 const links = visibleThreadPullRequests(thread?.pullRequests ?? []);
387 const lines = pullRequestListLines(resolveThreadPullRequestChains(links));
388 const openCount = links.filter(
389 (link) => link.snapshot === null || link.snapshot.state === "open",
390 ).length;
391 const lastSynced = latestSyncedAt(links);
392 const linkCount = links.length;
393 const modifiers = useShortcutModifierState(true);
394 const speedMode =
395 modifiers.shiftKey && !modifiers.metaKey && !modifiers.ctrlKey && !modifiers.altKey;
396 const openLinkDialog = () => openLinkPullRequestDialog(threadRef);
397 const unlink = useAtomCommand(threadEnvironment.unlinkPullRequest, { reportFailure: true });
398 const watch = useAtomCommand(threadEnvironment.watchPullRequest, { reportFailure: true });
399 const capabilities = useServerConfigs().get(threadRef.environmentId)?.environment.capabilities;
400 const supportsWatch = capabilities?.threadPullRequestWatch === true;
401 const handleUnlink = (link: ThreadPullRequestLink) => {
402 void unlink({
403 environmentId: threadRef.environmentId,
404 input: {
405 threadId: threadRef.threadId,
406 host: link.host,
407 repository: link.repository,
408 number: link.number,
409 },
410 });
411 };
412 const handleSetWatching = (link: ThreadPullRequestLink, watching: boolean) => {
413 void watch({
414 environmentId: threadRef.environmentId,
415 input: {
416 threadId: threadRef.threadId,
417 host: link.host,
418 repository: link.repository,
419 number: link.number,
420 watching,
421 },
422 });
423 };
424
425 // Legend re-renders visible rows only when data or extraData changes, so everything the rows
426 // read from outside their line goes in here.
427 const rowInputs = { speedMode, environmentProjects, capabilities, supportsWatch, thread };
428
429 if (linkCount === 0) {
430 return (
431 <div className="flex h-full flex-col items-center justify-center gap-2 p-6 text-center">
432 <PullRequestGlyph.link aria-hidden className="size-6 text-muted-foreground/60" />
433 <p className="text-sm font-medium">No linked pull requests</p>
434 <p className="max-w-60 text-xs text-muted-foreground">
435 Pull requests the agent opens from this thread land here. Link one yourself from a URL or
436 a number.
437 </p>
438 <Button size="sm" variant="outline" onClick={openLinkDialog}>
439 <PlusIcon className="size-3.5" />
440 Link pull request
441 </Button>
442 </div>
443 );
444 }
445
446 return (
447 <PullRequestSpeedModeContext value={speedMode}>
448 <div className="flex h-full min-h-0 flex-col">
449 {/* Threads that run a stack or a sweep link hundreds of pull requests; only the rows in
450 view are mounted. */}
451 <LegendList<PullRequestListLine>
452 data={lines}
453 keyExtractor={lineKey}
454 extraData={rowInputs}
455 renderItem={({ item: line }) => (
456 <LinkRow
457 line={line}
458 threadRef={threadRef}
459 projectId={
460 capabilities?.pullRequests === true
461 ? (findProjectForChangeRequest(environmentProjects, line.link)?.id ??
462 thread?.projectId ??
463 null)
464 : null
465 }
466 speedMode={speedMode}
467 onUnlink={handleUnlink}
468 onSetWatching={supportsWatch ? handleSetWatching : null}
469 />
470 )}
471 estimatedItemSize={44}
472 drawDistance={440}
473 className="min-h-0 flex-1 overscroll-contain p-1.5"
474 />
475 <footer className="flex items-center justify-between border-t border-border/60 px-2 py-1.5 text-2xs text-muted-foreground">
476 <span>
477 {openCount} open · {linkCount} linked
478 {lastSynced ? (
479 <>
480 {" · synced "}
481 <RelativeTime timestamp={lastSynced} />
482 </>
483 ) : null}
484 </span>
485 <Button size="xs" variant="ghost" onClick={openLinkDialog}>
486 <PlusIcon className="size-3.5" />
487 Link
488 </Button>
489 </footer>
490 </div>
491 </PullRequestSpeedModeContext>
492 );
493}