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