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

ThreadPullRequestsPanel.tsx

506 lines18.9 KB

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