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

ThreadPullRequestsPanel.tsx

550 lines20.2 KB

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