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

ThreadStatusIndicators.tsx

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