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