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