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

ThreadStatusIndicators.tsx

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