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 } 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
282 entry={actionEntry}
283 hostActions={linkHostActions}
284 visible={speedMode}
285 />
286 ) : null}
287 <span
288 className={cn(
289 "absolute right-0 bottom-0.5 flex items-center rounded-r-md bg-background pr-1 pl-5",
290 "[mask-image:linear-gradient(to_right,transparent,black_1rem)]",
291 // Hidden means untouchable too: on a touch screen there is no hover, and an invisible
292 // layer over the right of the row would otherwise swallow the tap meant for the link.
293 "pointer-events-none opacity-0 group-hover/pr-row:pointer-events-auto group-hover/pr-row:opacity-100",
294 "has-[[data-popup-open]]:pointer-events-auto has-[[data-popup-open]]:opacity-100",
295 "has-[:focus-visible]:pointer-events-auto has-[:focus-visible]:opacity-100",
296 "group-has-[[data-pull-request-action-pending=true]]/pr-row:hidden",
297 speedMode && hasQuickActions && "hidden",
298 )}
299 >
300 <span aria-hidden className="absolute inset-0 bg-accent/60" />
301 <Menu
302 open={menuOpen}
303 onOpenChange={(open) => {
304 setMenuOpen(open);
305 if (!open) setMenuPosition(null);
306 }}
307 >
308 <MenuTrigger
309 render={
310 <Button
311 variant="ghost"
312 size="icon-micro"
313 aria-label={`Actions for #${link.number}`}
314 className="relative"
315 >
316 <MoreHorizontalIcon className="size-3.5" />
317 </Button>
318 }
319 />
320 <MenuPopup
321 anchor={menuAnchor}
322 align={menuPosition ? "start" : "end"}
323 side="bottom"
324 sideOffset={menuPosition ? 0 : 4}
325 >
326 <MenuItem onClick={() => void writeTextToClipboard(link.url, "link")}>
327 <LinkIcon className="size-3.5" />
328 Copy link
329 </MenuItem>
330 <MenuItem onClick={(event) => openPrLink(event, link.url, threadRef)}>
331 <ArrowUpRightIcon className="size-3.5" />
332 Open
333 </MenuItem>
334 {onSetWatching !== null && open ? (
335 <MenuItem onClick={() => onSetWatching(link, !watching)}>
336 {watching ? <EyeOffIcon className="size-3.5" /> : <EyeIcon className="size-3.5" />}
337 {watching ? "Stop watching" : "Watch for changes"}
338 </MenuItem>
339 ) : null}
340 <MenuItem onClick={() => onUnlink(link)}>
341 <PullRequestGlyph.unlink className="size-3.5" />
342 {link.source === "stack" ? "Dismiss from thread" : "Unlink from thread"}
343 </MenuItem>
344 </MenuPopup>
345 </Menu>
346 </span>
347 </div>
348 );
349}
350
351/** Memoized so a modifier key or a sync of one link re-renders only the rows that changed. */
352const LinkRow = memo(LinkRowImpl);
353
354function latestSyncedAt(links: ReadonlyArray<ThreadPullRequestLink>): string | null {
355 let latest: string | null = null;
356 for (const link of links) {
357 const at = link.snapshot?.syncedAt;
358 if (at !== undefined && (latest === null || at > latest)) latest = at;
359 }
360 return latest;
361}
362
363const lineKey = (line: PullRequestListLine) =>
364 `${line.link.host}/${line.link.repository}#${line.link.number}`;
365
366export function ThreadPullRequestsPanel({ threadRef }: { threadRef: ScopedThreadRef }) {
367 const configs = useServerConfigs();
368 if (configs.get(threadRef.environmentId)?.environment.capabilities.threadPullRequests !== true) {
369 return (
370 <PullRequestsUnavailableState
371 title="Linked pull requests unavailable"
372 error="This environment does not support multiple linked pull requests."
373 />
374 );
375 }
376 return <EnabledThreadPullRequestsPanel threadRef={threadRef} />;
377}
378
379function EnabledThreadPullRequestsPanel({ threadRef }: { threadRef: ScopedThreadRef }) {
380 const thread = useThreadShell(threadRef);
381 const projects = useProjects();
382 const environmentProjects = projects
383 .filter((project) => project.environmentId === threadRef.environmentId)
384 .toSorted((left, right) =>
385 left.id === thread?.projectId ? -1 : right.id === thread?.projectId ? 1 : 0,
386 );
387 // LegendList re-renders its rows when `data` changes identity. `links` and values derived
388 // from it go through plain functions only here, before the next hook, so the compiler keeps
389 // `lines` in its own cache scope.
390 const links = visibleThreadPullRequests(thread?.pullRequests ?? []);
391 const lines = pullRequestListLines(resolveThreadPullRequestChains(links));
392 const openCount = links.filter(
393 (link) => link.snapshot === null || link.snapshot.state === "open",
394 ).length;
395 const lastSynced = latestSyncedAt(links);
396 const linkCount = links.length;
397 const modifiers = useShortcutModifierState(true);
398 const speedMode =
399 modifiers.shiftKey && !modifiers.metaKey && !modifiers.ctrlKey && !modifiers.altKey;
400 const openLinkDialog = () => openLinkPullRequestDialog(threadRef);
401 const unlink = useAtomCommand(threadEnvironment.unlinkPullRequest, { reportFailure: true });
402 const watch = useAtomCommand(threadEnvironment.watchPullRequest, { reportFailure: true });
403 const capabilities = useServerConfigs().get(threadRef.environmentId)?.environment.capabilities;
404 const supportsWatch = capabilities?.threadPullRequestWatch === true;
405 const handleUnlink = (link: ThreadPullRequestLink) => {
406 void unlink({
407 environmentId: threadRef.environmentId,
408 input: {
409 threadId: threadRef.threadId,
410 host: link.host,
411 repository: link.repository,
412 number: link.number,
413 },
414 });
415 };
416 const handleSetWatching = (link: ThreadPullRequestLink, watching: boolean) => {
417 void watch({
418 environmentId: threadRef.environmentId,
419 input: {
420 threadId: threadRef.threadId,
421 host: link.host,
422 repository: link.repository,
423 number: link.number,
424 watching,
425 },
426 });
427 };
428
429 // Legend re-renders visible rows only when data or extraData changes, so everything the rows
430 // read from outside their line goes in here.
431 const rowInputs = { speedMode, environmentProjects, capabilities, supportsWatch, thread };
432
433 if (linkCount === 0) {
434 return (
435 <div className="flex h-full flex-col items-center justify-center gap-2 p-6 text-center">
436 <PullRequestGlyph.link aria-hidden className="size-6 text-muted-foreground/60" />
437 <p className="text-sm font-medium">No linked pull requests</p>
438 <p className="max-w-60 text-xs text-muted-foreground">
439 Pull requests the agent opens from this thread land here. Link one yourself from a URL or
440 a number.
441 </p>
442 <Button size="sm" variant="outline" onClick={openLinkDialog}>
443 <PlusIcon className="size-3.5" />
444 Link pull request
445 </Button>
446 </div>
447 );
448 }
449
450 return (
451 <div className="flex h-full min-h-0 flex-col">
452 {/* Threads that run a stack or a sweep link hundreds of pull requests; only the rows in
453 view are mounted. */}
454 <LegendList<PullRequestListLine>
455 data={lines}
456 keyExtractor={lineKey}
457 extraData={rowInputs}
458 renderItem={({ item: line }) => (
459 <LinkRow
460 line={line}
461 threadRef={threadRef}
462 projectId={
463 capabilities?.pullRequests === true
464 ? (findProjectForChangeRequest(environmentProjects, line.link)?.id ??
465 thread?.projectId ??
466 null)
467 : null
468 }
469 speedMode={speedMode}
470 onUnlink={handleUnlink}
471 onSetWatching={supportsWatch ? handleSetWatching : null}
472 />
473 )}
474 estimatedItemSize={44}
475 drawDistance={440}
476 className="min-h-0 flex-1 overscroll-contain p-1.5"
477 />
478 <footer className="flex items-center justify-between border-t border-border/60 px-2 py-1.5 text-2xs text-muted-foreground">
479 <span>
480 {openCount} open · {linkCount} linked
481 {lastSynced ? (
482 <>
483 {" · synced "}
484 <RelativeTime timestamp={lastSynced} />
485 </>
486 ) : null}
487 </span>
488 <Button size="xs" variant="ghost" onClick={openLinkDialog}>
489 <PlusIcon className="size-3.5" />
490 Link
491 </Button>
492 </footer>
493 </div>
494 );
495}