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