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

ThreadPullRequestsPanel.tsx

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