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

ThreadStatusIndicators.tsx

677 lines21.0 KB

1import {
2 scopeProjectRef,
3 scopedThreadKey,
4 scopeThreadRef,
5} from "@t3tools/client-runtime/environment";
6import { pullRequestDetailToVcsStatus } from "@t3tools/client-runtime/state/pull-requests";
7import type { EnvironmentId, ThreadLinkedPullRequest, VcsStatusResult } from "@t3tools/contracts";
8import { Atom } from "effect/unstable/reactivity";
9import { CloudIcon, FolderGit2Icon, GitPullRequestIcon, TerminalIcon } from "lucide-react";
10import { useMemo } from "react";
11import { appAtomRegistry } from "../rpc/atomRegistry";
12import { useEnvironment, usePrimaryEnvironmentId } from "../state/environments";
13import { useProject } from "../state/entities";
14import { useEnvironmentQuery } from "../state/query";
15import { linkedPullRequestDetailAtom } from "../state/pullRequests";
16import { useThreadRunningTerminalIds } from "../state/terminalSessions";
17import { vcsEnvironment } from "../state/vcs";
18import { useUiStateStore } from "../uiStateStore";
19import { resolveChangeRequestPresentation } from "../sourceControlPresentation";
20import { resolveThreadStatusPill, type ThreadStatusPill } from "./Sidebar.logic";
21import type { SidebarThreadSummary } from "../types";
22import { formatWorktreePathForDisplay } from "../worktreeCleanup";
23import { Tooltip, TooltipPopup, TooltipTrigger } from "./ui/tooltip";
24​
25export interface PrStatusIndicator {
26 label: string;
27 colorClass: string;
28 tooltip: string;
29 tooltipLead: string;
30 tooltipTitle: string;
31 url: string;
33​
34export interface TerminalStatusIndicator {
35 label: "Terminal process running";
36 colorClass: string;
37 pulse: boolean;
39​
40export type ThreadPr = VcsStatusResult["pr"];
41​
42export type ThreadPullRequestRefreshSource = "linked-detail" | "vcs";
43​
44/** Refresh only when the panel has newer state for this thread's own pull request. */
45export function threadPullRequestRefreshSource(input: {
46 readonly panel: {
47 readonly repository: string;
48 readonly number: number;
49 readonly state: NonNullable<ThreadPr>["state"];
50 };
51 readonly thread: {
52 readonly repository: string | null;
53 readonly number: number | null;
54 readonly state: NonNullable<ThreadPr>["state"] | null;
55 readonly linked: boolean;
56 };
57}): ThreadPullRequestRefreshSource | null {
58 if (
59 input.thread.repository?.toLowerCase() !== input.panel.repository.toLowerCase() ||
60 input.thread.number !== input.panel.number ||
61 input.thread.state === input.panel.state
62 ) {
63 return null;
64 }
65 return input.thread.linked ? "linked-detail" : "vcs";
67​
68export interface LinkedThreadPullRequestStatus {
69 readonly pr: NonNullable<ThreadPr>;
70 readonly sourceControlProvider: NonNullable<VcsStatusResult["sourceControlProvider"]>;
72​
73export function useLinkedThreadPullRequest(
74 environmentId: EnvironmentId | null,
75 linkedPullRequest: ThreadLinkedPullRequest | null | undefined,
76): LinkedThreadPullRequestStatus | null {
77 const detail = useEnvironmentQuery(
78 environmentId === null || linkedPullRequest == null
79 ? null
80 : linkedPullRequestDetailAtom({
81 environmentId,
82 input: {
83 projectId: linkedPullRequest.projectId,
84 repository: linkedPullRequest.repository,
85 number: linkedPullRequest.number,
86 },
87 }),
88 ).data;
89​
90 return useMemo(
91 () =>
92 detail === null
93 ? null
94 : {
95 pr: pullRequestDetailToVcsStatus(detail),
96 sourceControlProvider: {
97 kind: detail.provider,
98 name: detail.provider,
99 baseUrl: "",
100 },
101 },
102 [detail],
103 );
105​
106export function settledPrHoverColorClass(state: NonNullable<ThreadPr>["state"]): string {
107 switch (state) {
108 case "open":
109 return "group-hover/v2-row:text-emerald-600 dark:group-hover/v2-row:text-emerald-300/90";
110 case "merged":
111 return "group-hover/v2-row:text-violet-600 dark:group-hover/v2-row:text-violet-300/90";
112 case "closed":
113 return "group-hover/v2-row:text-red-600 dark:group-hover/v2-row:text-red-300/90";
114 }
116​
117export function prStatusIndicator(
118 pr: ThreadPr,
119 provider: VcsStatusResult["sourceControlProvider"] | null | undefined,
120): PrStatusIndicator | null {
121 function formatPrState(state: NonNullable<ThreadPr>["state"]): string {
122 return state.charAt(0).toUpperCase() + state.slice(1);
123 }
124​
125 function formatPrStatusLead(pr: NonNullable<ThreadPr>, changeRequestShortName: string): string {
126 return `${changeRequestShortName} #${pr.number} - ${formatPrState(pr.state)}`;
127 }
128 if (!pr) return null;
129 const presentation = resolveChangeRequestPresentation(provider);
130​
131 const tooltipLead = formatPrStatusLead(pr, presentation.shortName);
132 const tooltip = `${tooltipLead}: ${pr.title}`;
133​
134 if (pr.state === "open") {
135 return {
136 label: `${presentation.shortName} open`,
137 colorClass: "text-emerald-600 dark:text-emerald-300/90",
138 tooltip,
139 tooltipLead,
140 tooltipTitle: pr.title,
141 url: pr.url,
142 };
143 }
144 if (pr.state === "closed") {
145 return {
146 label: `${presentation.shortName} closed`,
147 colorClass: "text-red-600 dark:text-red-300/90",
148 tooltip,
149 tooltipLead,
150 tooltipTitle: pr.title,
151 url: pr.url,
152 };
153 }
154 if (pr.state === "merged") {
155 return {
156 label: `${presentation.shortName} merged`,
157 colorClass: "text-violet-600 dark:text-violet-300/90",
158 tooltip,
159 tooltipLead,
160 tooltipTitle: pr.title,
161 url: pr.url,
162 };
163 }
164 return null;
166​
167export function ChangeRequestStatusIcon({ className }: { className?: string }) {
168 return <GitPullRequestIcon className={className} />;
170​
171export function PrStatusTooltipContent({ status }: { status: PrStatusIndicator }) {
172 return (
173 <span className="flex max-w-[min(34rem,calc(100vw-2rem))] items-stretch overflow-hidden whitespace-nowrap">
174 <span className="shrink-0 pr-2 font-medium">{status.tooltipLead}</span>
175 <span className="min-h-4 shrink-0 border-border/70 border-l" aria-hidden="true" />
176 <span className="min-w-0 truncate pl-2">{status.tooltipTitle}</span>
177 </span>
178 );
180​
181export function resolveThreadPr(input: {
182 threadBranch: string | null;
183 gitStatus: VcsStatusResult | null;
184}): ThreadPr | null {
185 const { threadBranch, gitStatus } = input;
186 if (gitStatus === null) {
187 return null;
188 }
189​
190 if (threadBranch === null || gitStatus.refName !== threadBranch) {
191 return null;
192 }
193​
194 return gitStatus.pr ?? null;
196​
197/**
198 * Parent-held PR snapshot for Sidebar V2. Rows remount when settlement
199 * partitions move them, so terminal PR metadata must live above the row.
200 */
201export interface ThreadChangeRequestSnapshot {
202 readonly branch: string;
203 readonly pr: NonNullable<ThreadPr>;
204 readonly sourceControlProvider: VcsStatusResult["sourceControlProvider"] | undefined;
205 readonly linkedPullRequest?: ThreadLinkedPullRequest;
207​
208export const threadChangeRequestSnapshotsAtom = Atom.make<
209 ReadonlyMap<string, ThreadChangeRequestSnapshot>
210>(new Map()).pipe(Atom.keepAlive, Atom.withLabel("sidebar:thread-change-request-snapshots"));
211​
212function isTerminalChangeRequestState(
213 state: NonNullable<ThreadPr>["state"],
214): state is "merged" | "closed" {
215 return state === "merged" || state === "closed";
217​
218function sourceControlProvidersEqual(
219 left: VcsStatusResult["sourceControlProvider"] | undefined,
220 right: VcsStatusResult["sourceControlProvider"] | undefined,
221): boolean {
222 if (left === right) return true;
223 if (left == null || right == null) return left == null && right == null;
224 return left.kind === right.kind && left.name === right.name && left.baseUrl === right.baseUrl;
226​
227function linkedPullRequestsEqual(
228 left: ThreadLinkedPullRequest | null | undefined,
229 right: ThreadLinkedPullRequest | null | undefined,
230): boolean {
231 if (left == null || right == null) return left == null && right == null;
232 return (
233 left.projectId === right.projectId &&
234 left.repository === right.repository &&
235 left.number === right.number &&
236 left.url === right.url
237 );
239​
240export function threadChangeRequestSnapshotsEqual(
241 left: ThreadChangeRequestSnapshot,
242 right: ThreadChangeRequestSnapshot,
243): boolean {
244 return (
245 left.branch === right.branch &&
246 left.pr.number === right.pr.number &&
247 left.pr.title === right.pr.title &&
248 left.pr.url === right.pr.url &&
249 left.pr.baseRef === right.pr.baseRef &&
250 left.pr.headRef === right.pr.headRef &&
251 left.pr.state === right.pr.state &&
252 (left.pr.updatedAt ?? null) === (right.pr.updatedAt ?? null) &&
253 sourceControlProvidersEqual(left.sourceControlProvider, right.sourceControlProvider) &&
254 linkedPullRequestsEqual(left.linkedPullRequest, right.linkedPullRequest)
255 );
257​
258export function setThreadChangeRequestSnapshot(
259 threadKey: string,
260 snapshot: ThreadChangeRequestSnapshot | null,
261): void {
262 appAtomRegistry.modify(threadChangeRequestSnapshotsAtom, (current) => {
263 const existing = current.get(threadKey);
264 if (snapshot === null) {
265 if (existing === undefined) return [false, current];
266 const next = new Map(current);
267 next.delete(threadKey);
268 return [true, next];
269 }
270 if (existing !== undefined && threadChangeRequestSnapshotsEqual(existing, snapshot)) {
271 return [false, current];
272 }
273 const next = new Map(current);
274 next.set(threadKey, snapshot);
275 return [true, next];
276 });
278​
279/**
280 * Authoritative snapshot update from live VCS status.
281 * - `undefined`: missing status, or a local checkout retaining a terminal PR — leave the map alone
282 * - `null`: no PR (without a retained terminal snapshot), a cleared branch, or a mismatch without a terminal PR — clear
283 * - snapshot: matching branch reports a PR — store/replace
284 */
285export function nextThreadChangeRequestSnapshot(input: {
286 threadBranch: string | null;
287 gitStatus: VcsStatusResult | null;
288 snapshot: ThreadChangeRequestSnapshot | null | undefined;
289 retainTerminalOnBranchMismatch: boolean;
290 linkedPullRequest?: ThreadLinkedPullRequest | null | undefined;
291 linkedPullRequestStatus?: LinkedThreadPullRequestStatus | null | undefined;
292}): ThreadChangeRequestSnapshot | null | undefined {
293 const {
294 threadBranch,
295 gitStatus,
296 snapshot,
297 retainTerminalOnBranchMismatch,
298 linkedPullRequest,
299 linkedPullRequestStatus,
300 } = input;
301 if (linkedPullRequest != null) {
302 if (linkedPullRequestStatus === null || linkedPullRequestStatus === undefined) {
303 return linkedPullRequestsEqual(snapshot?.linkedPullRequest, linkedPullRequest)
304 ? undefined
305 : null;
306 }
307 return {
308 branch: threadBranch ?? linkedPullRequestStatus.pr.headRef,
309 pr: linkedPullRequestStatus.pr,
310 sourceControlProvider: linkedPullRequestStatus.sourceControlProvider,
311 linkedPullRequest,
312 };
313 }
314 if (gitStatus === null) {
315 return snapshot?.linkedPullRequest === undefined ? undefined : null;
316 }
317 if (threadBranch === null) {
318 return null;
319 }
320 if (gitStatus.refName !== threadBranch) {
321 return retainTerminalOnBranchMismatch &&
322 snapshot != null &&
323 snapshot.linkedPullRequest === undefined &&
324 isTerminalChangeRequestState(snapshot.pr.state)
325 ? undefined
326 : null;
327 }
328 if (gitStatus.pr == null) {
329 if (
330 retainTerminalOnBranchMismatch &&
331 snapshot != null &&
332 snapshot.linkedPullRequest === undefined &&
333 isTerminalChangeRequestState(snapshot.pr.state)
334 ) {
335 return undefined;
336 }
337 return null;
338 }
339 return {
340 branch: threadBranch,
341 pr: gitStatus.pr,
342 sourceControlProvider: gitStatus.sourceControlProvider,
343 };
345​
346/**
347 * Live PR when the checkout matches the thread branch; otherwise, for local
348 * checkouts only, a cached merged/closed PR for the thread. Local thread
349 * metadata follows the shared checkout, so the cached branch intentionally
350 * survives that metadata changing to the newly checked-out branch. Open PRs
351 * are never retained — their state can still change.
352 */
353export function resolveDisplayedThreadPr(input: {
354 threadBranch: string | null;
355 gitStatus: VcsStatusResult | null;
356 snapshot: ThreadChangeRequestSnapshot | null | undefined;
357 retainTerminalOnBranchMismatch: boolean;
358 linkedPullRequest?: ThreadLinkedPullRequest | null | undefined;
359 linkedPullRequestStatus?: LinkedThreadPullRequestStatus | null | undefined;
360}): ThreadPr | null {
361 const {
362 threadBranch,
363 gitStatus,
364 snapshot,
365 retainTerminalOnBranchMismatch,
366 linkedPullRequest,
367 linkedPullRequestStatus,
368 } = input;
369 if (linkedPullRequest != null) {
370 return (
371 linkedPullRequestStatus?.pr ??
372 (linkedPullRequestsEqual(snapshot?.linkedPullRequest, linkedPullRequest)
373 ? (snapshot?.pr ?? null)
374 : null)
375 );
376 }
377 if (
378 threadBranch !== null &&
379 gitStatus !== null &&
380 gitStatus.refName === threadBranch &&
381 gitStatus.pr != null
382 ) {
383 return gitStatus.pr;
384 }
385​
386 if (
387 threadBranch !== null &&
388 retainTerminalOnBranchMismatch &&
389 snapshot != null &&
390 snapshot.linkedPullRequest === undefined &&
391 isTerminalChangeRequestState(snapshot.pr.state)
392 ) {
393 return snapshot.pr;
394 }
395​
396 return null;
398​
399export function resolveDisplayedThreadPrProvider(input: {
400 threadBranch: string | null;
401 gitStatus: VcsStatusResult | null;
402 snapshot: ThreadChangeRequestSnapshot | null | undefined;
403 retainTerminalOnBranchMismatch: boolean;
404 linkedPullRequest?: ThreadLinkedPullRequest | null | undefined;
405 linkedPullRequestStatus?: LinkedThreadPullRequestStatus | null | undefined;
406}): VcsStatusResult["sourceControlProvider"] | undefined {
407 const {
408 threadBranch,
409 gitStatus,
410 snapshot,
411 retainTerminalOnBranchMismatch,
412 linkedPullRequest,
413 linkedPullRequestStatus,
414 } = input;
415 if (linkedPullRequest != null) {
416 return (
417 linkedPullRequestStatus?.sourceControlProvider ??
418 (linkedPullRequestsEqual(snapshot?.linkedPullRequest, linkedPullRequest)
419 ? snapshot?.sourceControlProvider
420 : undefined)
421 );
422 }
423 if (
424 threadBranch !== null &&
425 gitStatus !== null &&
426 gitStatus.refName === threadBranch &&
427 gitStatus.pr != null
428 ) {
429 return gitStatus.sourceControlProvider;
430 }
431​
432 if (
433 threadBranch !== null &&
434 retainTerminalOnBranchMismatch &&
435 snapshot != null &&
436 snapshot.linkedPullRequest === undefined &&
437 isTerminalChangeRequestState(snapshot.pr.state)
438 ) {
439 return snapshot.sourceControlProvider;
440 }
441​
442 return undefined;
444​
445export function terminalStatusFromRunningIds(
446 runningTerminalIds: ReadonlyArray<string>,
447): TerminalStatusIndicator | null {
448 if (runningTerminalIds.length === 0) {
449 return null;
450 }
451 return {
452 label: "Terminal process running",
453 colorClass: "text-teal-600 dark:text-teal-300/90",
454 pulse: true,
455 };
457​
458export function ThreadWorktreeIndicator({
459 thread,
460}: {
461 thread: Pick<SidebarThreadSummary, "id" | "branch" | "worktreePath">;
462}) {
463 const worktreePath = thread.worktreePath?.trim();
464 if (!worktreePath) {
465 return null;
466 }
467​
468 const displayPath = formatWorktreePathForDisplay(worktreePath);
469 const tooltip = thread.branch
470 ? `Worktree: ${displayPath} (${thread.branch})`
471 : `Worktree: ${displayPath}`;
472​
473 return (
474 <Tooltip>
475 <TooltipTrigger
476 render={
477 <span
478 role="img"
479 aria-label={tooltip}
480 data-testid={`thread-worktree-${thread.id}`}
481 className="inline-flex items-center justify-center"
482 />
483 }
484 >
485 <FolderGit2Icon className="size-3 text-muted-foreground/40" />
486 </TooltipTrigger>
487 <TooltipPopup side="top">{tooltip}</TooltipPopup>
488 </Tooltip>
489 );
491​
492export function ThreadStatusLabel({
493 status,
494 compact = false,
495}: {
496 status: ThreadStatusPill;
497 compact?: boolean;
498}) {
499 if (compact) {
500 return (
501 <Tooltip>
502 <TooltipTrigger
503 render={
504 <span
505 aria-label={status.label}
506 className={`inline-flex size-3.5 shrink-0 items-center justify-center ${status.colorClass}`}
507 />
508 }
509 >
510 <span
511 className={`size-[9px] rounded-full ${status.dotClass} ${
512 status.pulse ? "animate-status-pulse" : ""
513 }`}
514 />
515 </TooltipTrigger>
516 <TooltipPopup side="top">{status.label}</TooltipPopup>
517 </Tooltip>
518 );
519 }
520​
521 return (
522 <Tooltip>
523 <TooltipTrigger
524 render={
525 <span
526 aria-label={status.label}
527 className={`inline-flex items-center gap-1 text-[10px] ${status.colorClass}`}
528 />
529 }
530 >
531 <span
532 className={`h-1.5 w-1.5 rounded-full ${status.dotClass} ${
533 status.pulse ? "animate-status-pulse" : ""
534 }`}
535 />
536 <span className="hidden md:inline">{status.label}</span>
537 </TooltipTrigger>
538 <TooltipPopup side="top">{status.label}</TooltipPopup>
539 </Tooltip>
540 );
542​
543/**
544 * Non-interactive leading status icons for a thread row in compact contexts
545 * like the command palette. Shows the change request state icon (if present) and the
546 * thread status dot, matching the sidebar's leading indicators.
547 */
548export function ThreadRowLeadingStatus({ thread }: { thread: SidebarThreadSummary }) {
549 const threadRef = scopeThreadRef(thread.environmentId, thread.id);
550 const lastVisitedAt = useUiStateStore(
551 (state) => state.threadLastVisitedAtById[scopedThreadKey(threadRef)],
552 );
553 const threadProject = useProject(
554 useMemo(
555 () => scopeProjectRef(thread.environmentId, thread.projectId),
556 [thread.environmentId, thread.projectId],
557 ),
558 );
559 const threadProjectCwd = threadProject?.workspaceRoot ?? null;
560 const gitCwd = thread.worktreePath ?? threadProjectCwd;
561 const linkedPullRequest = useLinkedThreadPullRequest(
562 thread.environmentId,
563 thread.linkedPullRequest,
564 );
565 const gitStatus = useEnvironmentQuery(
566 thread.linkedPullRequest == null &&
567 (thread.branch != null || thread.worktreePath !== null) &&
568 gitCwd !== null
569 ? vcsEnvironment.status({
570 environmentId: thread.environmentId,
571 input: { cwd: gitCwd },
572 })
573 : null,
574 );
575 const pr =
576 thread.linkedPullRequest == null
577 ? resolveThreadPr({ threadBranch: thread.branch, gitStatus: gitStatus.data })
578 : (linkedPullRequest?.pr ?? null);
579 const prStatus = prStatusIndicator(
580 pr,
581 linkedPullRequest?.sourceControlProvider ?? gitStatus.data?.sourceControlProvider,
582 );
583 const threadStatus = resolveThreadStatusPill({
584 thread: {
585 ...thread,
586 lastVisitedAt,
587 },
588 });
589​
590 if (!prStatus && !threadStatus) {
591 return null;
592 }
593​
594 return (
595 <span className="inline-flex shrink-0 items-center gap-1.5">
596 {prStatus ? (
597 <Tooltip>
598 <TooltipTrigger
599 render={
600 <span
601 aria-label={prStatus.tooltip}
602 className={`inline-flex items-center justify-center ${prStatus.colorClass}`}
603 />
604 }
605 >
606 <ChangeRequestStatusIcon className="size-3" />
607 </TooltipTrigger>
608 <TooltipPopup side="top">
609 <PrStatusTooltipContent status={prStatus} />
610 </TooltipPopup>
611 </Tooltip>
612 ) : null}
613 {threadStatus ? <ThreadStatusLabel status={threadStatus} /> : null}
614 </span>
615 );
617​
618/**
619 * Non-interactive trailing status icons for a thread row in compact contexts
620 * like the command palette. Shows a terminal-running indicator and a remote
621 * environment indicator, matching the sidebar's trailing indicators.
622 */
623export function ThreadRowTrailingStatus({ thread }: { thread: SidebarThreadSummary }) {
624 const runningTerminalIds = useThreadRunningTerminalIds({
625 environmentId: thread.environmentId,
626 threadId: thread.id,
627 });
628 const environment = useEnvironment(thread.environmentId);
629 const primaryEnvironmentId = usePrimaryEnvironmentId();
630 const isRemoteThread =
631 primaryEnvironmentId !== null && thread.environmentId !== primaryEnvironmentId;
632 const remoteEnvLabel = environment?.label ?? null;
633 const threadEnvironmentLabel = isRemoteThread ? (remoteEnvLabel ?? "Remote") : null;
634 const terminalStatus = terminalStatusFromRunningIds(runningTerminalIds);
635​
636 if (!terminalStatus && !isRemoteThread) {
637 return null;
638 }
639​
640 return (
641 <span className="inline-flex shrink-0 items-center gap-1.5">
642 {terminalStatus ? (
643 <Tooltip>
644 <TooltipTrigger
645 render={
646 <span
647 role="img"
648 aria-label={terminalStatus.label}
649 className={`inline-flex items-center justify-center ${terminalStatus.colorClass}`}
650 />
651 }
652 >
653 <TerminalIcon
654 className={`size-3 ${terminalStatus.pulse ? "animate-status-pulse" : ""}`}
655 />
656 </TooltipTrigger>
657 <TooltipPopup side="top">{terminalStatus.label}</TooltipPopup>
658 </Tooltip>
659 ) : null}
660 {isRemoteThread ? (
661 <Tooltip>
662 <TooltipTrigger
663 render={
664 <span
665 aria-label={threadEnvironmentLabel ?? "Remote"}
666 className="inline-flex items-center justify-center"
667 />
668 }
669 >
670 <CloudIcon className="size-3 text-muted-foreground/60" />
671 </TooltipTrigger>
672 <TooltipPopup side="top">{threadEnvironmentLabel}</TooltipPopup>
673 </Tooltip>
674 ) : null}
675 </span>
676 );