The best way to control Claude Code, Codex and more from any computer or phone

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