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

ThreadStatusIndicators.tsx

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