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

ThreadPullRequestsPanel.tsx

497 lines18.5 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/client-runtime/thread-pull-requests";
12import { canStartThreadPullRequestWatch } from "@t3tools/client-runtime/thread-pull-request-compatibility";
13import {
14 ArrowUpRightIcon,
15 EyeIcon,
16 EyeOffIcon,
17 LinkIcon,
18 MoreHorizontalIcon,
19 PlusIcon,
20} from "lucide-react";
21import { LegendList } from "@legendapp/list/react";
22import { memo, useState } from "react";
23​
24import {
25 COMPOSER_PULL_REQUEST_DRAG_TYPE,
26 encodePullRequestDragPayload,
27} from "~/components/chat/composerMentionDrag";
28import { writeTextToClipboard } from "~/hooks/useCopyToClipboard";
29import { findProjectForChangeRequest } from "@t3tools/client-runtime/change-request-links";
30import { useOpenPrLink } from "~/lib/openPullRequestLink";
31import { cn } from "~/lib/utils";
32import { useShortcutModifierState } from "~/shortcutModifierState";
33import { useProjects, useServerConfigs, useThreadShell } from "~/state/entities";
34import { PullRequestChangeBreakdownStat } from "./PullRequestChangeBreakdownStat";
35import { PullRequestsUnavailableState } from "./PullRequestsUnavailableState";
36import { threadEnvironment } from "~/state/threads";
37import { useAtomCommand } from "~/state/use-atom-command";
38import { RelativeTime } from "~/components/RelativeTime";
39import { Button } from "../ui/button";
40import { Menu, MenuItem, MenuPopup, MenuTrigger } from "../ui/menu";
41import { MiddleTruncate } from "../ui/middle-truncate";
42import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";
43import { openLinkPullRequestDialog } from "./LinkPullRequestDialog";
44import {
45 PULL_REQUEST_ROW_CLASS,
46 PULL_REQUEST_ROW_NUMBER_CLASS,
47 PullRequestRowAuthor,
48 PullRequestRowBranches,
49 PullRequestRowGlyph,
50 PullRequestRowLines,
51} from "./PullRequestListRow";
52import {
53 PullRequestDiffStat,
54 PullRequestReviewDecisionGlyph,
55 pullRequestChecksStatePresentation,
56} from "./pullRequestPresentation";
57import { PullRequestGlyph } from "./pullRequestIcons";
58import { pullRequestQuickActions } from "./pullRequestList.logic";
59import { PullRequestSpeedActions, PullRequestSpeedModeContext } from "./PullRequestSpeedActions";
60​
61const SOURCE_LABELS: Record<ThreadPullRequestLink["source"], string> = {
62 manual: "Linked by you",
63 created: "Created from this thread",
64 agent: "Linked by the agent",
65 stack: "Found in the stack",
66 "stack-dismissed": "Dismissed",
67};
68​
69function ChecksGlyph({
70 state,
71}: {
72 state: NonNullable<ThreadPullRequestLink["snapshot"]>["checksState"] & string;
73}) {
74 const presentation = pullRequestChecksStatePresentation(state);
75 return (
76 <Tooltip>
77 <TooltipTrigger render={<span className="inline-flex shrink-0" />}>
78 <presentation.Icon
79 role="img"
80 aria-label={presentation.label}
81 className={cn("size-3.5", presentation.toneClassName)}
82 />
83 </TooltipTrigger>
84 <TooltipPopup>{presentation.label}</TooltipPopup>
85 </Tooltip>
86 );
88​
89function LinkRowImpl({
90 line,
91 threadRef,
92 projectId,
93 speedMode,
94 onUnlink,
95 onSetWatching,
96 canStartWatch,
97}: {
98 line: PullRequestListLine;
99 threadRef: ScopedThreadRef;
100 projectId: ProjectId | null;
101 speedMode: boolean;
102 onUnlink: (link: ThreadPullRequestLink) => void;
103 onSetWatching: ((link: ThreadPullRequestLink, watching: boolean) => void) | null;
104 canStartWatch: boolean;
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 linkHost =
117 sourceControlClients.findByChangeRequestUrl(link.url) ?? UNKNOWN_SOURCE_CONTROL_CLIENT;
118 const linkHostActions = linkHost.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 // Outside drops use the URL; the composer uses this context-chip payload.
163 onDragStart={
164 snapshot === null
165 ? undefined
166 : (event) =>
167 event.dataTransfer.setData(
168 COMPOSER_PULL_REQUEST_DRAG_TYPE,
169 encodePullRequestDragPayload({
170 number: link.number,
171 title: snapshot.title,
172 url: link.url,
173 headBranch: snapshot.headBranch,
174 baseBranch: snapshot.baseBranch,
175 state: snapshot.state,
176 isDraft: snapshot.isDraft,
177 }),
178 )
179 }
180 className="flex min-w-0 flex-1"
181 >
182 <PullRequestRowLines
183 number={
184 <Tooltip>
185 <TooltipTrigger render={<span className={PULL_REQUEST_ROW_NUMBER_CLASS} />}>
186 #{link.number}
187 </TooltipTrigger>
188 <TooltipPopup>
189 {SOURCE_LABELS[link.source]} · <RelativeTime timestamp={link.linkedAt} />
190 </TooltipPopup>
191 </Tooltip>
192 }
193 title={snapshot?.title ?? link.repository}
194 signals={
195 open ? (
196 <>
197 {watching ? (
198 <Tooltip>
199 <TooltipTrigger render={<span className="inline-flex shrink-0" />}>
200 <EyeIcon role="img" aria-label="Watching" className="size-3.5" />
201 </TooltipTrigger>
202 <TooltipPopup>
203 Watching: the agent wakes when checks finish, someone comments, or the branch
204 conflicts
205 </TooltipPopup>
206 </Tooltip>
207 ) : null}
208 {snapshot?.checksState ? <ChecksGlyph state={snapshot.checksState} /> : null}
209 {snapshot?.reviewDecision ? (
210 <PullRequestReviewDecisionGlyph decision={snapshot.reviewDecision} />
211 ) : null}
212 </>
213 ) : null
214 }
215 status={
216 projectId === null ? (
217 <PullRequestDiffStat
218 additions={snapshot?.additions ?? 0}
219 deletions={snapshot?.deletions ?? 0}
220 className="font-mono"
221 />
222 ) : (
223 <PullRequestChangeBreakdownStat
224 environmentId={threadRef.environmentId}
225 reference={{
226 projectId,
227 host: link.host,
228 repository: link.repository,
229 number: link.number,
230 }}
231 additions={snapshot?.additions ?? 0}
232 deletions={snapshot?.deletions ?? 0}
233 className="font-mono"
234 />
235 )
236 }
237 meta={
238 <>
239 {stack ? (
240 <Tooltip>
241 <TooltipTrigger
242 render={
243 <span className="inline-flex shrink-0 items-center gap-0.5 text-foreground/70" />
244 }
245 >
246 <PullRequestGlyph.stack aria-hidden className="size-3" />
247 {stack.size}
248 </TooltipTrigger>
249 <TooltipPopup>
250 {stack.kind === "native"
251 ? `${sourceControlClients.hostLabelForChangeRequestUrl(link.url)} stack of ${stack.size}: merging a layer lands the ones below it.`
252 : `${stack.size} ${linkHost.changeRequest.plural} chained by base branch.`}
253 </TooltipPopup>
254 </Tooltip>
255 ) : null}
256 {snapshot?.author ? (
257 <PullRequestRowAuthor
258 actor={snapshot.author}
259 className="shrink-0"
260 labelClassName="max-w-28"
261 />
262 ) : null}
263 {snapshot !== null ? (
264 <>
265 <Tooltip>
266 <TooltipTrigger render={<span className="flex min-w-0 max-w-32 font-mono" />}>
267 <MiddleTruncate value={link.repository} showTitle={false} />
268 </TooltipTrigger>
269 <TooltipPopup>{link.repository}</TooltipPopup>
270 </Tooltip>
271 <PullRequestRowBranches head={snapshot.headBranch} base={snapshot.baseBranch} />
272 </>
273 ) : (
274 <span className="truncate font-mono">
275 {link.host}/{link.repository}
276 </span>
277 )}
278 </>
279 }
280 updatedAt={snapshot?.updatedAt}
281 />
282 </a>
283 {actionEntry !== null ? (
284 <PullRequestSpeedActions
285 entry={actionEntry}
286 hostActions={linkHostActions}
287 terminology={linkHost.changeRequest}
288 />
289 ) : null}
290 <span
291 className={cn(
292 "absolute right-0 bottom-0.5 flex items-center rounded-r-md bg-background pr-1 pl-5",
293 "[mask-image:linear-gradient(to_right,transparent,black_1rem)]",
294 // Hidden controls would intercept link taps on touch screens.
295 "pointer-events-none opacity-0 group-hover/pr-row:pointer-events-auto group-hover/pr-row:opacity-100",
296 "has-[[data-popup-open]]:pointer-events-auto has-[[data-popup-open]]:opacity-100",
297 "has-[:focus-visible]:pointer-events-auto has-[:focus-visible]:opacity-100",
298 "group-has-[[data-pull-request-action-pending=true]]/pr-row:hidden",
299 speedMode && hasQuickActions && "hidden",
300 )}
301 >
302 <span aria-hidden className="absolute inset-0 bg-accent/60" />
303 <Menu
304 open={menuOpen}
305 onOpenChange={(open) => {
306 setMenuOpen(open);
307 if (!open) setMenuPosition(null);
308 }}
309 >
310 <MenuTrigger
311 render={
312 <Button
313 variant="ghost"
314 size="icon-micro"
315 aria-label={`Actions for #${link.number}`}
316 className="relative"
317 >
318 <MoreHorizontalIcon className="size-3.5" />
319 </Button>
320 }
321 />
322 <MenuPopup
323 anchor={menuAnchor}
324 align={menuPosition ? "start" : "end"}
325 side="bottom"
326 sideOffset={menuPosition ? 0 : 4}
327 >
328 <MenuItem onClick={() => void writeTextToClipboard(link.url, "link")}>
329 <LinkIcon className="size-3.5" />
330 Copy link
331 </MenuItem>
332 <MenuItem onClick={(event) => openPrLink(event, link.url, threadRef)}>
333 <ArrowUpRightIcon className="size-3.5" />
334 Open
335 </MenuItem>
336 {onSetWatching !== null && open && (watching || canStartWatch) ? (
337 <MenuItem onClick={() => onSetWatching(link, !watching)}>
338 {watching ? <EyeOffIcon className="size-3.5" /> : <EyeIcon className="size-3.5" />}
339 {watching ? "Stop watching" : "Watch for changes"}
340 </MenuItem>
341 ) : null}
342 <MenuItem onClick={() => onUnlink(link)}>
343 <PullRequestGlyph.unlink className="size-3.5" />
344 {link.source === "stack" ? "Dismiss from thread" : "Unlink from thread"}
345 </MenuItem>
346 </MenuPopup>
347 </Menu>
348 </span>
349 </div>
350 );
352​
353const LinkRow = memo(LinkRowImpl);
354​
355function latestSyncedAt(links: ReadonlyArray<ThreadPullRequestLink>): string | null {
356 let latest: string | null = null;
357 for (const link of links) {
358 const at = link.snapshot?.syncedAt;
359 if (at !== undefined && (latest === null || at > latest)) latest = at;
360 }
361 return latest;
363​
364const lineKey = (line: PullRequestListLine) =>
365 `${line.link.host}/${line.link.repository}#${line.link.number}`;
366​
367export function ThreadPullRequestsPanel({ threadRef }: { threadRef: ScopedThreadRef }) {
368 const configs = useServerConfigs();
369 if (configs.get(threadRef.environmentId) === undefined) {
370 return (
371 <PullRequestsUnavailableState
372 title="Linked pull requests unavailable"
373 error="This environment does not support multiple linked pull requests."
374 />
375 );
376 }
377 return <EnabledThreadPullRequestsPanel threadRef={threadRef} />;
379​
380function EnabledThreadPullRequestsPanel({ threadRef }: { threadRef: ScopedThreadRef }) {
381 const thread = useThreadShell(threadRef);
382 const projects = useProjects();
383 const environmentProjects = projects
384 .filter((project) => project.environmentId === threadRef.environmentId)
385 .toSorted((left, right) =>
386 left.id === thread?.projectId ? -1 : right.id === thread?.projectId ? 1 : 0,
387 );
388 // Derive lines before later hooks to preserve compiler caching and avoid LegendList renders.
389 const links = visibleThreadPullRequests(thread?.pullRequests ?? []);
390 const lines = pullRequestListLines(resolveThreadPullRequestChains(links));
391 const openCount = links.filter(
392 (link) => link.snapshot === null || link.snapshot.state === "open",
393 ).length;
394 const lastSynced = latestSyncedAt(links);
395 const linkCount = links.length;
396 const modifiers = useShortcutModifierState(true);
397 const speedMode =
398 modifiers.shiftKey && !modifiers.metaKey && !modifiers.ctrlKey && !modifiers.altKey;
399 const openLinkDialog = () => openLinkPullRequestDialog(threadRef);
400 const unlink = useAtomCommand(threadEnvironment.unlinkPullRequest, { reportFailure: true });
401 const watch = useAtomCommand(threadEnvironment.watchPullRequest, { reportFailure: true });
402 const capabilities = useServerConfigs().get(threadRef.environmentId)?.environment.capabilities;
403 const supportsWatch = capabilities?.threadPullRequestWatch === true;
404 const canStartWatch = thread !== null && canStartThreadPullRequestWatch(thread);
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 rows update only for data/extraData changes; include all external inputs.
430 const rowInputs = { speedMode, environmentProjects, capabilities, supportsWatch, thread };
431​
432 if (linkCount === 0) {
433 return (
434 <div className="flex h-full flex-col items-center justify-center gap-2 p-6 text-center">
435 <PullRequestGlyph.link aria-hidden className="size-6 text-muted-foreground/60" />
436 <p className="text-sm font-medium">No linked pull requests</p>
437 <p className="max-w-60 text-xs text-muted-foreground">
438 Pull requests the agent opens from this thread land here. Link one yourself from a URL or
439 a number.
440 </p>
441 <Button size="sm" variant="outline" onClick={openLinkDialog}>
442 <PlusIcon className="size-3.5" />
443 Link pull request
444 </Button>
445 </div>
446 );
447 }
448​
449 return (
450 <PullRequestSpeedModeContext value={speedMode}>
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 !== undefined
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 canStartWatch={canStartWatch}
473 />
474 )}
475 estimatedItemSize={44}
476 drawDistance={440}
477 className="min-h-0 flex-1 overscroll-contain p-1.5"
478 />
479 <footer className="flex items-center justify-between border-t border-border/60 px-2 py-1.5 text-2xs text-muted-foreground">
480 <span>
481 {openCount} open · {linkCount} linked
482 {lastSynced ? (
483 <>
484 {" · synced "}
485 <RelativeTime timestamp={lastSynced} />
486 </>
487 ) : null}
488 </span>
489 <Button size="xs" variant="ghost" onClick={openLinkDialog}>
490 <PlusIcon className="size-3.5" />
491 Link
492 </Button>
493 </footer>
494 </div>
495 </PullRequestSpeedModeContext>
496 );