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

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