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

ThreadStatusIndicators.tsx

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