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

ThreadPullRequestsPanel.tsx

446 lines16.9 KB

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