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 type PullRequestListLine,
8 pullRequestListLines,
9 resolveThreadPullRequestChains,
10 visibleThreadPullRequests,
11} from "@t3tools/client-runtime/thread-pull-requests";
12import { canStartThreadPullRequestWatch } from "@t3tools/client-runtime/thread-pull-request-compatibility";
13import {
14 ArrowUpRightIcon,
15 EyeIcon,
16 EyeOffIcon,
17 LinkIcon,
18 MoreHorizontalIcon,
19 PlusIcon,
20} from "lucide-react";
21import { LegendList } from "@legendapp/list/react";
22import { msg, T, useGT, useMessages, Var } from "gt-react";
23import { memo, useState } from "react";
24
25import {
26 COMPOSER_PULL_REQUEST_DRAG_TYPE,
27 encodePullRequestDragPayload,
28} from "~/components/chat/composerMentionDrag";
29import { writeTextToClipboard } from "~/hooks/useCopyToClipboard";
30import { findProjectForChangeRequest } from "@t3tools/client-runtime/change-request-links";
31import { pullRequestLinkPanelTarget, useOpenPrLink } from "~/lib/openPullRequestLink";
32import { useClientSettings } from "~/hooks/useSettings";
33import { usePrimaryEnvironmentId } from "~/state/environments";
34import { usePullRequestIntentPrefetch } from "./usePullRequestIntentPrefetch";
35import { cn } from "~/lib/utils";
36import { useShortcutModifierState } from "~/shortcutModifierState";
37import { useProjects, useServerConfigs, useThreadShell } from "~/state/entities";
38import { PullRequestChangeBreakdownStat } from "./PullRequestChangeBreakdownStat";
39import { PullRequestsUnavailableState } from "./PullRequestsUnavailableState";
40import { threadEnvironment } from "~/state/threads";
41import { useAtomCommand } from "~/state/use-atom-command";
42import { RelativeTime } from "~/components/RelativeTime";
43import { Button } from "../ui/button";
44import { Menu, MenuItem, MenuPopup, MenuTrigger } from "../ui/menu";
45import { MiddleTruncate } from "../ui/middle-truncate";
46import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";
47import { openLinkPullRequestDialog } from "./LinkPullRequestDialog";
48import {
49 PULL_REQUEST_ROW_CLASS,
50 PULL_REQUEST_ROW_NUMBER_CLASS,
51 PullRequestRowAuthor,
52 PullRequestRowBranches,
53 PullRequestRowGlyph,
54 PullRequestRowLines,
55} from "./PullRequestListRow";
56import {
57 PullRequestDiffStat,
58 PullRequestReviewDecisionGlyph,
59 pullRequestChecksStatePresentation,
60} from "./pullRequestPresentation";
61import { PullRequestGlyph } from "./pullRequestIcons";
62import { pullRequestQuickActions } from "./pullRequestList.logic";
63import { PullRequestSpeedActions, PullRequestSpeedModeContext } from "./PullRequestSpeedActions";
64
65import { changeRequestTermKind } from "./changeRequestTerm";
66
67const SOURCE_LABELS: Record<ThreadPullRequestLink["source"], string> = {
68 manual: msg("Linked by you"),
69 created: msg("Created from this thread"),
70 agent: msg("Linked by the agent"),
71 stack: msg("Found in the stack"),
72 "stack-dismissed": msg("Dismissed", { $context: "pull request link source" }),
73};
74
75function ChecksGlyph({
76 state,
77}: {
78 state: NonNullable<ThreadPullRequestLink["snapshot"]>["checksState"] & string;
79}) {
80 const resolve = useMessages();
81 const presentation = pullRequestChecksStatePresentation(state, resolve);
82 return (
83 <Tooltip>
84 <TooltipTrigger render={<span className="inline-flex shrink-0" />}>
85 <presentation.Icon
86 role="img"
87 aria-label={presentation.label}
88 className={cn("size-3.5", presentation.toneClassName)}
89 />
90 </TooltipTrigger>
91 <TooltipPopup>{presentation.label}</TooltipPopup>
92 </Tooltip>
93 );
94}
95
96function LinkRowImpl({
97 line,
98 threadRef,
99 projectId,
100 speedMode,
101 onUnlink,
102 onSetWatching,
103 onIntent,
104 canStartWatch,
105}: {
106 line: PullRequestListLine;
107 threadRef: ScopedThreadRef;
108 projectId: ProjectId | null;
109 speedMode: boolean;
110 onUnlink: (link: ThreadPullRequestLink) => void;
111 onSetWatching: ((link: ThreadPullRequestLink, watching: boolean) => void) | null;
112 onIntent: (link: ThreadPullRequestLink | null) => void;
113 canStartWatch: boolean;
114}) {
115 const gt = useGT();
116 const resolve = useMessages();
117 const openPrLink = useOpenPrLink(threadRef);
118 const [menuOpen, setMenuOpen] = useState(false);
119 const [menuPosition, setMenuPosition] = useState<{ x: number; y: number } | null>(null);
120 const menuAnchor = menuPosition
121 ? { getBoundingClientRect: () => new DOMRect(menuPosition.x, menuPosition.y, 0, 0) }
122 : undefined;
123 const { link, depth, stack } = line;
124 const snapshot = link.snapshot;
125 const open = snapshot === null || snapshot.state === "open";
126 const watching = link.watch !== undefined;
127 const linkHost =
128 sourceControlClients.findByChangeRequestUrl(link.url) ?? UNKNOWN_SOURCE_CONTROL_CLIENT;
129 const linkHostActions = linkHost.changeRequestActions;
130 const actionEntry =
131 projectId !== null && snapshot !== null && snapshot.state !== "merged"
132 ? {
133 environmentId: threadRef.environmentId,
134 projectId,
135 host: link.host,
136 repository: link.repository,
137 number: link.number,
138 state: snapshot.state,
139 isDraft: snapshot.isDraft,
140 ...(link.stack === null ? {} : { stack: link.stack }),
141 }
142 : null;
143 const hasQuickActions =
144 actionEntry !== null && pullRequestQuickActions(actionEntry, linkHostActions).length > 0;
145 return (
146 <div
147 className={cn(PULL_REQUEST_ROW_CLASS, "relative hover:bg-accent/60")}
148 onPointerEnter={() => onIntent(link)}
149 onPointerLeave={(event) => {
150 if (!event.currentTarget.contains(document.activeElement)) onIntent(null);
151 }}
152 onFocus={() => onIntent(link)}
153 onBlur={(event) => {
154 if (!event.currentTarget.matches(":hover")) onIntent(null);
155 }}
156 onContextMenu={(event) => {
157 event.preventDefault();
158 event.stopPropagation();
159 setMenuPosition({ x: event.clientX, y: event.clientY });
160 setMenuOpen(true);
161 }}
162 style={{ paddingLeft: `${0.5 + Math.min(depth, 3) * 1.25}rem` }}
163 >
164 {depth > 0 ? <span aria-hidden className="-ml-2 h-6 w-px shrink-0 bg-border/70" /> : null}
165 {snapshot === null ? (
166 <PullRequestGlyph.pullRequest
167 aria-label={gt("Waiting for host state")}
168 className="size-4 shrink-0 text-muted-foreground"
169 />
170 ) : (
171 <PullRequestRowGlyph
172 state={snapshot.state}
173 isDraft={snapshot.isDraft}
174 mergeability={snapshot.mergeability}
175 baseBranch={snapshot.baseBranch}
176 />
177 )}
178 <a
179 href={link.url}
180 onClick={(event) => openPrLink(event, link.url, threadRef)}
181 // Outside drops use the URL; the composer uses this context-chip payload.
182 onDragStart={
183 snapshot === null
184 ? undefined
185 : (event) =>
186 event.dataTransfer.setData(
187 COMPOSER_PULL_REQUEST_DRAG_TYPE,
188 encodePullRequestDragPayload({
189 number: link.number,
190 title: snapshot.title,
191 url: link.url,
192 headBranch: snapshot.headBranch,
193 baseBranch: snapshot.baseBranch,
194 state: snapshot.state,
195 isDraft: snapshot.isDraft,
196 }),
197 )
198 }
199 className="flex min-w-0 flex-1"
200 >
201 <PullRequestRowLines
202 number={
203 <Tooltip>
204 <TooltipTrigger render={<span className={PULL_REQUEST_ROW_NUMBER_CLASS} />}>
205 #{link.number}
206 </TooltipTrigger>
207 <TooltipPopup>
208 {resolve(SOURCE_LABELS[link.source])} · <RelativeTime timestamp={link.linkedAt} />
209 </TooltipPopup>
210 </Tooltip>
211 }
212 title={snapshot?.title ?? link.repository}
213 signals={
214 open ? (
215 <>
216 {watching ? (
217 <Tooltip>
218 <TooltipTrigger render={<span className="inline-flex shrink-0" />}>
219 <EyeIcon role="img" aria-label={gt("Watching")} className="size-3.5" />
220 </TooltipTrigger>
221 <TooltipPopup>
222 <T>
223 Watching: the agent wakes when checks finish, someone comments, or the
224 branch conflicts
225 </T>
226 </TooltipPopup>
227 </Tooltip>
228 ) : null}
229 {snapshot?.checksState ? <ChecksGlyph state={snapshot.checksState} /> : null}
230 {snapshot?.reviewDecision ? (
231 <PullRequestReviewDecisionGlyph decision={snapshot.reviewDecision} />
232 ) : null}
233 </>
234 ) : null
235 }
236 status={
237 projectId === null ? (
238 <PullRequestDiffStat
239 additions={snapshot?.additions ?? 0}
240 deletions={snapshot?.deletions ?? 0}
241 className="font-mono"
242 />
243 ) : (
244 <PullRequestChangeBreakdownStat
245 environmentId={threadRef.environmentId}
246 reference={{
247 projectId,
248 host: link.host,
249 repository: link.repository,
250 number: link.number,
251 }}
252 additions={snapshot?.additions ?? 0}
253 deletions={snapshot?.deletions ?? 0}
254 className="font-mono"
255 />
256 )
257 }
258 meta={
259 <>
260 {stack ? (
261 <Tooltip>
262 <TooltipTrigger
263 render={
264 <span className="inline-flex shrink-0 items-center gap-0.5 text-foreground/70" />
265 }
266 >
267 <PullRequestGlyph.stack aria-hidden className="size-3" />
268 {stack.size}
269 </TooltipTrigger>
270 <TooltipPopup>
271 {stack.kind === "native"
272 ? gt("{host} stack of {size}: merging a layer lands the ones below it.", {
273 host: sourceControlClients.hostLabelForChangeRequestUrl(link.url),
274 size: stack.size,
275 })
276 : gt(
277 "{size} {terms, select, mr {merge requests} cr {change requests} other {pull requests}} chained by base branch.",
278 {
279 size: stack.size,
280 terms: changeRequestTermKind(linkHost.changeRequest),
281 },
282 )}
283 </TooltipPopup>
284 </Tooltip>
285 ) : null}
286 {snapshot?.author ? (
287 <PullRequestRowAuthor
288 actor={snapshot.author}
289 className="shrink-0"
290 labelClassName="max-w-28"
291 />
292 ) : null}
293 {snapshot !== null ? (
294 <>
295 <Tooltip>
296 <TooltipTrigger render={<span className="flex min-w-0 max-w-32 font-mono" />}>
297 <MiddleTruncate value={link.repository} showTitle={false} />
298 </TooltipTrigger>
299 <TooltipPopup>{link.repository}</TooltipPopup>
300 </Tooltip>
301 <PullRequestRowBranches head={snapshot.headBranch} base={snapshot.baseBranch} />
302 </>
303 ) : (
304 <span className="truncate font-mono">
305 {link.host}/{link.repository}
306 </span>
307 )}
308 </>
309 }
310 updatedAt={snapshot?.updatedAt}
311 />
312 </a>
313 {actionEntry !== null ? (
314 <PullRequestSpeedActions
315 entry={actionEntry}
316 hostActions={linkHostActions}
317 terminology={linkHost.changeRequest}
318 />
319 ) : null}
320 <span
321 className={cn(
322 "absolute right-0 bottom-0.5 flex items-center rounded-r-md bg-background pr-1 pl-5",
323 "[mask-image:linear-gradient(to_right,transparent,black_1rem)]",
324 // Hidden controls would intercept link taps on touch screens.
325 "pointer-events-none opacity-0 group-hover/pr-row:pointer-events-auto group-hover/pr-row:opacity-100",
326 "has-[[data-popup-open]]:pointer-events-auto has-[[data-popup-open]]:opacity-100",
327 "has-[:focus-visible]:pointer-events-auto has-[:focus-visible]:opacity-100",
328 "group-has-[[data-pull-request-action-pending=true]]/pr-row:hidden",
329 speedMode && hasQuickActions && "hidden",
330 )}
331 >
332 <span aria-hidden className="absolute inset-0 bg-accent/60" />
333 <Menu
334 open={menuOpen}
335 onOpenChange={(open) => {
336 setMenuOpen(open);
337 if (!open) setMenuPosition(null);
338 }}
339 >
340 <MenuTrigger
341 render={
342 <Button
343 variant="ghost"
344 size="icon-micro"
345 aria-label={gt("Actions for #{number}", { number: link.number })}
346 className="relative"
347 >
348 <MoreHorizontalIcon className="size-3.5" />
349 </Button>
350 }
351 />
352 <MenuPopup
353 anchor={menuAnchor}
354 align={menuPosition ? "start" : "end"}
355 side="bottom"
356 sideOffset={menuPosition ? 0 : 4}
357 >
358 <MenuItem
359 onClick={() =>
360 void writeTextToClipboard(link.url, {
361 target: "link",
362 unavailableMessage: msg("Clipboard API is unavailable while copying link."),
363 failureMessage: msg("Failed to copy link to the clipboard."),
364 })
365 }
366 >
367 <LinkIcon className="size-3.5" />
368 <T>Copy link</T>
369 </MenuItem>
370 <MenuItem onClick={(event) => openPrLink(event, link.url, threadRef)}>
371 <ArrowUpRightIcon className="size-3.5" />
372 <T context="verb, open a link">Open</T>
373 </MenuItem>
374 {onSetWatching !== null && open && (watching || canStartWatch) ? (
375 <MenuItem onClick={() => onSetWatching(link, !watching)}>
376 {watching ? <EyeOffIcon className="size-3.5" /> : <EyeIcon className="size-3.5" />}
377 {watching ? gt("Stop watching") : gt("Watch for changes")}
378 </MenuItem>
379 ) : null}
380 <MenuItem onClick={() => onUnlink(link)}>
381 <PullRequestGlyph.unlink className="size-3.5" />
382 {link.source === "stack" ? gt("Dismiss from thread") : gt("Unlink from thread")}
383 </MenuItem>
384 </MenuPopup>
385 </Menu>
386 </span>
387 </div>
388 );
389}
390
391const LinkRow = memo(LinkRowImpl);
392
393function latestSyncedAt(links: ReadonlyArray<ThreadPullRequestLink>): string | null {
394 let latest: string | null = null;
395 for (const link of links) {
396 const at = link.snapshot?.syncedAt;
397 if (at !== undefined && (latest === null || at > latest)) latest = at;
398 }
399 return latest;
400}
401
402const lineKey = (line: PullRequestListLine) =>
403 `${line.link.host}/${line.link.repository}#${line.link.number}`;
404
405export function ThreadPullRequestsPanel({ threadRef }: { threadRef: ScopedThreadRef }) {
406 const gt = useGT();
407 const configs = useServerConfigs();
408 if (configs.get(threadRef.environmentId) === undefined) {
409 return (
410 <PullRequestsUnavailableState
411 title={gt("Linked pull requests unavailable")}
412 error={gt("This environment does not support multiple linked pull requests.")}
413 />
414 );
415 }
416 return <EnabledThreadPullRequestsPanel threadRef={threadRef} />;
417}
418
419function EnabledThreadPullRequestsPanel({ threadRef }: { threadRef: ScopedThreadRef }) {
420 const gt = useGT();
421 const thread = useThreadShell(threadRef);
422 const projects = useProjects();
423 const environmentProjects = projects
424 .filter((project) => project.environmentId === threadRef.environmentId)
425 .toSorted((left, right) =>
426 left.id === thread?.projectId ? -1 : right.id === thread?.projectId ? 1 : 0,
427 );
428 // Derive lines before later hooks to preserve compiler caching and avoid LegendList renders.
429 const links = visibleThreadPullRequests(thread?.pullRequests ?? []);
430 const lines = pullRequestListLines(resolveThreadPullRequestChains(links));
431 const openCount = links.filter(
432 (link) => link.snapshot === null || link.snapshot.state === "open",
433 ).length;
434 const lastSynced = latestSyncedAt(links);
435 const linkCount = links.length;
436 const modifiers = useShortcutModifierState(true);
437 const speedMode =
438 modifiers.shiftKey && !modifiers.metaKey && !modifiers.ctrlKey && !modifiers.altKey;
439 const openLinkDialog = () => openLinkPullRequestDialog(threadRef);
440 const unlink = useAtomCommand(threadEnvironment.unlinkPullRequest, { reportFailure: true });
441 const watch = useAtomCommand(threadEnvironment.watchPullRequest, { reportFailure: true });
442 const capabilities = useServerConfigs().get(threadRef.environmentId)?.environment.capabilities;
443 const primaryEnvironmentId = usePrimaryEnvironmentId();
444 const opensInApp = useClientSettings((settings) => settings.pullRequestLinksOpenInApp);
445 const prefetch = usePullRequestIntentPrefetch((target) =>
446 links.some(
447 (link) =>
448 link.number === target.number &&
449 link.repository.toLowerCase() === target.repository.toLowerCase(),
450 ),
451 );
452 const intendLink = (link: ThreadPullRequestLink | null) => {
453 const target =
454 link === null || !opensInApp
455 ? null
456 : pullRequestLinkPanelTarget({
457 url: link.url,
458 environmentId: threadRef.environmentId,
459 primaryEnvironmentId,
460 lendHostProject: true,
461 });
462 prefetch(
463 target?.host === undefined
464 ? null
465 : {
466 environmentId: target.project.environmentId,
467 projectId: target.project.id,
468 host: target.host,
469 repository: target.repository,
470 number: target.number,
471 },
472 );
473 };
474 const supportsWatch = capabilities?.threadPullRequestWatch === true;
475 const canStartWatch = thread !== null && canStartThreadPullRequestWatch(thread);
476 const handleUnlink = (link: ThreadPullRequestLink) => {
477 void unlink({
478 environmentId: threadRef.environmentId,
479 input: {
480 threadId: threadRef.threadId,
481 host: link.host,
482 repository: link.repository,
483 number: link.number,
484 },
485 });
486 };
487 const handleSetWatching = (link: ThreadPullRequestLink, watching: boolean) => {
488 void watch({
489 environmentId: threadRef.environmentId,
490 input: {
491 threadId: threadRef.threadId,
492 host: link.host,
493 repository: link.repository,
494 number: link.number,
495 watching,
496 },
497 });
498 };
499
500 // Legend rows update only for data/extraData changes; include all external inputs.
501 const rowInputs = {
502 speedMode,
503 environmentProjects,
504 capabilities,
505 supportsWatch,
506 thread,
507 opensInApp,
508 primaryEnvironmentId,
509 };
510
511 if (linkCount === 0) {
512 return (
513 <div className="flex h-full flex-col items-center justify-center gap-2 p-6 text-center">
514 <PullRequestGlyph.link aria-hidden className="size-6 text-muted-foreground/60" />
515 <p className="text-sm font-medium">
516 <T>No linked pull requests</T>
517 </p>
518 <p className="max-w-60 text-xs text-muted-foreground">
519 <T>
520 Pull requests the agent opens from this thread land here. Link one yourself from a URL
521 or a number.
522 </T>
523 </p>
524 <Button size="sm" variant="outline" onClick={openLinkDialog}>
525 <PlusIcon className="size-3.5" />
526 <T>Link pull request</T>
527 </Button>
528 </div>
529 );
530 }
531
532 return (
533 <PullRequestSpeedModeContext value={speedMode}>
534 <div className="flex h-full min-h-0 flex-col">
535 {/* Threads that run a stack or a sweep link hundreds of pull requests; only the rows in
536 view are mounted. */}
537 <LegendList<PullRequestListLine>
538 data={lines}
539 keyExtractor={lineKey}
540 extraData={rowInputs}
541 renderItem={({ item: line }) => (
542 <LinkRow
543 line={line}
544 threadRef={threadRef}
545 projectId={
546 capabilities !== undefined
547 ? (findProjectForChangeRequest(environmentProjects, line.link)?.id ??
548 thread?.projectId ??
549 null)
550 : null
551 }
552 speedMode={speedMode}
553 onUnlink={handleUnlink}
554 onSetWatching={supportsWatch ? handleSetWatching : null}
555 onIntent={intendLink}
556 canStartWatch={canStartWatch}
557 />
558 )}
559 estimatedItemSize={44}
560 drawDistance={440}
561 className="min-h-0 flex-1 overscroll-contain p-1.5"
562 />
563 <footer className="flex items-center justify-between border-t border-border/60 px-2 py-1.5 text-2xs text-muted-foreground">
564 <span>
565 {gt(
566 "{openCount, plural, one {{openCount} open} other {{openCount} open}} · {linkCount, plural, one {{linkCount} linked} other {{linkCount} linked}}",
567 { openCount, linkCount },
568 )}
569 {lastSynced ? (
570 <>
571 {" · "}
572 <T context="followed by a relative time such as 5m ago or just now">
573 synced{" "}
574 <Var>
575 <RelativeTime timestamp={lastSynced} />
576 </Var>
577 </T>
578 </>
579 ) : null}
580 </span>
581 <Button size="xs" variant="ghost" onClick={openLinkDialog}>
582 <PlusIcon className="size-3.5" />
583 <T context="verb, button">Link</T>
584 </Button>
585 </footer>
586 </div>
587 </PullRequestSpeedModeContext>
588 );
589}