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