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