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

ThreadStatusIndicators.tsx

1,111 lines35.3 KB

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