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