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

ThreadPullRequestsPanel.tsx

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