Open History to see the last commit
1import { useSupportsMultiplePullRequests } from "~/hooks/useSupportsMultiplePullRequests";
2import { scopedThreadKey, scopeThreadRef } from "@t3tools/client-runtime/environment";
3import { pullRequestDetailToVcsStatus } from "@t3tools/client-runtime/state/pull-requests";
4import {
5 resolveEnvironmentMachineKind,
6 type EnvironmentId,
7 type ThreadLinkedPullRequest,
8 type ThreadPullRequestLink,
9 type VcsStatusResult,
10} from "@t3tools/contracts";
11import {
12 resolveThreadCurrentPullRequestLink,
13 resolveThreadPullRequestChains,
14 visibleThreadPullRequests,
15 type ThreadPullRequestBadge,
16} from "@t3tools/shared/threadPullRequests";
17import { FolderGit2Icon, GitPullRequestArrowIcon, LayersIcon, TerminalIcon } from "lucide-react";
18import { useMemo, type MouseEvent } from "react";
19import { buttonVariants, InlineButton } from "./ui/button";
20import { cn } from "../lib/utils";
21import { useEnvironment, usePrimaryEnvironmentId } from "../state/environments";
22import { EnvironmentMachineIcon } from "./EnvironmentMachineIcon";
23import { parseChangeRequestUrl } from "../lib/openPullRequestLink";
24import { useEnvironmentQuery } from "../state/query";
25import { linkedPullRequestDetailAtom, useSharedPullRequestSummary } from "../state/pullRequests";
26import { useThreadRunningTerminalIds } from "../state/terminalSessions";
27import { useUiStateStore } from "../uiStateStore";
28import { resolveChangeRequestPresentation } from "../sourceControlPresentation";
29import { resolveThreadStatusPill, type ThreadStatusPill } from "./Sidebar.logic";
30import type { SidebarThreadSummary } from "../types";
31import { formatWorktreePathForDisplay } from "../worktreeCleanup";
32import { Tooltip, TooltipPopup, TooltipTrigger } from "./ui/tooltip";
33import { pullRequestListLines } from "./pullRequest/pullRequestListLines";
34import { resolvePullRequestState } from "./pullRequest/pullRequestPresentation";
35
36export interface PrStatusIndicator {
37 label: string;
38 colorClass: string;
39 tooltip: string;
40 tooltipLead: string;
41 tooltipTitle: string;
42 url: string;
43}
44
45export interface TerminalStatusIndicator {
46 label: "Terminal process running";
47 colorClass: string;
48 pulse: boolean;
49}
50
51export type ThreadPr = VcsStatusResult["pr"];
52
53export interface LinkedThreadPullRequestStatus {
54 readonly pr: NonNullable<ThreadPr>;
55 readonly sourceControlProvider: NonNullable<VcsStatusResult["sourceControlProvider"]>;
56}
57
58/** Linked badges use persisted snapshots; only branch and legacy fallbacks lease summary reads. */
59export function useLinkedThreadPullRequest(
60 environmentId: EnvironmentId | null,
61 linkedPullRequest: ThreadLinkedPullRequest | null | undefined,
62 enabled = true,
63 pullRequests?: ReadonlyArray<ThreadPullRequestLink>,
64 branchPullRequest?: ThreadLinkedPullRequest | null,
65): LinkedThreadPullRequestStatus | null {
66 const supportsLinks = useSupportsMultiplePullRequests(environmentId);
67 const current = useMemo(
68 () => (supportsLinks ? resolveThreadCurrentPullRequestLink(pullRequests ?? []) : null),
69 [pullRequests, supportsLinks],
70 );
71 const fallback =
72 current === null ? ((!supportsLinks ? linkedPullRequest : null) ?? branchPullRequest) : null;
73 const host = fallback == null ? undefined : parseChangeRequestUrl(fallback.url)?.host;
74 const reference =
75 fallback == null ? null : { ...fallback, ...(host === undefined ? {} : { host }) };
76 const queried = useEnvironmentQuery(
77 !enabled || environmentId === null || reference === null
78 ? null
79 : linkedPullRequestDetailAtom({ environmentId, input: reference }),
80 ).data;
81 const detail = useSharedPullRequestSummary(environmentId, reference, queried);
82
83 return useMemo(() => {
84 if (current !== null) return linkedPullRequestSnapshotStatus(current);
85 return detail === null
86 ? null
87 : {
88 pr: pullRequestDetailToVcsStatus(detail),
89 sourceControlProvider: { kind: detail.provider, name: detail.provider, baseUrl: "" },
90 };
91 }, [current, detail]);
92}
93
94export function linkedPullRequestSnapshotStatus(
95 link: ThreadPullRequestLink,
96): LinkedThreadPullRequestStatus | null {
97 const snapshot = link.snapshot;
98 if (snapshot === null) return null;
99 const kind = link.url.includes("/-/merge_requests/")
100 ? "gitlab"
101 : link.url.includes("/pullrequest/")
102 ? "azure-devops"
103 : link.url.includes("/pull-requests/")
104 ? "bitbucket"
105 : link.url.includes("/pulls/")
106 ? "forgejo"
107 : "github";
108 return {
109 pr: {
110 number: link.number,
111 url: link.url,
112 title: snapshot.title,
113 state: snapshot.state,
114 isDraft: snapshot.isDraft,
115 headRef: snapshot.headBranch,
116 baseRef: snapshot.baseBranch,
117 ...(snapshot.updatedAt === null ? {} : { updatedAt: snapshot.updatedAt }),
118 },
119 sourceControlProvider: { kind, name: kind, baseUrl: "" },
120 };
121}
122
123export {
124 resolveThreadPullRequestBadge,
125 type ThreadPullRequestBadge,
126} from "@t3tools/shared/threadPullRequests";
127
128/** The glyph a row's badge wears: the layers icon for a stack, the pull-request one otherwise. */
129function ThreadPullRequestBadgeIcon({
130 icon,
131 className,
132}: {
133 icon: "stack" | "pull-request";
134 className?: string | undefined;
135}) {
136 const Icon = icon === "stack" ? LayersIcon : GitPullRequestArrowIcon;
137 return <Icon aria-hidden className={cn("size-3 shrink-0", className)} />;
138}
139
140/** The complete linked-PR control shared by the sidebar and composer footer. */
141export function ThreadPullRequestBadgeControl({
142 variant,
143 badge,
144 number,
145 url,
146 status,
147 iconOnly = false,
148 onOpenStack,
149 onOpenPullRequest,
150}: {
151 variant: "underline" | "ghost";
152 badge: ThreadPullRequestBadge | null;
153 number?: number | undefined;
154 url?: string | undefined;
155 status: PrStatusIndicator | null;
156 /** Dense rows drop the number/layer count and keep only the state glyph. */
157 iconOnly?: boolean;
158 onOpenStack: () => void;
159 onOpenPullRequest: (event: MouseEvent<HTMLAnchorElement>) => void;
160}) {
161 const isStack = badge?.kind === "stack";
162 const linkedCount = badge?.kind === "pull-request" && badge.others > 0 ? badge.others + 1 : null;
163 if (!isStack && (number === undefined || url === undefined)) return null;
164 const label = isStack
165 ? `Stack of ${badge.layers} pull requests, ${badge.state}`
166 : `${status?.tooltip ?? `PR #${number}, status pending`}${
167 badge?.kind === "pull-request" && badge.others > 0
168 ? `, and ${badge.others} more linked; overall ${badge.state}`
169 : ""
170 }`;
171 const className = cn(
172 variant === "ghost"
173 ? buttonVariants({ variant: "ghost", size: "xs" })
174 : "inline-flex shrink-0 cursor-pointer items-center gap-0.5 whitespace-nowrap border-b border-transparent hover:border-current focus-visible:outline-2 focus-visible:outline-ring",
175 "text-xs tabular-nums",
176 variant === "ghost" &&
177 "font-normal text-xs! active:scale-100 [--control-icon-color:currentColor]",
178 badge !== null && (isStack || linkedCount !== null)
179 ? PR_STATE_COLOR_CLASS[badge.state]
180 : (status?.colorClass ?? "text-muted-foreground"),
181 );
182 const content = (
183 <>
184 <ThreadPullRequestBadgeIcon icon={badge?.kind ?? "pull-request"} />
185 {iconOnly ? null : isStack ? badge.layers : linkedCount !== null ? `+${linkedCount}` : number}
186 </>
187 );
188 return (
189 <Tooltip>
190 <TooltipTrigger
191 render={
192 isStack ? (
193 <InlineButton
194 className={className}
195 aria-label={label}
196 onPointerDown={(event) => event.stopPropagation()}
197 onClick={(event) => {
198 event.preventDefault();
199 event.stopPropagation();
200 onOpenStack();
201 }}
202 />
203 ) : (
204 <a
205 href={url}
206 target="_blank"
207 rel="noopener noreferrer"
208 className={className}
209 aria-label={label}
210 onPointerDown={(event) => event.stopPropagation()}
211 onClick={onOpenPullRequest}
212 />
213 )
214 }
215 >
216 {content}
217 </TooltipTrigger>
218 <TooltipPopup side="top">{label}</TooltipPopup>
219 </Tooltip>
220 );
221}
222
223/**
224 * A miniature of the pull-requests panel for the thread tooltip: same order, same indentation,
225 * so the hover answers "what is in here" without opening the surface.
226 */
227export function ThreadPullRequestsMiniList({
228 pullRequests,
229}: {
230 pullRequests: ReadonlyArray<ThreadPullRequestLink>;
231}) {
232 const lines = useMemo(
233 () =>
234 pullRequestListLines(resolveThreadPullRequestChains(visibleThreadPullRequests(pullRequests))),
235 [pullRequests],
236 );
237 if (lines.length === 0) return null;
238 return (
239 <ul className="flex flex-col gap-1">
240 {lines.map((line) => {
241 const snapshot = line.link.snapshot;
242 const presentation =
243 snapshot === null
244 ? null
245 : resolvePullRequestState({ state: snapshot.state, isDraft: snapshot.isDraft });
246 return (
247 <li
248 key={`${line.link.host}/${line.link.repository}#${line.link.number}`}
249 className="flex min-w-0 items-center gap-2"
250 // Capped like the panel: past a few layers the indent only repeats "still in the
251 // stack", and sixteen of them would walk the titles off the popover.
252 style={{ paddingLeft: `${Math.min(line.depth, 3) * 0.75}rem` }}
253 >
254 {presentation ? (
255 <presentation.Icon
256 aria-hidden
257 className={cn("size-3 shrink-0", presentation.toneClassName)}
258 />
259 ) : (
260 <GitPullRequestArrowIcon
261 aria-hidden
262 className="size-3 shrink-0 stroke-muted-foreground"
263 />
264 )}
265 <span className="shrink-0 font-mono tabular-nums">#{line.link.number}</span>
266 <span className="min-w-0 truncate text-foreground/75">
267 {snapshot?.title ?? line.link.repository}
268 </span>
269 {line.stack ? (
270 <span className="ml-auto shrink-0 pl-1 text-[10px]">
271 {line.stack.kind === "native" ? "stack" : "chain"} · {line.stack.size}
272 </span>
273 ) : null}
274 </li>
275 );
276 })}
277 </ul>
278 );
279}
280
281/** The ink each pull-request state wears in the sidebar, shared by the number and stack badges. */
282const PR_STATE_COLOR_CLASS: Record<ThreadPullRequestBadge["state"], string> = {
283 open: "text-emerald-600 dark:text-emerald-300/90",
284 merged: "text-violet-600 dark:text-violet-300/90",
285 closed: "text-red-600 dark:text-red-300/90",
286 draft: "text-zinc-500 dark:text-zinc-400/80",
287};
288
289export function settledPrHoverColorClass(
290 state: NonNullable<ThreadPr>["state"],
291 isDraft = false,
292): string {
293 switch (state) {
294 case "open":
295 if (isDraft) {
296 return "group-hover/sidebar-row:text-zinc-500 dark:group-hover/sidebar-row:text-zinc-400/80";
297 }
298 return "group-hover/sidebar-row:text-emerald-600 dark:group-hover/sidebar-row:text-emerald-300/90";
299 case "merged":
300 return "group-hover/sidebar-row:text-violet-600 dark:group-hover/sidebar-row:text-violet-300/90";
301 case "closed":
302 return "group-hover/sidebar-row:text-red-600 dark:group-hover/sidebar-row:text-red-300/90";
303 }
304}
305
306export function prStatusIndicator(
307 pr: ThreadPr,
308 provider: VcsStatusResult["sourceControlProvider"] | null | undefined,
309): PrStatusIndicator | null {
310 function formatPrState(pr: NonNullable<ThreadPr>): string {
311 if (pr.state === "open" && pr.isDraft === true) return "Draft";
312 return pr.state.charAt(0).toUpperCase() + pr.state.slice(1);
313 }
314
315 function formatPrStatusLead(pr: NonNullable<ThreadPr>, changeRequestShortName: string): string {
316 return `${changeRequestShortName} #${pr.number} - ${formatPrState(pr)}`;
317 }
318 if (!pr) return null;
319 const presentation = resolveChangeRequestPresentation(provider);
320
321 const tooltipLead = formatPrStatusLead(pr, presentation.shortName);
322 const tooltip = `${tooltipLead}: ${pr.title}`;
323
324 if (pr.state === "open") {
325 const isDraft = pr.isDraft === true;
326 return {
327 label: `${presentation.shortName} ${isDraft ? "draft" : "open"}`,
328 colorClass: isDraft
329 ? "text-zinc-500 dark:text-zinc-400/80"
330 : "text-emerald-600 dark:text-emerald-300/90",
331 tooltip,
332 tooltipLead,
333 tooltipTitle: pr.title,
334 url: pr.url,
335 };
336 }
337 if (pr.state === "closed") {
338 return {
339 label: `${presentation.shortName} closed`,
340 colorClass: "text-red-600 dark:text-red-300/90",
341 tooltip,
342 tooltipLead,
343 tooltipTitle: pr.title,
344 url: pr.url,
345 };
346 }
347 if (pr.state === "merged") {
348 return {
349 label: `${presentation.shortName} merged`,
350 colorClass: "text-violet-600 dark:text-violet-300/90",
351 tooltip,
352 tooltipLead,
353 tooltipTitle: pr.title,
354 url: pr.url,
355 };
356 }
357 return null;
358}
359
360export function ChangeRequestStatusIcon({
361 state,
362 isDraft = false,
363 className,
364}: Pick<NonNullable<ThreadPr>, "state"> & {
365 readonly isDraft?: boolean | undefined;
366 readonly className?: string | undefined;
367}) {
368 const presentation = resolvePullRequestState({ state, isDraft });
369 return <presentation.Icon className={className} />;
370}
371
372export function PrStatusTooltipContent({ status }: { status: PrStatusIndicator }) {
373 return (
374 <span className="flex max-w-[min(34rem,calc(100vw-2rem))] items-stretch overflow-hidden whitespace-nowrap">
375 <span className="shrink-0 pr-2 font-medium">{status.tooltipLead}</span>
376 <span className="min-h-4 shrink-0 border-border/70 border-l" aria-hidden="true" />
377 <span className="min-w-0 truncate pl-2">{status.tooltipTitle}</span>
378 </span>
379 );
380}
381
382export function terminalStatusFromRunningIds(
383 runningTerminalIds: ReadonlyArray<string>,
384): TerminalStatusIndicator | null {
385 if (runningTerminalIds.length === 0) {
386 return null;
387 }
388 return {
389 label: "Terminal process running",
390 colorClass: "text-teal-600 dark:text-teal-300/90",
391 pulse: true,
392 };
393}
394
395export function ThreadWorktreeIndicator({
396 thread,
397}: {
398 thread: Pick<SidebarThreadSummary, "id" | "branch" | "worktreePath">;
399}) {
400 const worktreePath = thread.worktreePath?.trim();
401 if (!worktreePath) {
402 return null;
403 }
404
405 const displayPath = formatWorktreePathForDisplay(worktreePath);
406 const tooltip = thread.branch
407 ? `Worktree: ${displayPath} (${thread.branch})`
408 : `Worktree: ${displayPath}`;
409
410 return (
411 <Tooltip>
412 <TooltipTrigger
413 render={
414 <span
415 role="img"
416 aria-label={tooltip}
417 data-testid={`thread-worktree-${thread.id}`}
418 className="inline-flex items-center justify-center"
419 />
420 }
421 >
422 <FolderGit2Icon className="size-3 text-muted-foreground/40" />
423 </TooltipTrigger>
424 <TooltipPopup side="top">{tooltip}</TooltipPopup>
425 </Tooltip>
426 );
427}
428
429export function ThreadStatusLabel({
430 status,
431 compact = false,
432}: {
433 status: ThreadStatusPill;
434 compact?: boolean;
435}) {
436 if (compact) {
437 return (
438 <Tooltip>
439 <TooltipTrigger
440 render={
441 <span
442 aria-label={status.label}
443 className={`inline-flex size-3.5 shrink-0 items-center justify-center ${status.colorClass}`}
444 />
445 }
446 >
447 <span
448 className={`size-[9px] rounded-full ${status.dotClass} ${
449 status.pulse ? "animate-status-pulse" : ""
450 }`}
451 />
452 </TooltipTrigger>
453 <TooltipPopup side="top">{status.label}</TooltipPopup>
454 </Tooltip>
455 );
456 }
457
458 return (
459 <Tooltip>
460 <TooltipTrigger
461 render={
462 <span
463 aria-label={status.label}
464 className={`inline-flex items-center gap-1 text-[10px] ${status.colorClass}`}
465 />
466 }
467 >
468 <span
469 className={`h-1.5 w-1.5 rounded-full ${status.dotClass} ${
470 status.pulse ? "animate-status-pulse" : ""
471 }`}
472 />
473 <span className="hidden md:inline">{status.label}</span>
474 </TooltipTrigger>
475 <TooltipPopup side="top">{status.label}</TooltipPopup>
476 </Tooltip>
477 );
478}
479
480/**
481 * Non-interactive leading status icons for a thread row in compact contexts
482 * like the command palette. Shows the change request state icon (if present) and the
483 * thread status dot, matching the sidebar's leading indicators.
484 */
485export function ThreadRowLeadingStatus({ thread }: { thread: SidebarThreadSummary }) {
486 const threadRef = scopeThreadRef(thread.environmentId, thread.id);
487 const lastVisitedAt = useUiStateStore(
488 (state) => state.threadLastVisitedAtById[scopedThreadKey(threadRef)],
489 );
490 const pullRequest = useLinkedThreadPullRequest(
491 thread.environmentId,
492 thread.linkedPullRequest,
493 true,
494 thread.pullRequests,
495 thread.branchPullRequest,
496 );
497 const pr = pullRequest?.pr ?? null;
498 const prStatus = prStatusIndicator(pr, pullRequest?.sourceControlProvider);
499 const threadStatus = resolveThreadStatusPill({
500 thread: {
501 ...thread,
502 lastVisitedAt,
503 },
504 });
505
506 const supportsMultiplePullRequests = useSupportsMultiplePullRequests(thread.environmentId);
507 const pendingLink =
508 pr === null && supportsMultiplePullRequests
509 ? resolveThreadCurrentPullRequestLink(thread.pullRequests)
510 : null;
511 if (!prStatus && !threadStatus && !pendingLink) {
512 return null;
513 }
514
515 return (
516 <span className="inline-flex shrink-0 items-center gap-1.5">
517 {prStatus && pr ? (
518 <Tooltip>
519 <TooltipTrigger
520 render={
521 <span
522 aria-label={prStatus.tooltip}
523 className={`inline-flex items-center justify-center ${prStatus.colorClass}`}
524 />
525 }
526 >
527 <ChangeRequestStatusIcon state={pr.state} isDraft={pr.isDraft} className="size-3" />
528 </TooltipTrigger>
529 <TooltipPopup side="top">
530 <PrStatusTooltipContent status={prStatus} />
531 </TooltipPopup>
532 </Tooltip>
533 ) : null}
534 {pendingLink ? (
535 <GitPullRequestArrowIcon
536 className="size-3 text-muted-foreground"
537 aria-label={`PR #${pendingLink.number}, status pending`}
538 />
539 ) : null}
540 {threadStatus ? <ThreadStatusLabel status={threadStatus} /> : null}
541 </span>
542 );
543}
544
545/**
546 * Non-interactive trailing status icons for a thread row in compact contexts
547 * like the command palette. Shows a terminal-running indicator and a remote
548 * environment indicator, matching the sidebar's trailing indicators.
549 */
550export function ThreadRowTrailingStatus({ thread }: { thread: SidebarThreadSummary }) {
551 const runningTerminalIds = useThreadRunningTerminalIds({
552 environmentId: thread.environmentId,
553 threadId: thread.id,
554 });
555 const environment = useEnvironment(thread.environmentId);
556 const primaryEnvironmentId = usePrimaryEnvironmentId();
557 // No primary (the hosted app) means every thread is remote, and the machine
558 // glyph is what tells the environments apart.
559 const isRemoteThread = thread.environmentId !== primaryEnvironmentId;
560 const remoteEnvLabel = environment?.label ?? null;
561 const threadEnvironmentLabel = isRemoteThread ? (remoteEnvLabel ?? "Remote") : null;
562 const remoteMachine = resolveEnvironmentMachineKind(environment?.serverConfig ?? null);
563 const terminalStatus = terminalStatusFromRunningIds(runningTerminalIds);
564
565 if (!terminalStatus && !isRemoteThread) {
566 return null;
567 }
568
569 return (
570 <span className="inline-flex shrink-0 items-center gap-1.5">
571 {terminalStatus ? (
572 <Tooltip>
573 <TooltipTrigger
574 render={
575 <span
576 role="img"
577 aria-label={terminalStatus.label}
578 className={`inline-flex items-center justify-center ${terminalStatus.colorClass}`}
579 />
580 }
581 >
582 <TerminalIcon
583 className={`size-3 ${terminalStatus.pulse ? "animate-status-pulse" : ""}`}
584 />
585 </TooltipTrigger>
586 <TooltipPopup side="top">{terminalStatus.label}</TooltipPopup>
587 </Tooltip>
588 ) : null}
589 {isRemoteThread ? (
590 <Tooltip>
591 <TooltipTrigger
592 render={
593 <span
594 aria-label={threadEnvironmentLabel ?? "Remote"}
595 className="inline-flex items-center justify-center"
596 />
597 }
598 >
599 <EnvironmentMachineIcon
600 kind={remoteMachine}
601 className="size-3 text-muted-foreground/60"
602 />
603 </TooltipTrigger>
604 <TooltipPopup side="top">{threadEnvironmentLabel}</TooltipPopup>
605 </Tooltip>
606 ) : null}
607 </span>
608 );
609}