Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

ThreadStatusIndicators.tsx

583 lines19.4 KB

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