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 { useRender } from "@base-ui/react/use-render";
19import { useMemo, type AnimationEvent, type MouseEvent, type ReactElement } from "react";
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/**
195 * The linked-PR badge shared by the sidebar and composer footer. The badge owns what it shows:
196 * the state glyph and number at the meta size, in the state's color. The caller owns the control
197 * it sits in through `render` (an inline link in a sidebar row, a toolbar control in the
198 * composer), and the badge fills in the behavior: a single PR is a link to it, while a stack or
199 * several linked PRs is a button that opens the thread's pull requests tab.
200 */
201export function ThreadPullRequestBadgeControl({
202 render,
203 badge,
204 number,
205 url,
206 status,
207 onOpenList,
208 onOpenPullRequest,
209}: {
210 render: ReactElement<{ render?: useRender.RenderProp }>;
211 badge: ThreadPullRequestBadge | null;
212 number?: number | undefined;
213 url?: string | undefined;
214 status: PrStatusIndicator | null;
215 onOpenList: () => void;
216 onOpenPullRequest: (event: MouseEvent<HTMLElement>) => void;
217}) {
218 const presentation = resolveThreadPullRequestBadgePresentation({ badge, number, url, status });
219 if (presentation === null) return null;
220 return (
221 <PullRequestBadge
222 render={render}
223 presentation={presentation}
224 opensList={badge !== null && (badge.kind === "stack" || badge.others > 0)}
225 url={url}
226 onOpenList={onOpenList}
227 onOpenPullRequest={onOpenPullRequest}
228 />
229 );
230}
231
232function PullRequestBadge({
233 render,
234 presentation,
235 opensList,
236 url,
237 onOpenList,
238 onOpenPullRequest,
239}: {
240 render: ReactElement<{ render?: useRender.RenderProp }>;
241 presentation: NonNullable<ReturnType<typeof resolveThreadPullRequestBadgePresentation>>;
242 opensList: boolean;
243 url: string | undefined;
244 onOpenList: () => void;
245 onOpenPullRequest: (event: MouseEvent<HTMLElement>) => void;
246}) {
247 const onClick = opensList
248 ? (event: MouseEvent<HTMLElement>) => {
249 event.preventDefault();
250 event.stopPropagation();
251 onOpenList();
252 }
253 : onOpenPullRequest;
254 const element = opensList ? (
255 <button type="button" />
256 ) : (
257 <a href={url} target="_blank" rel="noopener noreferrer" />
258 );
259 // The caller's control (InlineButton, ComposerControl) renders as the link or stack button
260 // through its own render prop; useRender merges the badge's behavior into it.
261 const control = useRender({
262 render,
263 props: {
264 render: element,
265 "aria-label": presentation.label,
266 onPointerDown: (event: MouseEvent<HTMLElement>) => event.stopPropagation(),
267 onClick,
268 },
269 });
270 return (
271 <Tooltip>
272 <TooltipTrigger render={control}>
273 <span
274 className={cn("contents font-normal text-xs tabular-nums", presentation.toneClassName)}
275 >
276 <presentation.Icon aria-hidden className="size-3 shrink-0" />
277 {/* An element, not bare text: bare text takes its line box from the control, which
278 inherits the row's size, so beside a text-sm title it sat below the other meta. */}
279 <span>{presentation.text}</span>
280 </span>
281 </TooltipTrigger>
282 <TooltipPopup side="top">{presentation.label}</TooltipPopup>
283 </Tooltip>
284 );
285}
286
287/**
288 * A miniature of the pull-requests panel for the thread tooltip: same order, same indentation,
289 * so the hover answers "what is in here" without opening the surface.
290 */
291export function ThreadPullRequestsMiniList({
292 pullRequests,
293}: {
294 pullRequests: ReadonlyArray<ThreadPullRequestLink>;
295}) {
296 const lines = useMemo(
297 () =>
298 pullRequestListLines(resolveThreadPullRequestChains(visibleThreadPullRequests(pullRequests))),
299 [pullRequests],
300 );
301 if (lines.length === 0) return null;
302 return (
303 <ul className="flex flex-col gap-1">
304 {lines.map((line) => {
305 const snapshot = line.link.snapshot;
306 const presentation =
307 snapshot === null
308 ? null
309 : resolvePullRequestState({ state: snapshot.state, isDraft: snapshot.isDraft });
310 return (
311 <li
312 key={`${line.link.host}/${line.link.repository}#${line.link.number}`}
313 className="flex min-w-0 items-center gap-2"
314 // Capped like the panel: past a few layers the indent only repeats "still in the
315 // stack", and sixteen of them would walk the titles off the popover.
316 style={{ paddingLeft: `${Math.min(line.depth, 3) * 0.75}rem` }}
317 >
318 {presentation ? (
319 <presentation.Icon
320 aria-hidden
321 className={cn("size-3 shrink-0", presentation.toneClassName)}
322 />
323 ) : (
324 <PullRequestGlyph.pullRequest
325 aria-hidden
326 className="size-3 shrink-0 stroke-muted-foreground"
327 />
328 )}
329 <span className="shrink-0 font-mono tabular-nums">#{line.link.number}</span>
330 <span className="min-w-0 truncate text-foreground/75">
331 {snapshot?.title ?? line.link.repository}
332 </span>
333 {line.stack ? (
334 <span className="ml-auto shrink-0 pl-1 text-3xs">
335 {line.stack.kind === "native" ? "stack" : "chain"} · {line.stack.size}
336 </span>
337 ) : null}
338 </li>
339 );
340 })}
341 </ul>
342 );
343}
344
345export function prStatusIndicator(
346 pr: ThreadPr,
347 provider: VcsStatusResult["sourceControlProvider"] | null | undefined,
348): PrStatusIndicator | null {
349 if (!pr) return null;
350 const presentation = resolveChangeRequestPresentation(provider);
351 const state = resolvePullRequestState({ state: pr.state, isDraft: pr.isDraft === true });
352
353 const tooltipLead = `${presentation.shortName} #${pr.number} - ${state.label}`;
354 return {
355 label: `${presentation.shortName} ${state.label.toLowerCase()}`,
356 colorClass: state.toneClassName,
357 Icon: state.Icon,
358 tooltip: `${tooltipLead}: ${pr.title}`,
359 tooltipLead,
360 tooltipTitle: pr.title,
361 url: pr.url,
362 };
363}
364
365export function ChangeRequestStatusIcon({
366 state,
367 isDraft = false,
368 className,
369}: Pick<NonNullable<ThreadPr>, "state"> & {
370 readonly isDraft?: boolean | undefined;
371 readonly className?: string | undefined;
372}) {
373 const presentation = resolvePullRequestState({ state, isDraft });
374 return <presentation.Icon className={className} />;
375}
376
377export function PrStatusTooltipContent({ status }: { status: PrStatusIndicator }) {
378 return (
379 <span className="flex max-w-[min(34rem,calc(100vw-2rem))] items-stretch overflow-hidden whitespace-nowrap">
380 <span className="shrink-0 pr-2 font-medium">{status.tooltipLead}</span>
381 <span className="min-h-4 shrink-0 border-border/70 border-l" aria-hidden="true" />
382 <span className="min-w-0 truncate pl-2">{status.tooltipTitle}</span>
383 </span>
384 );
385}
386
387export function terminalStatusFromRunningIds(
388 runningTerminalIds: ReadonlyArray<string>,
389): TerminalStatusIndicator | null {
390 if (runningTerminalIds.length === 0) {
391 return null;
392 }
393 return {
394 label: "Terminal process running",
395 colorClass: "text-teal-600 dark:text-teal-300/90",
396 pulse: true,
397 };
398}
399
400/** Align newly started pulses with the document clock without a timer or frame loop. */
401export function synchronizeTerminalPulse(event: AnimationEvent<SVGSVGElement>) {
402 if (event.animationName !== "status-pulse") return;
403
404 for (const animation of event.currentTarget.getAnimations()) {
405 if ("animationName" in animation && animation.animationName === "status-pulse") {
406 animation.startTime = 0;
407 }
408 }
409}
410
411export function ThreadWorktreeIndicator({
412 thread,
413}: {
414 thread: Pick<SidebarThreadSummary, "id" | "branch" | "worktreePath">;
415}) {
416 const worktreePath = thread.worktreePath?.trim();
417 if (!worktreePath) {
418 return null;
419 }
420
421 const displayPath = formatWorktreePathForDisplay(worktreePath);
422 const tooltip = thread.branch
423 ? `Worktree: ${displayPath} (${thread.branch})`
424 : `Worktree: ${displayPath}`;
425
426 return (
427 <Tooltip>
428 <TooltipTrigger
429 render={
430 <span
431 role="img"
432 aria-label={tooltip}
433 data-testid={`thread-worktree-${thread.id}`}
434 className="inline-flex items-center justify-center"
435 />
436 }
437 >
438 <FolderGit2Icon className="size-3 text-muted-foreground/40" />
439 </TooltipTrigger>
440 <TooltipPopup side="top">{tooltip}</TooltipPopup>
441 </Tooltip>
442 );
443}
444
445export function ThreadStatusLabel({
446 status,
447 compact = false,
448}: {
449 status: ThreadStatusPill;
450 compact?: boolean;
451}) {
452 if (compact) {
453 return (
454 <Tooltip>
455 <TooltipTrigger
456 render={
457 <span
458 aria-label={status.label}
459 className={`inline-flex size-3.5 shrink-0 items-center justify-center ${status.colorClass}`}
460 />
461 }
462 >
463 <span
464 className={`size-[9px] rounded-full ${status.dotClass} ${
465 status.pulse ? "animate-status-pulse" : ""
466 }`}
467 />
468 </TooltipTrigger>
469 <TooltipPopup side="top">{status.label}</TooltipPopup>
470 </Tooltip>
471 );
472 }
473
474 return (
475 <Tooltip>
476 <TooltipTrigger
477 render={
478 <span
479 aria-label={status.label}
480 className={`inline-flex items-center gap-1 text-3xs ${status.colorClass}`}
481 />
482 }
483 >
484 <span
485 className={`h-1.5 w-1.5 rounded-full ${status.dotClass} ${
486 status.pulse ? "animate-status-pulse" : ""
487 }`}
488 />
489 <span className="hidden md:inline">{status.label}</span>
490 </TooltipTrigger>
491 <TooltipPopup side="top">{status.label}</TooltipPopup>
492 </Tooltip>
493 );
494}
495
496/**
497 * Non-interactive leading status icons for a thread row in compact contexts
498 * like the command palette. Shows the change request state icon (if present) and the
499 * thread status dot, matching the sidebar's leading indicators.
500 */
501export function ThreadRowLeadingStatus({ thread }: { thread: SidebarThreadSummary }) {
502 const threadRef = scopeThreadRef(thread.environmentId, thread.id);
503 const lastVisitedAt = useUiStateStore(
504 (state) => state.threadLastVisitedAtById[scopedThreadKey(threadRef)],
505 );
506 const pullRequest = useLinkedThreadPullRequest(
507 thread.environmentId,
508 thread.linkedPullRequest,
509 true,
510 thread.pullRequests,
511 thread.branchPullRequest,
512 );
513 const pr = pullRequest?.pr ?? null;
514 const prStatus = prStatusIndicator(pr, pullRequest?.sourceControlProvider);
515 const threadStatus = resolveThreadStatusPill({
516 thread: {
517 ...thread,
518 lastVisitedAt,
519 },
520 });
521
522 const supportsMultiplePullRequests = useSupportsMultiplePullRequests(thread.environmentId);
523 const pendingLink =
524 pr === null && supportsMultiplePullRequests
525 ? resolveThreadCurrentPullRequestLink(thread.pullRequests)
526 : null;
527 if (!prStatus && !threadStatus && !pendingLink) {
528 return null;
529 }
530
531 return (
532 <span className="inline-flex shrink-0 items-center gap-1.5">
533 {prStatus && pr ? (
534 <Tooltip>
535 <TooltipTrigger
536 render={
537 <span
538 aria-label={prStatus.tooltip}
539 className={`inline-flex items-center justify-center ${prStatus.colorClass}`}
540 />
541 }
542 >
543 <ChangeRequestStatusIcon state={pr.state} isDraft={pr.isDraft} className="size-3" />
544 </TooltipTrigger>
545 <TooltipPopup side="top">
546 <PrStatusTooltipContent status={prStatus} />
547 </TooltipPopup>
548 </Tooltip>
549 ) : null}
550 {pendingLink ? (
551 <PullRequestGlyph.pullRequest
552 className="size-3 text-muted-foreground"
553 aria-label={`PR #${pendingLink.number}, status pending`}
554 />
555 ) : null}
556 {threadStatus ? <ThreadStatusLabel status={threadStatus} /> : null}
557 </span>
558 );
559}
560
561/**
562 * Non-interactive trailing status icons for a thread row in compact contexts
563 * like the command palette. Shows a terminal-running indicator and a remote
564 * environment indicator, matching the sidebar's trailing indicators.
565 */
566export function ThreadRowTrailingStatus({ thread }: { thread: SidebarThreadSummary }) {
567 const runningTerminalIds = useThreadRunningTerminalIds({
568 environmentId: thread.environmentId,
569 threadId: thread.id,
570 });
571 const environment = useEnvironment(thread.environmentId);
572 const primaryEnvironmentId = usePrimaryEnvironmentId();
573 // No primary (the hosted app) means every thread is remote, and the machine
574 // glyph is what tells the environments apart.
575 const isRemoteThread = thread.environmentId !== primaryEnvironmentId;
576 const remoteEnvLabel = environment?.label ?? null;
577 const threadEnvironmentLabel = isRemoteThread ? (remoteEnvLabel ?? "Remote") : null;
578 const remoteMachine = resolveEnvironmentMachineKind(environment?.serverConfig ?? null);
579 const terminalStatus = terminalStatusFromRunningIds(runningTerminalIds);
580
581 if (!terminalStatus && !isRemoteThread) {
582 return null;
583 }
584
585 return (
586 <span className="inline-flex shrink-0 items-center gap-1.5">
587 {terminalStatus ? (
588 <Tooltip>
589 <TooltipTrigger
590 render={
591 <span
592 role="img"
593 aria-label={terminalStatus.label}
594 className={`inline-flex items-center justify-center ${terminalStatus.colorClass}`}
595 />
596 }
597 >
598 <TerminalIcon
599 className={`size-3 ${terminalStatus.pulse ? "motion-safe:animate-status-pulse" : ""}`}
600 onAnimationStart={synchronizeTerminalPulse}
601 />
602 </TooltipTrigger>
603 <TooltipPopup side="top">{terminalStatus.label}</TooltipPopup>
604 </Tooltip>
605 ) : null}
606 {isRemoteThread ? (
607 <Tooltip>
608 <TooltipTrigger
609 render={
610 <span
611 aria-label={threadEnvironmentLabel ?? "Remote"}
612 className="inline-flex items-center justify-center"
613 />
614 }
615 >
616 <EnvironmentMachineIcon
617 kind={remoteMachine}
618 className="size-3 text-muted-foreground/60"
619 />
620 </TooltipTrigger>
621 <TooltipPopup side="top">{threadEnvironmentLabel}</TooltipPopup>
622 </Tooltip>
623 ) : null}
624 </span>
625 );
626}