Open History to see the last commit
1import { changeRequestTermKind, type ChangeRequestTermKind } from "./pullRequest/changeRequestTerm";
2import {
3 scopeProjectRef,
4 scopedThreadKey,
5 scopeThreadRef,
6} from "@t3tools/client-runtime/environment";
7import { useSupportsMultiplePullRequests } from "~/hooks/useSupportsMultiplePullRequests";
8import { useStableCallback } from "~/hooks/useStableCallback";
9
10import { pullRequestDetailToVcsStatus } from "@t3tools/client-runtime/state/pull-requests";
11import type { EnvironmentThreadShell } from "@t3tools/client-runtime/state/shell";
12import {
13 resolveEnvironmentMachineKind,
14 type EnvironmentId,
15 type ProjectId,
16 type PullRequestSummary,
17 type ScopedThreadRef,
18 type ThreadLinkedPullRequest,
19 type ThreadPullRequestLink,
20 type VcsStatusResult,
21} from "@t3tools/contracts";
22import { msg, T, useGT, useMessages, Var, plural, part, select } from "gt-react";
23import { FolderGit2Icon, TerminalIcon } from "lucide-react";
24import { m, type MessageResolver } from "../i18n/messages";
25import { useEnvironment, usePrimaryEnvironmentId } from "../state/environments";
26import { EnvironmentMachineIcon } from "./EnvironmentMachineIcon";
27import { useProject } from "../state/entities";
28import {
29 isThreadPullRequestDismissed,
30 pullRequestListLines,
31 resolveThreadCurrentPullRequestLink,
32 resolveThreadPullRequestChains,
33 type ThreadPullRequestBadge,
34} from "@t3tools/client-runtime/thread-pull-requests";
35import { useRender } from "@base-ui/react/use-render";
36import {
37 type ComponentType,
38 type ReactNode,
39 type AnimationEvent,
40 type MouseEvent,
41 type ReactElement,
42} from "react";
43import { cn } from "../lib/utils";
44import { Button } from "./ui/button";
45import { revealThreadTerminal } from "../lib/revealThreadTerminal";
46
47import { useEnvironmentQuery } from "../state/query";
48import {
49 linkedPullRequestDetailAtom,
50 useLinkedThreadPullRequestSummary,
51 useSharedPullRequestSummary,
52 useSharedThreadPullRequestBadge,
53} from "../state/pullRequests";
54import { useThreadRunningTerminalIds } from "../state/terminalSessions";
55import { vcsEnvironment } from "../state/vcs";
56import { useUiStateStore } from "../uiStateStore";
57import { sourceControlClients } from "@t3tools/client-runtime/source-control-clients";
58import {
59 pullRequestMatchesSearchQuery,
60 resolveThreadLastVisitedAt,
61 resolveThreadStatusPill,
62 type ThreadStatusPill,
63 useRetainedValue,
64 useSidebarRowSubscriptionLease,
65} from "./Sidebar.logic";
66
67import type { SidebarThreadSummary } from "../types";
68import { formatWorktreePathForDisplay } from "../worktreeCleanup";
69import { SharedTooltipTrigger } from "./ui/shared-tooltip";
70import {
71 PULL_REQUEST_STATE_PRESENTATION,
72 PullRequestGlyph,
73 type PullRequestGlyphIcon,
74} from "./pullRequest/pullRequestIcons";
75import { resolvePullRequestState } from "./pullRequest/pullRequestPresentation";
76
77export interface PrStatusIndicator {
78 label: string;
79 colorClass: string;
80 Icon: PullRequestGlyphIcon;
81 tooltip: string;
82 tooltipLead: string;
83 tooltipTitle: string;
84 url: string;
85}
86
87export interface TerminalStatusIndicator {
88 label: string;
89 colorClass: string;
90 pulse: boolean;
91}
92
93export type ThreadPr = VcsStatusResult["pr"];
94
95export interface LinkedThreadPullRequestStatus {
96 readonly pr: NonNullable<ThreadPr>;
97 readonly sourceControlProvider: NonNullable<VcsStatusResult["sourceControlProvider"]>;
98}
99
100export function useLinkedThreadPullRequest(
101 environmentId: EnvironmentId | null,
102 linkedPullRequest: ThreadLinkedPullRequest | null | undefined,
103 enabled = true,
104 pullRequests?: ReadonlyArray<ThreadPullRequestLink>,
105 branchPullRequest?: ThreadLinkedPullRequest | null,
106 projectId?: ProjectId,
107): LinkedThreadPullRequestStatus | null {
108 const supportsLinks = useSupportsMultiplePullRequests(environmentId);
109 const current = supportsLinks ? resolveThreadCurrentPullRequestLink(pullRequests ?? []) : null;
110 const currentStatus = useLinkedPullRequestStatus(environmentId, projectId ?? null, current);
111 const fallback =
112 current === null ? ((!supportsLinks ? linkedPullRequest : null) ?? branchPullRequest) : null;
113 // Preserve reference identity so sidebar renders do not touch the summary cache.
114 const reference = fallback == null ? null : linkedPullRequestReference(fallback);
115 // Mounted for its answers, which land in the shared summary read below.
116 useEnvironmentQuery(
117 !enabled || environmentId === null || reference === null
118 ? null
119 : linkedPullRequestDetailAtom({ environmentId, input: reference }),
120 );
121 const detail = useSharedPullRequestSummary(environmentId, reference);
122 return currentStatus ?? (detail === null ? null : summaryStatus(detail));
123}
124
125function summaryStatus(detail: PullRequestSummary): LinkedThreadPullRequestStatus {
126 return {
127 pr: pullRequestDetailToVcsStatus(detail),
128 sourceControlProvider: {
129 kind: detail.provider,
130 name: sourceControlClients.get(detail.provider).label,
131 baseUrl: "",
132 },
133 };
134}
135
136export function useLinkedPullRequestStatus(
137 environmentId: EnvironmentId | null,
138 projectId: ProjectId | null,
139 link: ThreadPullRequestLink | null,
140): LinkedThreadPullRequestStatus | null {
141 const summary = useLinkedThreadPullRequestSummary(environmentId, projectId, link);
142 return summary === null
143 ? link === null
144 ? null
145 : linkedPullRequestSnapshotStatus(link)
146 : summaryStatus(summary);
147}
148
149/** The pull request a thread shows: its current link, else the one found for its branch. */
150export function useThreadDisplayedPullRequest(
151 environmentId: EnvironmentId,
152 thread: Pick<
153 EnvironmentThreadShell,
154 "projectId" | "pullRequests" | "linkedPullRequest" | "branchPullRequest"
155 > | null,
156 branchPr: ThreadPr = null,
157 branchSourceControlProvider?: VcsStatusResult["sourceControlProvider"],
158) {
159 const m = useMessages();
160 const supportsLinks = useSupportsMultiplePullRequests(environmentId);
161 const linkedStatus = useLinkedThreadPullRequest(
162 environmentId,
163 thread?.linkedPullRequest,
164 true,
165 thread?.pullRequests,
166 thread?.branchPullRequest,
167 thread?.projectId,
168 );
169 const currentLink = supportsLinks
170 ? resolveThreadCurrentPullRequestLink(thread?.pullRequests ?? [])
171 : null;
172 const pr = linkedStatus?.pr ?? (currentLink === null ? branchPr : null);
173 const badge = useSharedThreadPullRequestBadge(
174 environmentId,
175 thread?.projectId,
176 supportsLinks ? thread?.pullRequests : undefined,
177 );
178 return {
179 currentLink,
180 badge,
181 pr,
182 status: prStatusIndicator(
183 pr,
184 linkedStatus?.sourceControlProvider ?? branchSourceControlProvider,
185 m,
186 ),
187 number: currentLink?.number ?? pr?.number,
188 url: currentLink?.url ?? pr?.url,
189 };
190}
191
192function linkedPullRequestReference(fallback: ThreadLinkedPullRequest) {
193 const host = sourceControlClients.parseChangeRequestUrl(fallback.url)?.link.host;
194 return { ...fallback, ...(host === undefined ? {} : { host }) };
195}
196
197function changeRequestTerminologyForUrl(url: string | undefined) {
198 const host = url === undefined ? null : sourceControlClients.findByChangeRequestUrl(url);
199 return (host ?? sourceControlClients.get(undefined)).changeRequest;
200}
201
202function linkedPullRequestSnapshotStatus(
203 link: ThreadPullRequestLink,
204): LinkedThreadPullRequestStatus | null {
205 const snapshot = link.snapshot;
206 if (snapshot === null) return null;
207 const kind = (
208 sourceControlClients.findByChangeRequestUrl(link.url) ?? sourceControlClients.get(undefined)
209 ).kind;
210 return {
211 pr: {
212 number: link.number,
213 url: link.url,
214 title: snapshot.title,
215 state: snapshot.state,
216 isDraft: snapshot.isDraft,
217 headRef: snapshot.headBranch,
218 baseRef: snapshot.baseBranch,
219 ...(snapshot.updatedAt === null ? {} : { updatedAt: snapshot.updatedAt }),
220 },
221 sourceControlProvider: { kind, name: kind, baseUrl: "" },
222 };
223}
224
225export interface ThreadPullRequestBadgePresentation {
226 readonly Icon: PullRequestGlyphIcon;
227 readonly toneClassName: string;
228 readonly label: string;
229 readonly text: string | number;
230}
231
232type PullRequestBadgeState = ThreadPullRequestBadge["state"];
233
234function stackBadgeLabel(
235 state: PullRequestBadgeState,
236 count: number,
237 term: ChangeRequestTermKind,
238 resolve: MessageResolver,
239): string {
240 switch (state) {
241 case "open":
242 return resolve(
243 msg`${plural(
244 { count },
245 {
246 one: part`Stack of ${{ count }} ${select(
247 { term },
248 {
249 mr: "merge requests",
250 cr: "change requests",
251 other: "pull requests",
252 },
253 )}, open`,
254 other: part`Stack of ${{ count }} ${select(
255 { term },
256 {
257 mr: "merge requests",
258 cr: "change requests",
259 other: "pull requests",
260 },
261 )}, open`,
262 },
263 )}`,
264 );
265 case "draft":
266 return resolve(
267 msg`${plural(
268 { count },
269 {
270 one: part`Stack of ${{ count }} ${select(
271 { term },
272 {
273 mr: "merge requests",
274 cr: "change requests",
275 other: "pull requests",
276 },
277 )}, draft`,
278 other: part`Stack of ${{ count }} ${select(
279 { term },
280 {
281 mr: "merge requests",
282 cr: "change requests",
283 other: "pull requests",
284 },
285 )}, draft`,
286 },
287 )}`,
288 );
289 case "closed":
290 return resolve(
291 msg`${plural(
292 { count },
293 {
294 one: part`Stack of ${{ count }} ${select(
295 { term },
296 {
297 mr: "merge requests",
298 cr: "change requests",
299 other: "pull requests",
300 },
301 )}, closed`,
302 other: part`Stack of ${{ count }} ${select(
303 { term },
304 {
305 mr: "merge requests",
306 cr: "change requests",
307 other: "pull requests",
308 },
309 )}, closed`,
310 },
311 )}`,
312 );
313 case "merged":
314 return resolve(
315 msg`${plural(
316 { count },
317 {
318 one: part`Stack of ${{ count }} ${select(
319 { term },
320 {
321 mr: "merge requests",
322 cr: "change requests",
323 other: "pull requests",
324 },
325 )}, merged`,
326 other: part`Stack of ${{ count }} ${select(
327 { term },
328 {
329 mr: "merge requests",
330 cr: "change requests",
331 other: "pull requests",
332 },
333 )}, merged`,
334 },
335 )}`,
336 );
337 }
338}
339
340function moreLinkedBadgeLabel(
341 state: PullRequestBadgeState,
342 tooltip: string,
343 others: number,
344 resolve: MessageResolver,
345): string {
346 switch (state) {
347 case "open":
348 return resolve(
349 msg`${plural(
350 { others },
351 {
352 one: part`${{ tooltip }}, and ${{ others }} more linked; overall open`,
353 other: part`${{ tooltip }}, and ${{ others }} more linked; overall open`,
354 },
355 )}`,
356 );
357 case "draft":
358 return resolve(
359 msg`${plural(
360 { others },
361 {
362 one: part`${{ tooltip }}, and ${{ others }} more linked; overall draft`,
363 other: part`${{ tooltip }}, and ${{ others }} more linked; overall draft`,
364 },
365 )}`,
366 );
367 case "closed":
368 return resolve(
369 msg`${plural(
370 { others },
371 {
372 one: part`${{ tooltip }}, and ${{ others }} more linked; overall closed`,
373 other: part`${{ tooltip }}, and ${{ others }} more linked; overall closed`,
374 },
375 )}`,
376 );
377 case "merged":
378 return resolve(
379 msg`${plural(
380 { others },
381 {
382 one: part`${{ tooltip }}, and ${{ others }} more linked; overall merged`,
383 other: part`${{ tooltip }}, and ${{ others }} more linked; overall merged`,
384 },
385 )}`,
386 );
387 }
388}
389
390function prStatusLabels(
391 state: PullRequestBadgeState,
392 term: ChangeRequestTermKind,
393 number: number,
394 resolve: MessageResolver,
395): { readonly label: string; readonly tooltipLead: string } {
396 switch (state) {
397 case "open":
398 return {
399 label: resolve(
400 msg`${select({ term }, { mr: "MR", cr: "change request", other: "PR" })} open`,
401 ),
402 tooltipLead: resolve(
403 msg`${select({ term }, { mr: "MR", cr: "change request", other: "PR" })} #${{ number }} - Open`,
404 ),
405 };
406 case "draft":
407 return {
408 label: resolve(
409 msg`${select({ term }, { mr: "MR", cr: "change request", other: "PR" })} draft`,
410 ),
411 tooltipLead: resolve(
412 msg`${select({ term }, { mr: "MR", cr: "change request", other: "PR" })} #${{ number }} - Draft`,
413 ),
414 };
415 case "closed":
416 return {
417 label: resolve(
418 msg`${select({ term }, { mr: "MR", cr: "change request", other: "PR" })} closed`,
419 ),
420 tooltipLead: resolve(
421 msg`${select({ term }, { mr: "MR", cr: "change request", other: "PR" })} #${{ number }} - Closed`,
422 ),
423 };
424 case "merged":
425 return {
426 label: resolve(
427 msg`${select({ term }, { mr: "MR", cr: "change request", other: "PR" })} merged`,
428 ),
429 tooltipLead: resolve(
430 msg`${select({ term }, { mr: "MR", cr: "change request", other: "PR" })} #${{ number }} - Merged`,
431 ),
432 };
433 }
434}
435
436function resolveThreadPullRequestBadgePresentation(
437 {
438 badge,
439 number,
440 url,
441 status,
442 }: {
443 readonly badge: ThreadPullRequestBadge | null;
444 readonly number?: number | undefined;
445 readonly url?: string | undefined;
446 readonly status: PrStatusIndicator | null;
447 },
448 resolve: MessageResolver = m,
449): ThreadPullRequestBadgePresentation | null {
450 const terminology = changeRequestTerminologyForUrl(url);
451 if (badge?.kind === "stack") {
452 const aggregate = PULL_REQUEST_STATE_PRESENTATION[badge.state];
453 return {
454 Icon: PullRequestGlyph.stack,
455 toneClassName: aggregate.toneClassName,
456 label: stackBadgeLabel(
457 badge.state,
458 badge.layers,
459 changeRequestTermKind(terminology),
460 resolve,
461 ),
462 text: badge.layers,
463 };
464 }
465 if (number === undefined || url === undefined) return null;
466
467 const tooltip =
468 status?.tooltip ??
469 resolve(
470 msg`${select(
471 { term: changeRequestTermKind(terminology) },
472 {
473 mr: "MR",
474 cr: "change request",
475 other: "PR",
476 },
477 )} #${{ number }}, status pending`,
478 );
479 if (badge?.kind === "pull-request" && badge.others > 0) {
480 const aggregate = PULL_REQUEST_STATE_PRESENTATION[badge.state];
481 return {
482 Icon: aggregate.Icon,
483 toneClassName: aggregate.toneClassName,
484 label: moreLinkedBadgeLabel(badge.state, tooltip, badge.others, resolve),
485 text: `+${badge.others + 1}`,
486 };
487 }
488 return {
489 Icon: status?.Icon ?? PullRequestGlyph.pullRequest,
490 toneClassName: status?.colorClass ?? "text-muted-foreground",
491 label: tooltip,
492 text: number,
493 };
494}
495
496export function ThreadPullRequestBadgeControl({
497 render,
498 badge,
499 environmentId,
500 projectId,
501 pullRequests,
502 number,
503 url,
504 status,
505 onOpenList,
506 onOpenPullRequest,
507 side,
508}: {
509 render: ReactElement<{ render?: useRender.RenderProp }>;
510 badge: ThreadPullRequestBadge | null;
511 environmentId: EnvironmentId;
512 projectId: ProjectId | null;
513 pullRequests: ReadonlyArray<ThreadPullRequestLink>;
514 number?: number | undefined;
515 url?: string | undefined;
516 status: PrStatusIndicator | null;
517 onOpenList: () => void;
518 onOpenPullRequest: (event: MouseEvent<HTMLElement>, url?: string) => void;
519 side?: ThreadLinkBadgeSide | undefined;
520}) {
521 const m = useMessages();
522 const presentation = resolveThreadPullRequestBadgePresentation({ badge, number, url, status }, m);
523 if (presentation === null) return null;
524 return (
525 <PullRequestBadge
526 render={render}
527 presentation={presentation}
528 opensList={badge !== null && (badge.kind === "stack" || badge.others > 0)}
529 url={url}
530 number={number}
531 status={status}
532 environmentId={environmentId}
533 projectId={projectId}
534 pullRequests={pullRequests}
535 onOpenList={onOpenList}
536 onOpenPullRequest={onOpenPullRequest}
537 side={side}
538 />
539 );
540}
541
542function PullRequestBadge({
543 render,
544 presentation,
545 opensList,
546 url,
547 number,
548 status,
549 environmentId,
550 projectId,
551 pullRequests,
552 onOpenList,
553 onOpenPullRequest,
554 side,
555}: {
556 render: ReactElement<{ render?: useRender.RenderProp }>;
557 presentation: NonNullable<ReturnType<typeof resolveThreadPullRequestBadgePresentation>>;
558 opensList: boolean;
559 url: string | undefined;
560 number: number | undefined;
561 status: PrStatusIndicator | null;
562 environmentId: EnvironmentId;
563 projectId: ProjectId | null;
564 pullRequests: ReadonlyArray<ThreadPullRequestLink>;
565 onOpenList: () => void;
566 onOpenPullRequest: (event: MouseEvent<HTMLElement>, url?: string) => void;
567 side: ThreadLinkBadgeSide | undefined;
568}) {
569 const onClick = opensList
570 ? (event: MouseEvent<HTMLElement>) => {
571 event.preventDefault();
572 event.stopPropagation();
573 onOpenList();
574 }
575 : onOpenPullRequest;
576 const element = opensList ? (
577 <button type="button" />
578 ) : (
579 <a href={url} target="_blank" rel="noopener noreferrer" />
580 );
581 const control = useRender({
582 render,
583 props: {
584 render: element,
585 "aria-label": presentation.label,
586 onPointerDown: (event: MouseEvent<HTMLElement>) => event.stopPropagation(),
587 onClick,
588 },
589 });
590 return (
591 <ThreadLinkBadge
592 key={opensList ? "list" : "link"}
593 control={control}
594 Icon={presentation.Icon}
595 toneClassName={presentation.toneClassName}
596 text={presentation.text}
597 side={side}
598 >
599 {pullRequests.some((link) => link.source !== "stack-dismissed") ? (
600 <ThreadPullRequestsMiniList
601 environmentId={environmentId}
602 projectId={projectId}
603 pullRequests={pullRequests}
604 onOpenPullRequest={onOpenPullRequest}
605 onShowAll={onOpenList}
606 />
607 ) : number !== undefined && url !== undefined ? (
608 <ul className="flex flex-col gap-1">
609 <ThreadPullRequestMiniListItem
610 number={number}
611 url={url}
612 title={status?.tooltipTitle ?? presentation.label}
613 presentation={presentation}
614 onOpenPullRequest={onOpenPullRequest}
615 />
616 </ul>
617 ) : null}
618 </ThreadLinkBadge>
619 );
620}
621
622type ThreadLinkBadgeSide = "top" | "right";
623
624export function ThreadLinkBadge({
625 control,
626 Icon,
627 toneClassName,
628 text,
629 side = "top",
630 children,
631}: {
632 control: ReactElement;
633 Icon: ComponentType<{ className?: string; "aria-hidden"?: boolean }>;
634 toneClassName: string;
635 text: string | number;
636 side?: ThreadLinkBadgeSide | undefined;
637 children: ReactNode;
638}) {
639 return (
640 // The shared popup renders at the app root, so a right-click in it never reaches the row.
641 <SharedTooltipTrigger
642 render={control}
643 side={side}
644 {...(side === "right" ? { align: "start" as const } : {})}
645 sideOffset={0}
646 variant="glass"
647 className="w-80 max-w-[calc(100vw-2rem)] text-left whitespace-normal"
648 label={
649 <div className="-mx-1 max-h-[calc(var(--available-height)-0.5rem-2px)] overflow-y-auto overscroll-contain">
650 {children}
651 </div>
652 }
653 >
654 <span className={cn("contents font-normal text-xs tabular-nums", toneClassName)}>
655 <Icon aria-hidden className="size-3 shrink-0" />
656 <span className="max-w-16 truncate">{text}</span>
657 </span>
658 </SharedTooltipTrigger>
659 );
660}
661
662// Hover previews stay short: rendering hundreds of rows froze the page and
663// filled the screen. The full list lives in the Linked items tab.
664export const LINKED_ITEMS_PREVIEW_LIMIT = 8;
665
666export function LinkedItemsOverflow({
667 hidden,
668 onShowAll,
669}: {
670 hidden: number;
671 onShowAll?: (() => void) | undefined;
672}) {
673 if (hidden <= 0) return null;
674 if (!onShowAll) {
675 return (
676 <div className="px-1 pt-1 text-muted-foreground">
677 <T>
678 +<Var>{hidden}</Var> more
679 </T>
680 </div>
681 );
682 }
683 return (
684 <Button
685 variant="ghost-muted"
686 size="xs"
687 className="mt-1 w-full justify-start"
688 onPointerDown={(event) => event.stopPropagation()}
689 onClick={(event) => {
690 event.preventDefault();
691 event.stopPropagation();
692 onShowAll();
693 }}
694 >
695 <T>
696 +<Var>{hidden}</Var> more in Linked items
697 </T>
698 </Button>
699 );
700}
701
702export function ThreadPullRequestsMiniList({
703 environmentId,
704 projectId,
705 pullRequests,
706 onOpenPullRequest,
707 onShowAll,
708}: {
709 environmentId: EnvironmentId;
710 projectId: ProjectId | null;
711 pullRequests: ReadonlyArray<ThreadPullRequestLink>;
712 onOpenPullRequest?: (event: MouseEvent<HTMLAnchorElement>, url: string) => void;
713 onShowAll?: (() => void) | undefined;
714}) {
715 const lines = pullRequestListLines(resolveThreadPullRequestChains(pullRequests));
716 if (lines.length === 0) return null;
717 return (
718 <>
719 <ul className="flex flex-col gap-1">
720 {lines.slice(0, LINKED_ITEMS_PREVIEW_LIMIT).map((line) => (
721 <LinkedPullRequestMiniListItem
722 key={`${line.link.host}/${line.link.repository}#${line.link.number}`}
723 environmentId={environmentId}
724 projectId={projectId}
725 line={line}
726 onOpenPullRequest={onOpenPullRequest}
727 />
728 ))}
729 </ul>
730 <LinkedItemsOverflow
731 hidden={lines.length - LINKED_ITEMS_PREVIEW_LIMIT}
732 onShowAll={onShowAll}
733 />
734 </>
735 );
736}
737
738function LinkedPullRequestMiniListItem({
739 environmentId,
740 projectId,
741 line,
742 onOpenPullRequest,
743}: {
744 environmentId: EnvironmentId;
745 projectId: ProjectId | null;
746 line: ReturnType<typeof pullRequestListLines>[number];
747 onOpenPullRequest: ((event: MouseEvent<HTMLAnchorElement>, url: string) => void) | undefined;
748}) {
749 const pr = useLinkedPullRequestStatus(environmentId, projectId, line.link)?.pr ?? null;
750 return (
751 <ThreadPullRequestMiniListItem
752 number={line.link.number}
753 url={line.link.url}
754 title={pr?.title ?? line.link.repository}
755 presentation={
756 pr === null
757 ? null
758 : resolvePullRequestState({ state: pr.state, isDraft: pr.isDraft ?? false })
759 }
760 depth={line.depth}
761 onOpenPullRequest={onOpenPullRequest}
762 >
763 {line.stack ? (
764 <span className="ml-auto shrink-0 pl-1 text-3xs">
765 {line.stack.kind === "native" ? (
766 <T context="a native stack of pull requests">stack</T>
767 ) : (
768 <T context="a chain of pull requests based on each other">chain</T>
769 )}{" "}
770 · {line.stack.size}
771 </span>
772 ) : null}
773 </ThreadPullRequestMiniListItem>
774 );
775}
776
777function ThreadPullRequestMiniListItem({
778 number,
779 url,
780 title,
781 presentation,
782 depth = 0,
783 onOpenPullRequest,
784 children,
785}: {
786 number: number;
787 url: string;
788 title: string;
789 presentation: Pick<ThreadPullRequestBadgePresentation, "Icon" | "toneClassName"> | null;
790 depth?: number;
791 onOpenPullRequest?: ((event: MouseEvent<HTMLAnchorElement>, url: string) => void) | undefined;
792 children?: ReactNode;
793}) {
794 const Icon = presentation?.Icon ?? PullRequestGlyph.pullRequest;
795 const content = (
796 <>
797 <Icon
798 aria-hidden
799 className={cn("size-3 shrink-0", presentation?.toneClassName ?? "stroke-muted-foreground")}
800 />
801 <span className="shrink-0 font-mono tabular-nums">#{number}</span>
802 <span className="min-w-0 truncate text-foreground/75">{title}</span>
803 {children}
804 </>
805 );
806 return (
807 <li style={{ paddingLeft: `${Math.min(depth, 3) * 0.75}rem` }}>
808 {onOpenPullRequest ? (
809 <a
810 href={url}
811 target="_blank"
812 rel="noopener noreferrer"
813 className="flex min-w-0 items-center gap-2 rounded-sm px-1 py-1 hover:bg-accent focus-visible:bg-accent focus-visible:outline-2 focus-visible:-outline-offset-2 focus-visible:outline-ring"
814 onPointerDown={(event) => event.stopPropagation()}
815 onClick={(event) => onOpenPullRequest(event, url)}
816 >
817 {content}
818 </a>
819 ) : (
820 <div className="flex min-w-0 items-center gap-2">{content}</div>
821 )}
822 </li>
823 );
824}
825
826export function prStatusIndicator(
827 pr: ThreadPr,
828 provider: VcsStatusResult["sourceControlProvider"] | null | undefined,
829 resolve: MessageResolver = m,
830): PrStatusIndicator | null {
831 if (!pr) return null;
832 const term = changeRequestTermKind(sourceControlClients.get(provider?.kind).changeRequest);
833 const state = resolvePullRequestState({ state: pr.state, isDraft: pr.isDraft === true }, resolve);
834 const { label, tooltipLead } = prStatusLabels(
835 pr.state === "open" && pr.isDraft === true ? "draft" : pr.state,
836 term,
837 pr.number,
838 resolve,
839 );
840 return {
841 label,
842 colorClass: state.toneClassName,
843 Icon: state.Icon,
844 tooltip: resolve(msg`${{ tooltipLead }}: ${{ title: pr.title }}`),
845 tooltipLead,
846 tooltipTitle: pr.title,
847 url: pr.url,
848 };
849}
850
851export function ChangeRequestStatusIcon({
852 state,
853 isDraft = false,
854 className,
855}: Pick<NonNullable<ThreadPr>, "state"> & {
856 readonly isDraft?: boolean | undefined;
857 readonly className?: string | undefined;
858}) {
859 const presentation = resolvePullRequestState({ state, isDraft });
860 return <presentation.Icon className={className} />;
861}
862
863function PrStatusTooltipContent({ status }: { status: PrStatusIndicator }) {
864 return (
865 <span className="flex max-w-[min(34rem,calc(100vw-2rem))] items-stretch overflow-hidden whitespace-nowrap">
866 <span className="shrink-0 pr-2 font-medium">{status.tooltipLead}</span>
867 <span className="min-h-4 shrink-0 border-border/70 border-l" aria-hidden="true" />
868 <span className="min-w-0 truncate pl-2">{status.tooltipTitle}</span>
869 </span>
870 );
871}
872
873export function resolveDisplayedThreadPr(input: {
874 threadBranch: string | null;
875 gitStatus: VcsStatusResult | null;
876 linkedPullRequest?: ThreadLinkedPullRequest | null | undefined;
877 linkedPullRequestStatus?: LinkedThreadPullRequestStatus | null | undefined;
878 pullRequests?: ReadonlyArray<ThreadPullRequestLink> | undefined;
879}): ThreadPr | null {
880 const { threadBranch, gitStatus, linkedPullRequest, linkedPullRequestStatus } = input;
881 if (linkedPullRequest != null) {
882 return linkedPullRequestStatus?.pr ?? null;
883 }
884 if (
885 threadBranch !== null &&
886 gitStatus !== null &&
887 gitStatus.refName === threadBranch &&
888 gitStatus.pr?.state === "open" &&
889 !isThreadPullRequestDismissed(input.pullRequests ?? [], gitStatus.pr.url)
890 ) {
891 return gitStatus.pr;
892 }
893
894 return null;
895}
896
897export function resolveDisplayedThreadPrProvider(input: {
898 threadBranch: string | null;
899 gitStatus: VcsStatusResult | null;
900 linkedPullRequest?: ThreadLinkedPullRequest | null | undefined;
901 linkedPullRequestStatus?: LinkedThreadPullRequestStatus | null | undefined;
902}): VcsStatusResult["sourceControlProvider"] | undefined {
903 const { gitStatus, linkedPullRequest, linkedPullRequestStatus } = input;
904 if (linkedPullRequest != null) {
905 return linkedPullRequestStatus?.sourceControlProvider;
906 }
907 if (resolveDisplayedThreadPr(input) !== null) {
908 return gitStatus?.sourceControlProvider;
909 }
910
911 return undefined;
912}
913
914export function terminalStatusFromRunningIds(
915 runningTerminalIds: ReadonlyArray<string>,
916 resolve: MessageResolver = m,
917): TerminalStatusIndicator | null {
918 if (runningTerminalIds.length === 0) {
919 return null;
920 }
921 return {
922 label: resolve(msg("Terminal process running")),
923 colorClass: "text-teal-600 dark:text-teal-300/90",
924 pulse: true,
925 };
926}
927
928function synchronizeTerminalPulse(event: AnimationEvent<SVGSVGElement>) {
929 if (event.animationName !== "status-pulse") return;
930
931 for (const animation of event.currentTarget.getAnimations()) {
932 if ("animationName" in animation && animation.animationName === "status-pulse") {
933 animation.startTime = 0;
934 }
935 }
936}
937
938export function ThreadTerminalStatusButton({
939 threadRef,
940 terminalIds,
941 onThreadActivate,
942}: {
943 threadRef: ScopedThreadRef;
944 terminalIds: readonly string[];
945 onThreadActivate: (threadRef: ScopedThreadRef) => void;
946}) {
947 const gt = useGT();
948 const messages = useMessages();
949 const terminalId = terminalIds[0];
950 if (terminalId === undefined) return null;
951 const status = terminalStatusFromRunningIds(terminalIds, messages);
952 const label = gt`${plural(
953 { count: terminalIds.length },
954 {
955 one: part`${{ count: terminalIds.length }} terminal process running. Open terminal`,
956 other: part`${{ count: terminalIds.length }} terminal processes running. Open terminal`,
957 },
958 )}`;
959 return (
960 <SharedTooltipTrigger
961 render={
962 <button
963 type="button"
964 aria-label={label}
965 data-testid={`sidebar-terminal-status-${threadRef.threadId}`}
966 className={cn(
967 "inline-flex shrink-0 cursor-pointer items-center justify-center rounded-sm outline-none hover:opacity-80 focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring",
968 status?.colorClass,
969 )}
970 onPointerDown={(event) => event.stopPropagation()}
971 onKeyDown={(event) => event.stopPropagation()}
972 onClick={(event) => {
973 event.preventDefault();
974 event.stopPropagation();
975 revealThreadTerminal(threadRef, terminalId);
976 onThreadActivate(threadRef);
977 }}
978 />
979 }
980 label={label}
981 >
982 <TerminalIcon
983 className="size-3.5 motion-safe:animate-status-pulse"
984 onAnimationStart={synchronizeTerminalPulse}
985 />
986 </SharedTooltipTrigger>
987 );
988}
989
990export function ThreadWorktreeIndicator({
991 thread,
992}: {
993 thread: Pick<SidebarThreadSummary, "id" | "branch" | "worktreePath">;
994}) {
995 const gt = useGT();
996 const worktreePath = thread.worktreePath?.trim();
997 if (!worktreePath) {
998 return null;
999 }
1000
1001 const displayPath = formatWorktreePathForDisplay(worktreePath);
1002 const tooltip = thread.branch
1003 ? gt`Worktree: ${{ path: displayPath }} (${{ branch: thread.branch }})`
1004 : gt`Worktree: ${{ path: displayPath }}`;
1005
1006 return (
1007 <SharedTooltipTrigger
1008 render={
1009 <span
1010 role="img"
1011 aria-label={tooltip}
1012 data-testid={`thread-worktree-${thread.id}`}
1013 className="inline-flex items-center justify-center"
1014 />
1015 }
1016 side="top"
1017 label={tooltip}
1018 >
1019 <FolderGit2Icon className="size-3.5 shrink-0 text-icon-muted" />
1020 </SharedTooltipTrigger>
1021 );
1022}
1023
1024function ThreadStatusLabel({
1025 status,
1026 compact = false,
1027}: {
1028 status: ThreadStatusPill;
1029 compact?: boolean;
1030}) {
1031 const m = useMessages();
1032 const label = m(status.label);
1033 if (compact) {
1034 return (
1035 <SharedTooltipTrigger
1036 render={
1037 <span
1038 role="img"
1039 aria-label={label}
1040 className={`inline-flex size-3.5 shrink-0 items-center justify-center ${status.colorClass}`}
1041 />
1042 }
1043 label={label}
1044 >
1045 <span
1046 className={`size-[9px] rounded-full ${status.dotClass} ${
1047 status.pulse ? "motion-safe:animate-status-pulse" : ""
1048 }`}
1049 />
1050 </SharedTooltipTrigger>
1051 );
1052 }
1053
1054 return (
1055 <SharedTooltipTrigger
1056 render={
1057 <span
1058 role="img"
1059 aria-label={label}
1060 className={`inline-flex items-center gap-1 text-3xs ${status.colorClass}`}
1061 />
1062 }
1063 label={label}
1064 >
1065 <span
1066 className={`h-1.5 w-1.5 rounded-full ${status.dotClass} ${
1067 status.pulse ? "motion-safe:animate-status-pulse" : ""
1068 }`}
1069 />
1070 <span className="hidden md:inline">{label}</span>
1071 </SharedTooltipTrigger>
1072 );
1073}
1074
1075export function ThreadRowLeadingStatus({ thread }: { thread: SidebarThreadSummary }) {
1076 const gt = useGT();
1077 const m = useMessages();
1078 const { leaseLiveStatus, rowRef } = useSidebarRowSubscriptionLease(false);
1079 // A new ref callback would detach and reattach the row, and each reattach sets lease state.
1080 const statusRef = useStableCallback((node: HTMLSpanElement | null) =>
1081 rowRef(node?.parentElement ?? null),
1082 );
1083 const threadRef = scopeThreadRef(thread.environmentId, thread.id);
1084 const localLastVisitedAt = useUiStateStore(
1085 (state) => state.threadLastVisitedAtById[scopedThreadKey(threadRef)],
1086 );
1087 const lastVisitedAt = resolveThreadLastVisitedAt(thread.lastVisitedAt, localLastVisitedAt);
1088 const threadProject = useProject(scopeProjectRef(thread.environmentId, thread.projectId));
1089 const threadProjectCwd = threadProject?.workspaceRoot ?? null;
1090 const gitCwd = thread.worktreePath ?? threadProjectCwd;
1091 const linkedPullRequest = useLinkedThreadPullRequest(
1092 thread.environmentId,
1093 thread.linkedPullRequest,
1094 leaseLiveStatus,
1095 thread.pullRequests,
1096 thread.branchPullRequest,
1097 thread.projectId,
1098 );
1099 const gitStatus = useEnvironmentQuery(
1100 leaseLiveStatus &&
1101 thread.linkedPullRequest == null &&
1102 (thread.branch != null || thread.worktreePath !== null) &&
1103 gitCwd !== null
1104 ? vcsEnvironment.status({
1105 environmentId: thread.environmentId,
1106 input: { cwd: gitCwd, includeRemote: false },
1107 })
1108 : null,
1109 );
1110 const visibleGitStatus = useRetainedValue(
1111 JSON.stringify([thread.environmentId, gitCwd]),
1112 gitStatus.data,
1113 );
1114 const displayedPrInput = {
1115 threadBranch: thread.branch,
1116 gitStatus: visibleGitStatus,
1117 linkedPullRequest: thread.linkedPullRequest,
1118 linkedPullRequestStatus: linkedPullRequest,
1119 pullRequests: thread.pullRequests,
1120 };
1121 const pr = linkedPullRequest?.pr ?? resolveDisplayedThreadPr(displayedPrInput);
1122 const prStatus = prStatusIndicator(
1123 pr,
1124 linkedPullRequest?.sourceControlProvider ?? resolveDisplayedThreadPrProvider(displayedPrInput),
1125 m,
1126 );
1127 const threadStatus = resolveThreadStatusPill({
1128 thread: {
1129 ...thread,
1130 lastVisitedAt,
1131 },
1132 });
1133
1134 const supportsMultiplePullRequests = useSupportsMultiplePullRequests(thread.environmentId);
1135 const pendingLink =
1136 pr === null && supportsMultiplePullRequests
1137 ? resolveThreadCurrentPullRequestLink(thread.pullRequests)
1138 : null;
1139
1140 return (
1141 <span
1142 ref={statusRef}
1143 className={
1144 prStatus || threadStatus ? "inline-flex shrink-0 items-center gap-1.5" : "contents"
1145 }
1146 >
1147 {prStatus && pr ? (
1148 <SharedTooltipTrigger
1149 render={
1150 <span
1151 aria-label={prStatus.tooltip}
1152 className={`inline-flex items-center justify-center ${prStatus.colorClass}`}
1153 />
1154 }
1155 label={
1156 <>
1157 <PrStatusTooltipContent status={prStatus} />
1158 </>
1159 }
1160 >
1161 <ChangeRequestStatusIcon state={pr.state} isDraft={pr.isDraft} className="size-3" />
1162 </SharedTooltipTrigger>
1163 ) : null}
1164 {pendingLink ? (
1165 <PullRequestGlyph.pullRequest
1166 className="size-3 text-muted-foreground"
1167 aria-label={gt`${select(
1168 { term: changeRequestTermKind(changeRequestTerminologyForUrl(pendingLink.url)) },
1169 {
1170 mr: "MR",
1171 cr: "change request",
1172 other: "PR",
1173 },
1174 )} #${{ number: pendingLink.number }}, status pending`}
1175 />
1176 ) : null}
1177 {threadStatus ? <ThreadStatusLabel status={threadStatus} /> : null}
1178 </span>
1179 );
1180}
1181
1182export function ThreadRowTrailingStatus({ thread }: { thread: SidebarThreadSummary }) {
1183 const gt = useGT();
1184 const m = useMessages();
1185 const runningTerminalIds = useThreadRunningTerminalIds({
1186 environmentId: thread.environmentId,
1187 threadId: thread.id,
1188 });
1189 const environment = useEnvironment(thread.environmentId);
1190 const primaryEnvironmentId = usePrimaryEnvironmentId();
1191 const isRemoteThread = thread.environmentId !== primaryEnvironmentId;
1192 const remoteEnvLabel = environment?.label ?? null;
1193 const threadEnvironmentLabel = isRemoteThread
1194 ? (remoteEnvLabel ?? gt({ context: "machine location" })`Remote`)
1195 : null;
1196 const remoteMachine = resolveEnvironmentMachineKind(environment?.serverConfig ?? null);
1197 const terminalStatus = terminalStatusFromRunningIds(runningTerminalIds, m);
1198
1199 if (!terminalStatus && !isRemoteThread) {
1200 return null;
1201 }
1202
1203 return (
1204 <span className="inline-flex shrink-0 items-center gap-1.5">
1205 {terminalStatus ? (
1206 <SharedTooltipTrigger
1207 render={
1208 <span
1209 role="img"
1210 aria-label={terminalStatus.label}
1211 className={`inline-flex items-center justify-center ${terminalStatus.colorClass}`}
1212 />
1213 }
1214 label={terminalStatus.label}
1215 >
1216 <TerminalIcon
1217 className={`size-3 ${terminalStatus.pulse ? "motion-safe:animate-status-pulse" : ""}`}
1218 onAnimationStart={synchronizeTerminalPulse}
1219 />
1220 </SharedTooltipTrigger>
1221 ) : null}
1222 {isRemoteThread ? (
1223 <SharedTooltipTrigger
1224 render={
1225 <span
1226 aria-label={threadEnvironmentLabel ?? gt({ context: "machine location" })`Remote`}
1227 className="inline-flex items-center justify-center"
1228 />
1229 }
1230 label={threadEnvironmentLabel}
1231 >
1232 <EnvironmentMachineIcon
1233 kind={remoteMachine}
1234 className="size-3 text-muted-foreground/60"
1235 />
1236 </SharedTooltipTrigger>
1237 ) : null}
1238 </span>
1239 );
1240}
1241
1242function settledPrHoverColorClass(state: ThreadPullRequestBadge["state"]): string {
1243 switch (state) {
1244 case "draft":
1245 return "group-hover/sidebar-row:text-zinc-500 dark:group-hover/sidebar-row:text-zinc-400/80";
1246 case "open":
1247 return "group-hover/sidebar-row:text-emerald-600 dark:group-hover/sidebar-row:text-emerald-300/90";
1248 case "merged":
1249 return "group-hover/sidebar-row:text-violet-600 dark:group-hover/sidebar-row:text-violet-300/90";
1250 case "closed":
1251 return "group-hover/sidebar-row:text-red-600 dark:group-hover/sidebar-row:text-red-300/90";
1252 }
1253}
1254
1255// Search rows are already buttons, so this renders the sidebar badge's look without its controls.
1256export function ThreadSearchPullRequestNumber({
1257 thread,
1258 query,
1259 enabled = true,
1260 settled = false,
1261}: {
1262 thread: SidebarThreadSummary;
1263 query: string;
1264 enabled?: boolean;
1265 settled?: boolean;
1266}) {
1267 const matched = pullRequestMatchesSearchQuery(thread, query);
1268 const supportsMultiplePullRequests = useSupportsMultiplePullRequests(thread.environmentId);
1269 const linked = useLinkedThreadPullRequest(
1270 thread.environmentId,
1271 thread.linkedPullRequest,
1272 enabled && matched,
1273 thread.pullRequests,
1274 thread.branchPullRequest,
1275 thread.projectId,
1276 );
1277 const m = useMessages();
1278 const badge = useSharedThreadPullRequestBadge(
1279 thread.environmentId,
1280 thread.projectId,
1281 matched && supportsMultiplePullRequests ? thread.pullRequests : undefined,
1282 );
1283 if (!matched) return null;
1284 const current = supportsMultiplePullRequests
1285 ? resolveThreadCurrentPullRequestLink(thread.pullRequests)
1286 : null;
1287 const pr = linked?.pr ?? null;
1288 // Stored references already carry a number, so the badge shows before PR details load.
1289 const stored =
1290 current ??
1291 [thread.linkedPullRequest, thread.branchPullRequest].find(
1292 (reference) =>
1293 reference != null && pullRequestMatchesSearchQuery({ linkedPullRequest: reference }, query),
1294 );
1295 const presentation = resolveThreadPullRequestBadgePresentation(
1296 {
1297 badge,
1298 number: pr?.number ?? stored?.number,
1299 url: pr?.url ?? stored?.url,
1300 status: prStatusIndicator(pr, linked?.sourceControlProvider, m),
1301 },
1302 m,
1303 );
1304 if (presentation === null) return null;
1305 const aggregate = badge !== null && (badge.kind === "stack" || badge.others > 0);
1306 const state = aggregate
1307 ? badge.state
1308 : pr === null
1309 ? null
1310 : pr.state === "open" && pr.isDraft
1311 ? "draft"
1312 : pr.state;
1313 return (
1314 <span
1315 aria-label={presentation.label}
1316 className={cn(
1317 "inline-flex shrink-0 items-center gap-0.5 text-xs tabular-nums",
1318 settled
1319 ? cn("text-secondary-label transition-colors", state && settledPrHoverColorClass(state))
1320 : presentation.toneClassName,
1321 )}
1322 >
1323 {/* text-current opts out of the command palette's muted icon color. */}
1324 <presentation.Icon aria-hidden className="size-3 shrink-0 text-current" />
1325 <span>{presentation.text}</span>
1326 </span>
1327 );
1328}