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

ThreadPullRequestsPanel.tsx

659 lines23.4 KB

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