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

ThreadStatusIndicators.tsx

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