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

ThreadPullRequestsPanel.tsx

492 lines18.2 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 {
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 } from "@t3tools/client-runtime/change-request-links";
29import { useOpenPrLink } from "~/lib/openPullRequestLink";
30import { cn } from "~/lib/utils";
31import { useShortcutModifierState } from "~/shortcutModifierState";
32import { useProjects, useServerConfigs, useThreadShell } from "~/state/entities";
33import { PullRequestChangeBreakdownStat } from "./PullRequestChangeBreakdownStat";
34import { PullRequestsUnavailableState } from "./PullRequestsUnavailableState";
35import { threadEnvironment } from "~/state/threads";
36import { useAtomCommand } from "~/state/use-atom-command";
37import { RelativeTime } from "~/components/RelativeTime";
38import { Button } from "../ui/button";
39import { Menu, MenuItem, MenuPopup, MenuTrigger } from "../ui/menu";
40import { MiddleTruncate } from "../ui/middle-truncate";
41import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";
42import { openLinkPullRequestDialog } from "./LinkPullRequestDialog";
43import {
44 PULL_REQUEST_ROW_CLASS,
45 PULL_REQUEST_ROW_NUMBER_CLASS,
46 PullRequestRowAuthor,
47 PullRequestRowBranches,
48 PullRequestRowGlyph,
49 PullRequestRowLines,
50} from "./PullRequestListRow";
51import {
52 PullRequestDiffStat,
53 PullRequestReviewDecisionGlyph,
54 pullRequestChecksStatePresentation,
55} from "./pullRequestPresentation";
56import { PullRequestGlyph } from "./pullRequestIcons";
57import { pullRequestQuickActions } from "./pullRequestList.logic";
58import { PullRequestSpeedActions, PullRequestSpeedModeContext } from "./PullRequestSpeedActions";
59​
60const SOURCE_LABELS: Record<ThreadPullRequestLink["source"], string> = {
61 manual: "Linked by you",
62 created: "Created from this thread",
63 agent: "Linked by the agent",
64 stack: "Found in the stack",
65 "stack-dismissed": "Dismissed",
66};
67​
68function ChecksGlyph({
69 state,
70}: {
71 state: NonNullable<ThreadPullRequestLink["snapshot"]>["checksState"] & string;
72}) {
73 const presentation = pullRequestChecksStatePresentation(state);
74 return (
75 <Tooltip>
76 <TooltipTrigger render={<span className="inline-flex shrink-0" />}>
77 <presentation.Icon
78 role="img"
79 aria-label={presentation.label}
80 className={cn("size-3.5", presentation.toneClassName)}
81 />
82 </TooltipTrigger>
83 <TooltipPopup>{presentation.label}</TooltipPopup>
84 </Tooltip>
85 );
87​
88function LinkRowImpl({
89 line,
90 threadRef,
91 projectId,
92 speedMode,
93 onUnlink,
94 onSetWatching,
95}: {
96 line: PullRequestListLine;
97 threadRef: ScopedThreadRef;
98 projectId: ProjectId | null;
99 speedMode: boolean;
100 onUnlink: (link: ThreadPullRequestLink) => void;
101 onSetWatching: ((link: ThreadPullRequestLink, watching: boolean) => void) | null;
102}) {
103 const openPrLink = useOpenPrLink(threadRef);
104 const [menuOpen, setMenuOpen] = useState(false);
105 const [menuPosition, setMenuPosition] = useState<{ x: number; y: number } | null>(null);
106 const menuAnchor = menuPosition
107 ? { getBoundingClientRect: () => new DOMRect(menuPosition.x, menuPosition.y, 0, 0) }
108 : undefined;
109 const { link, depth, stack } = line;
110 const snapshot = link.snapshot;
111 const open = snapshot === null || snapshot.state === "open";
112 const watching = link.watch !== undefined;
113 const linkHost =
114 sourceControlClients.findByChangeRequestUrl(link.url) ?? UNKNOWN_SOURCE_CONTROL_CLIENT;
115 const linkHostActions = linkHost.changeRequestActions;
116 const actionEntry =
117 projectId !== null && snapshot !== null && snapshot.state !== "merged"
118 ? {
119 environmentId: threadRef.environmentId,
120 projectId,
121 host: link.host,
122 repository: link.repository,
123 number: link.number,
124 state: snapshot.state,
125 isDraft: snapshot.isDraft,
126 ...(link.stack === null ? {} : { stack: link.stack }),
127 }
128 : null;
129 const hasQuickActions =
130 actionEntry !== null && pullRequestQuickActions(actionEntry, linkHostActions).length > 0;
131 return (
132 <div
133 className={cn(PULL_REQUEST_ROW_CLASS, "relative hover:bg-accent/60")}
134 onContextMenu={(event) => {
135 event.preventDefault();
136 event.stopPropagation();
137 setMenuPosition({ x: event.clientX, y: event.clientY });
138 setMenuOpen(true);
139 }}
140 style={{ paddingLeft: `${0.5 + Math.min(depth, 3) * 1.25}rem` }}
141 >
142 {depth > 0 ? <span aria-hidden className="-ml-2 h-6 w-px shrink-0 bg-border/70" /> : null}
143 {snapshot === null ? (
144 <PullRequestGlyph.pullRequest
145 aria-label="Waiting for host state"
146 className="size-4 shrink-0 text-muted-foreground"
147 />
148 ) : (
149 <PullRequestRowGlyph
150 state={snapshot.state}
151 isDraft={snapshot.isDraft}
152 mergeability={snapshot.mergeability}
153 baseBranch={snapshot.baseBranch}
154 />
155 )}
156 <a
157 href={link.url}
158 onClick={(event) => openPrLink(event, link.url, threadRef)}
159 // Outside drops use the URL; the composer uses this context-chip payload.
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} ${linkHost.changeRequest.plural} 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 terminology={linkHost.changeRequest}
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 controls would intercept link taps on touch screens.
292 "pointer-events-none opacity-0 group-hover/pr-row:pointer-events-auto group-hover/pr-row:opacity-100",
293 "has-[[data-popup-open]]:pointer-events-auto has-[[data-popup-open]]:opacity-100",
294 "has-[:focus-visible]:pointer-events-auto has-[:focus-visible]:opacity-100",
295 "group-has-[[data-pull-request-action-pending=true]]/pr-row:hidden",
296 speedMode && hasQuickActions && "hidden",
297 )}
298 >
299 <span aria-hidden className="absolute inset-0 bg-accent/60" />
300 <Menu
301 open={menuOpen}
302 onOpenChange={(open) => {
303 setMenuOpen(open);
304 if (!open) setMenuPosition(null);
305 }}
306 >
307 <MenuTrigger
308 render={
309 <Button
310 variant="ghost"
311 size="icon-micro"
312 aria-label={`Actions for #${link.number}`}
313 className="relative"
314 >
315 <MoreHorizontalIcon className="size-3.5" />
316 </Button>
317 }
318 />
319 <MenuPopup
320 anchor={menuAnchor}
321 align={menuPosition ? "start" : "end"}
322 side="bottom"
323 sideOffset={menuPosition ? 0 : 4}
324 >
325 <MenuItem onClick={() => void writeTextToClipboard(link.url, "link")}>
326 <LinkIcon className="size-3.5" />
327 Copy link
328 </MenuItem>
329 <MenuItem onClick={(event) => openPrLink(event, link.url, threadRef)}>
330 <ArrowUpRightIcon className="size-3.5" />
331 Open
332 </MenuItem>
333 {onSetWatching !== null && open ? (
334 <MenuItem onClick={() => onSetWatching(link, !watching)}>
335 {watching ? <EyeOffIcon className="size-3.5" /> : <EyeIcon className="size-3.5" />}
336 {watching ? "Stop watching" : "Watch for changes"}
337 </MenuItem>
338 ) : null}
339 <MenuItem onClick={() => onUnlink(link)}>
340 <PullRequestGlyph.unlink className="size-3.5" />
341 {link.source === "stack" ? "Dismiss from thread" : "Unlink from thread"}
342 </MenuItem>
343 </MenuPopup>
344 </Menu>
345 </span>
346 </div>
347 );
349​
350const LinkRow = memo(LinkRowImpl);
351​
352function latestSyncedAt(links: ReadonlyArray<ThreadPullRequestLink>): string | null {
353 let latest: string | null = null;
354 for (const link of links) {
355 const at = link.snapshot?.syncedAt;
356 if (at !== undefined && (latest === null || at > latest)) latest = at;
357 }
358 return latest;
360​
361const lineKey = (line: PullRequestListLine) =>
362 `${line.link.host}/${line.link.repository}#${line.link.number}`;
363​
364export function ThreadPullRequestsPanel({ threadRef }: { threadRef: ScopedThreadRef }) {
365 const configs = useServerConfigs();
366 if (configs.get(threadRef.environmentId) === undefined) {
367 return (
368 <PullRequestsUnavailableState
369 title="Linked pull requests unavailable"
370 error="This environment does not support multiple linked pull requests."
371 />
372 );
373 }
374 return <EnabledThreadPullRequestsPanel threadRef={threadRef} />;
376​
377function EnabledThreadPullRequestsPanel({ threadRef }: { threadRef: ScopedThreadRef }) {
378 const thread = useThreadShell(threadRef);
379 const projects = useProjects();
380 const environmentProjects = projects
381 .filter((project) => project.environmentId === threadRef.environmentId)
382 .toSorted((left, right) =>
383 left.id === thread?.projectId ? -1 : right.id === thread?.projectId ? 1 : 0,
384 );
385 // Derive lines before later hooks to preserve compiler caching and avoid LegendList renders.
386 const links = visibleThreadPullRequests(thread?.pullRequests ?? []);
387 const lines = pullRequestListLines(resolveThreadPullRequestChains(links));
388 const openCount = links.filter(
389 (link) => link.snapshot === null || link.snapshot.state === "open",
390 ).length;
391 const lastSynced = latestSyncedAt(links);
392 const linkCount = links.length;
393 const modifiers = useShortcutModifierState(true);
394 const speedMode =
395 modifiers.shiftKey && !modifiers.metaKey && !modifiers.ctrlKey && !modifiers.altKey;
396 const openLinkDialog = () => openLinkPullRequestDialog(threadRef);
397 const unlink = useAtomCommand(threadEnvironment.unlinkPullRequest, { reportFailure: true });
398 const watch = useAtomCommand(threadEnvironment.watchPullRequest, { reportFailure: true });
399 const capabilities = useServerConfigs().get(threadRef.environmentId)?.environment.capabilities;
400 const supportsWatch = capabilities?.threadPullRequestWatch === true;
401 const handleUnlink = (link: ThreadPullRequestLink) => {
402 void unlink({
403 environmentId: threadRef.environmentId,
404 input: {
405 threadId: threadRef.threadId,
406 host: link.host,
407 repository: link.repository,
408 number: link.number,
409 },
410 });
411 };
412 const handleSetWatching = (link: ThreadPullRequestLink, watching: boolean) => {
413 void watch({
414 environmentId: threadRef.environmentId,
415 input: {
416 threadId: threadRef.threadId,
417 host: link.host,
418 repository: link.repository,
419 number: link.number,
420 watching,
421 },
422 });
423 };
424​
425 // Legend rows update only for data/extraData changes; include all external inputs.
426 const rowInputs = { speedMode, environmentProjects, capabilities, supportsWatch, thread };
427​
428 if (linkCount === 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 <PullRequestSpeedModeContext value={speedMode}>
447 <div className="flex h-full min-h-0 flex-col">
448 {/* Threads that run a stack or a sweep link hundreds of pull requests; only the rows in
449 view are mounted. */}
450 <LegendList<PullRequestListLine>
451 data={lines}
452 keyExtractor={lineKey}
453 extraData={rowInputs}
454 renderItem={({ item: line }) => (
455 <LinkRow
456 line={line}
457 threadRef={threadRef}
458 projectId={
459 capabilities !== undefined
460 ? (findProjectForChangeRequest(environmentProjects, line.link)?.id ??
461 thread?.projectId ??
462 null)
463 : null
464 }
465 speedMode={speedMode}
466 onUnlink={handleUnlink}
467 onSetWatching={supportsWatch ? handleSetWatching : null}
468 />
469 )}
470 estimatedItemSize={44}
471 drawDistance={440}
472 className="min-h-0 flex-1 overscroll-contain p-1.5"
473 />
474 <footer className="flex items-center justify-between border-t border-border/60 px-2 py-1.5 text-2xs text-muted-foreground">
475 <span>
476 {openCount} open · {linkCount} linked
477 {lastSynced ? (
478 <>
479 {" · synced "}
480 <RelativeTime timestamp={lastSynced} />
481 </>
482 ) : null}
483 </span>
484 <Button size="xs" variant="ghost" onClick={openLinkDialog}>
485 <PlusIcon className="size-3.5" />
486 Link
487 </Button>
488 </footer>
489 </div>
490 </PullRequestSpeedModeContext>
491 );