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