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 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-[10px]">
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
397export function ThreadWorktreeIndicator({
398 thread,
399}: {
400 thread: Pick<SidebarThreadSummary, "id" | "branch" | "worktreePath">;
401}) {
402 const worktreePath = thread.worktreePath?.trim();
403 if (!worktreePath) {
404 return null;
405 }
406
407 const displayPath = formatWorktreePathForDisplay(worktreePath);
408 const tooltip = thread.branch
409 ? `Worktree: ${displayPath} (${thread.branch})`
410 : `Worktree: ${displayPath}`;
411
412 return (
413 <Tooltip>
414 <TooltipTrigger
415 render={
416 <span
417 role="img"
418 aria-label={tooltip}
419 data-testid={`thread-worktree-${thread.id}`}
420 className="inline-flex items-center justify-center"
421 />
422 }
423 >
424 <FolderGit2Icon className="size-3 text-muted-foreground/40" />
425 </TooltipTrigger>
426 <TooltipPopup side="top">{tooltip}</TooltipPopup>
427 </Tooltip>
428 );
429}
430
431export function ThreadStatusLabel({
432 status,
433 compact = false,
434}: {
435 status: ThreadStatusPill;
436 compact?: boolean;
437}) {
438 if (compact) {
439 return (
440 <Tooltip>
441 <TooltipTrigger
442 render={
443 <span
444 aria-label={status.label}
445 className={`inline-flex size-3.5 shrink-0 items-center justify-center ${status.colorClass}`}
446 />
447 }
448 >
449 <span
450 className={`size-[9px] rounded-full ${status.dotClass} ${
451 status.pulse ? "animate-status-pulse" : ""
452 }`}
453 />
454 </TooltipTrigger>
455 <TooltipPopup side="top">{status.label}</TooltipPopup>
456 </Tooltip>
457 );
458 }
459
460 return (
461 <Tooltip>
462 <TooltipTrigger
463 render={
464 <span
465 aria-label={status.label}
466 className={`inline-flex items-center gap-1 text-[10px] ${status.colorClass}`}
467 />
468 }
469 >
470 <span
471 className={`h-1.5 w-1.5 rounded-full ${status.dotClass} ${
472 status.pulse ? "animate-status-pulse" : ""
473 }`}
474 />
475 <span className="hidden md:inline">{status.label}</span>
476 </TooltipTrigger>
477 <TooltipPopup side="top">{status.label}</TooltipPopup>
478 </Tooltip>
479 );
480}
481
482/**
483 * Non-interactive leading status icons for a thread row in compact contexts
484 * like the command palette. Shows the change request state icon (if present) and the
485 * thread status dot, matching the sidebar's leading indicators.
486 */
487export function ThreadRowLeadingStatus({ thread }: { thread: SidebarThreadSummary }) {
488 const threadRef = scopeThreadRef(thread.environmentId, thread.id);
489 const lastVisitedAt = useUiStateStore(
490 (state) => state.threadLastVisitedAtById[scopedThreadKey(threadRef)],
491 );
492 const pullRequest = useLinkedThreadPullRequest(
493 thread.environmentId,
494 thread.linkedPullRequest,
495 true,
496 thread.pullRequests,
497 thread.branchPullRequest,
498 );
499 const pr = pullRequest?.pr ?? null;
500 const prStatus = prStatusIndicator(pr, pullRequest?.sourceControlProvider);
501 const threadStatus = resolveThreadStatusPill({
502 thread: {
503 ...thread,
504 lastVisitedAt,
505 },
506 });
507
508 const supportsMultiplePullRequests = useSupportsMultiplePullRequests(thread.environmentId);
509 const pendingLink =
510 pr === null && supportsMultiplePullRequests
511 ? resolveThreadCurrentPullRequestLink(thread.pullRequests)
512 : null;
513 if (!prStatus && !threadStatus && !pendingLink) {
514 return null;
515 }
516
517 return (
518 <span className="inline-flex shrink-0 items-center gap-1.5">
519 {prStatus && pr ? (
520 <Tooltip>
521 <TooltipTrigger
522 render={
523 <span
524 aria-label={prStatus.tooltip}
525 className={`inline-flex items-center justify-center ${prStatus.colorClass}`}
526 />
527 }
528 >
529 <ChangeRequestStatusIcon state={pr.state} isDraft={pr.isDraft} className="size-3" />
530 </TooltipTrigger>
531 <TooltipPopup side="top">
532 <PrStatusTooltipContent status={prStatus} />
533 </TooltipPopup>
534 </Tooltip>
535 ) : null}
536 {pendingLink ? (
537 <PullRequestGlyph.pullRequest
538 className="size-3 text-muted-foreground"
539 aria-label={`PR #${pendingLink.number}, status pending`}
540 />
541 ) : null}
542 {threadStatus ? <ThreadStatusLabel status={threadStatus} /> : null}
543 </span>
544 );
545}
546
547/**
548 * Non-interactive trailing status icons for a thread row in compact contexts
549 * like the command palette. Shows a terminal-running indicator and a remote
550 * environment indicator, matching the sidebar's trailing indicators.
551 */
552export function ThreadRowTrailingStatus({ thread }: { thread: SidebarThreadSummary }) {
553 const runningTerminalIds = useThreadRunningTerminalIds({
554 environmentId: thread.environmentId,
555 threadId: thread.id,
556 });
557 const environment = useEnvironment(thread.environmentId);
558 const primaryEnvironmentId = usePrimaryEnvironmentId();
559 // No primary (the hosted app) means every thread is remote, and the machine
560 // glyph is what tells the environments apart.
561 const isRemoteThread = thread.environmentId !== primaryEnvironmentId;
562 const remoteEnvLabel = environment?.label ?? null;
563 const threadEnvironmentLabel = isRemoteThread ? (remoteEnvLabel ?? "Remote") : null;
564 const remoteMachine = resolveEnvironmentMachineKind(environment?.serverConfig ?? null);
565 const terminalStatus = terminalStatusFromRunningIds(runningTerminalIds);
566
567 if (!terminalStatus && !isRemoteThread) {
568 return null;
569 }
570
571 return (
572 <span className="inline-flex shrink-0 items-center gap-1.5">
573 {terminalStatus ? (
574 <Tooltip>
575 <TooltipTrigger
576 render={
577 <span
578 role="img"
579 aria-label={terminalStatus.label}
580 className={`inline-flex items-center justify-center ${terminalStatus.colorClass}`}
581 />
582 }
583 >
584 <TerminalIcon
585 className={`size-3 ${terminalStatus.pulse ? "animate-status-pulse" : ""}`}
586 />
587 </TooltipTrigger>
588 <TooltipPopup side="top">{terminalStatus.label}</TooltipPopup>
589 </Tooltip>
590 ) : null}
591 {isRemoteThread ? (
592 <Tooltip>
593 <TooltipTrigger
594 render={
595 <span
596 aria-label={threadEnvironmentLabel ?? "Remote"}
597 className="inline-flex items-center justify-center"
598 />
599 }
600 >
601 <EnvironmentMachineIcon
602 kind={remoteMachine}
603 className="size-3 text-muted-foreground/60"
604 />
605 </TooltipTrigger>
606 <TooltipPopup side="top">{threadEnvironmentLabel}</TooltipPopup>
607 </Tooltip>
608 ) : null}
609 </span>
610 );
611}