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