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