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

ThreadStatusIndicators.tsx

683 lines21.3 KB

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