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

ThreadPullRequestsPanel.tsx

498 lines18.7 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 // The link's own URL still rides along for drops outside the app; the composer takes
160 // this payload instead and adds the pull request as a context chip.
161 onDragStart={
162 snapshot === null
163 ? undefined
164 : (event) =>
165 event.dataTransfer.setData(
166 COMPOSER_PULL_REQUEST_DRAG_TYPE,
167 encodePullRequestDragPayload({
168 number: link.number,
169 title: snapshot.title,
170 url: link.url,
171 headBranch: snapshot.headBranch,
172 baseBranch: snapshot.baseBranch,
173 state: snapshot.state,
174 isDraft: snapshot.isDraft,
175 }),
176 )
177 }
178 className="flex min-w-0 flex-1"
179 >
180 <PullRequestRowLines
181 number={
182 <Tooltip>
183 <TooltipTrigger render={<span className={PULL_REQUEST_ROW_NUMBER_CLASS} />}>
184 #{link.number}
185 </TooltipTrigger>
186 <TooltipPopup>
187 {SOURCE_LABELS[link.source]} · <RelativeTime timestamp={link.linkedAt} />
188 </TooltipPopup>
189 </Tooltip>
190 }
191 title={snapshot?.title ?? link.repository}
192 signals={
193 open ? (
194 <>
195 {watching ? (
196 <Tooltip>
197 <TooltipTrigger render={<span className="inline-flex shrink-0" />}>
198 <EyeIcon role="img" aria-label="Watching" className="size-3.5" />
199 </TooltipTrigger>
200 <TooltipPopup>
201 Watching: the agent wakes when checks finish, someone comments, or the branch
202 conflicts
203 </TooltipPopup>
204 </Tooltip>
205 ) : null}
206 {snapshot?.checksState ? <ChecksGlyph state={snapshot.checksState} /> : null}
207 {snapshot?.reviewDecision ? (
208 <PullRequestReviewDecisionGlyph decision={snapshot.reviewDecision} />
209 ) : null}
210 </>
211 ) : null
212 }
213 status={
214 projectId === null ? (
215 <PullRequestDiffStat
216 additions={snapshot?.additions ?? 0}
217 deletions={snapshot?.deletions ?? 0}
218 className="font-mono"
219 />
220 ) : (
221 <PullRequestChangeBreakdownStat
222 environmentId={threadRef.environmentId}
223 reference={{
224 projectId,
225 host: link.host,
226 repository: link.repository,
227 number: link.number,
228 }}
229 additions={snapshot?.additions ?? 0}
230 deletions={snapshot?.deletions ?? 0}
231 className="font-mono"
232 />
233 )
234 }
235 meta={
236 <>
237 {stack ? (
238 <Tooltip>
239 <TooltipTrigger
240 render={
241 <span className="inline-flex shrink-0 items-center gap-0.5 text-foreground/70" />
242 }
243 >
244 <PullRequestGlyph.stack aria-hidden className="size-3" />
245 {stack.size}
246 </TooltipTrigger>
247 <TooltipPopup>
248 {stack.kind === "native"
249 ? `${sourceControlClients.hostLabelForChangeRequestUrl(link.url)} stack of ${stack.size}: merging a layer lands the ones below it.`
250 : `${stack.size} ${linkHost.changeRequest.plural} chained by base branch.`}
251 </TooltipPopup>
252 </Tooltip>
253 ) : null}
254 {snapshot?.author ? (
255 <PullRequestRowAuthor
256 actor={snapshot.author}
257 className="shrink-0"
258 labelClassName="max-w-28"
259 />
260 ) : null}
261 {snapshot !== null ? (
262 <>
263 <Tooltip>
264 <TooltipTrigger render={<span className="flex min-w-0 max-w-32 font-mono" />}>
265 <MiddleTruncate value={link.repository} showTitle={false} />
266 </TooltipTrigger>
267 <TooltipPopup>{link.repository}</TooltipPopup>
268 </Tooltip>
269 <PullRequestRowBranches head={snapshot.headBranch} base={snapshot.baseBranch} />
270 </>
271 ) : (
272 <span className="truncate font-mono">
273 {link.host}/{link.repository}
274 </span>
275 )}
276 </>
277 }
278 updatedAt={snapshot?.updatedAt}
279 />
280 </a>
281 {actionEntry !== null ? (
282 <PullRequestSpeedActions
283 entry={actionEntry}
284 hostActions={linkHostActions}
285 terminology={linkHost.changeRequest}
286 />
287 ) : null}
288 <span
289 className={cn(
290 "absolute right-0 bottom-0.5 flex items-center rounded-r-md bg-background pr-1 pl-5",
291 "[mask-image:linear-gradient(to_right,transparent,black_1rem)]",
292 // Hidden means untouchable too: on a touch screen there is no hover, and an invisible
293 // layer over the right of the row would otherwise swallow the tap meant for the link.
294 "pointer-events-none opacity-0 group-hover/pr-row:pointer-events-auto group-hover/pr-row:opacity-100",
295 "has-[[data-popup-open]]:pointer-events-auto has-[[data-popup-open]]:opacity-100",
296 "has-[:focus-visible]:pointer-events-auto has-[:focus-visible]:opacity-100",
297 "group-has-[[data-pull-request-action-pending=true]]/pr-row:hidden",
298 speedMode && hasQuickActions && "hidden",
299 )}
300 >
301 <span aria-hidden className="absolute inset-0 bg-accent/60" />
302 <Menu
303 open={menuOpen}
304 onOpenChange={(open) => {
305 setMenuOpen(open);
306 if (!open) setMenuPosition(null);
307 }}
308 >
309 <MenuTrigger
310 render={
311 <Button
312 variant="ghost"
313 size="icon-micro"
314 aria-label={`Actions for #${link.number}`}
315 className="relative"
316 >
317 <MoreHorizontalIcon className="size-3.5" />
318 </Button>
319 }
320 />
321 <MenuPopup
322 anchor={menuAnchor}
323 align={menuPosition ? "start" : "end"}
324 side="bottom"
325 sideOffset={menuPosition ? 0 : 4}
326 >
327 <MenuItem onClick={() => void writeTextToClipboard(link.url, "link")}>
328 <LinkIcon className="size-3.5" />
329 Copy link
330 </MenuItem>
331 <MenuItem onClick={(event) => openPrLink(event, link.url, threadRef)}>
332 <ArrowUpRightIcon className="size-3.5" />
333 Open
334 </MenuItem>
335 {onSetWatching !== null && open ? (
336 <MenuItem onClick={() => onSetWatching(link, !watching)}>
337 {watching ? <EyeOffIcon className="size-3.5" /> : <EyeIcon className="size-3.5" />}
338 {watching ? "Stop watching" : "Watch for changes"}
339 </MenuItem>
340 ) : null}
341 <MenuItem onClick={() => onUnlink(link)}>
342 <PullRequestGlyph.unlink className="size-3.5" />
343 {link.source === "stack" ? "Dismiss from thread" : "Unlink from thread"}
344 </MenuItem>
345 </MenuPopup>
346 </Menu>
347 </span>
348 </div>
349 );
351​
352/** Memoized so a modifier key or a sync of one link re-renders only the rows that changed. */
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)?.environment.capabilities.threadPullRequests !== true) {
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 // LegendList re-renders its rows when `data` changes identity. `links` and values derived
389 // from it go through plain functions only here, before the next hook, so the compiler keeps
390 // `lines` in its own cache scope.
391 const links = visibleThreadPullRequests(thread?.pullRequests ?? []);
392 const lines = pullRequestListLines(resolveThreadPullRequestChains(links));
393 const openCount = links.filter(
394 (link) => link.snapshot === null || link.snapshot.state === "open",
395 ).length;
396 const lastSynced = latestSyncedAt(links);
397 const linkCount = links.length;
398 const modifiers = useShortcutModifierState(true);
399 const speedMode =
400 modifiers.shiftKey && !modifiers.metaKey && !modifiers.ctrlKey && !modifiers.altKey;
401 const openLinkDialog = () => openLinkPullRequestDialog(threadRef);
402 const unlink = useAtomCommand(threadEnvironment.unlinkPullRequest, { reportFailure: true });
403 const watch = useAtomCommand(threadEnvironment.watchPullRequest, { reportFailure: true });
404 const capabilities = useServerConfigs().get(threadRef.environmentId)?.environment.capabilities;
405 const supportsWatch = capabilities?.threadPullRequestWatch === true;
406 const handleUnlink = (link: ThreadPullRequestLink) => {
407 void unlink({
408 environmentId: threadRef.environmentId,
409 input: {
410 threadId: threadRef.threadId,
411 host: link.host,
412 repository: link.repository,
413 number: link.number,
414 },
415 });
416 };
417 const handleSetWatching = (link: ThreadPullRequestLink, watching: boolean) => {
418 void watch({
419 environmentId: threadRef.environmentId,
420 input: {
421 threadId: threadRef.threadId,
422 host: link.host,
423 repository: link.repository,
424 number: link.number,
425 watching,
426 },
427 });
428 };
429​
430 // Legend re-renders visible rows only when data or extraData changes, so everything the rows
431 // read from outside their line goes in here.
432 const rowInputs = { speedMode, environmentProjects, capabilities, supportsWatch, thread };
433​
434 if (linkCount === 0) {
435 return (
436 <div className="flex h-full flex-col items-center justify-center gap-2 p-6 text-center">
437 <PullRequestGlyph.link aria-hidden className="size-6 text-muted-foreground/60" />
438 <p className="text-sm font-medium">No linked pull requests</p>
439 <p className="max-w-60 text-xs text-muted-foreground">
440 Pull requests the agent opens from this thread land here. Link one yourself from a URL or
441 a number.
442 </p>
443 <Button size="sm" variant="outline" onClick={openLinkDialog}>
444 <PlusIcon className="size-3.5" />
445 Link pull request
446 </Button>
447 </div>
448 );
449 }
450​
451 return (
452 <PullRequestSpeedModeContext value={speedMode}>
453 <div className="flex h-full min-h-0 flex-col">
454 {/* Threads that run a stack or a sweep link hundreds of pull requests; only the rows in
455 view are mounted. */}
456 <LegendList<PullRequestListLine>
457 data={lines}
458 keyExtractor={lineKey}
459 extraData={rowInputs}
460 renderItem={({ item: line }) => (
461 <LinkRow
462 line={line}
463 threadRef={threadRef}
464 projectId={
465 capabilities?.pullRequests === true
466 ? (findProjectForChangeRequest(environmentProjects, line.link)?.id ??
467 thread?.projectId ??
468 null)
469 : null
470 }
471 speedMode={speedMode}
472 onUnlink={handleUnlink}
473 onSetWatching={supportsWatch ? handleSetWatching : null}
474 />
475 )}
476 estimatedItemSize={44}
477 drawDistance={440}
478 className="min-h-0 flex-1 overscroll-contain p-1.5"
479 />
480 <footer className="flex items-center justify-between border-t border-border/60 px-2 py-1.5 text-2xs text-muted-foreground">
481 <span>
482 {openCount} open · {linkCount} linked
483 {lastSynced ? (
484 <>
485 {" · synced "}
486 <RelativeTime timestamp={lastSynced} />
487 </>
488 ) : null}
489 </span>
490 <Button size="xs" variant="ghost" onClick={openLinkDialog}>
491 <PlusIcon className="size-3.5" />
492 Link
493 </Button>
494 </footer>
495 </div>
496 </PullRequestSpeedModeContext>
497 );