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 sourceControlProvidersEqual(left.sourceControlProvider, right.sourceControlProvider)
173 );
174}
175
176export function setThreadChangeRequestSnapshot(
177 threadKey: string,
178 snapshot: ThreadChangeRequestSnapshot | null,
179): void {
180 appAtomRegistry.modify(threadChangeRequestSnapshotsAtom, (current) => {
181 const existing = current.get(threadKey);
182 if (snapshot === null) {
183 if (existing === undefined) return [false, current];
184 const next = new Map(current);
185 next.delete(threadKey);
186 return [true, next];
187 }
188 if (existing !== undefined && threadChangeRequestSnapshotsEqual(existing, snapshot)) {
189 return [false, current];
190 }
191 const next = new Map(current);
192 next.set(threadKey, snapshot);
193 return [true, next];
194 });
195}
196
197/**
198 * Authoritative snapshot update from live VCS status.
199 * - `undefined`: missing status, or a local checkout retaining a terminal PR — leave the map alone
200 * - `null`: no PR (without a retained terminal snapshot), a cleared branch, or a mismatch without a terminal PR — clear
201 * - snapshot: matching branch reports a PR — store/replace
202 */
203export function nextThreadChangeRequestSnapshot(input: {
204 threadBranch: string | null;
205 gitStatus: VcsStatusResult | null;
206 snapshot: ThreadChangeRequestSnapshot | null | undefined;
207 retainTerminalOnBranchMismatch: boolean;
208}): ThreadChangeRequestSnapshot | null | undefined {
209 const { threadBranch, gitStatus, snapshot, retainTerminalOnBranchMismatch } = input;
210 if (gitStatus === null) {
211 return undefined;
212 }
213 if (threadBranch === null) {
214 return null;
215 }
216 if (gitStatus.refName !== threadBranch) {
217 return retainTerminalOnBranchMismatch &&
218 snapshot != null &&
219 isTerminalChangeRequestState(snapshot.pr.state)
220 ? undefined
221 : null;
222 }
223 if (gitStatus.pr == null) {
224 if (
225 retainTerminalOnBranchMismatch &&
226 snapshot != null &&
227 isTerminalChangeRequestState(snapshot.pr.state)
228 ) {
229 return undefined;
230 }
231 return null;
232 }
233 return {
234 branch: threadBranch,
235 pr: gitStatus.pr,
236 sourceControlProvider: gitStatus.sourceControlProvider,
237 };
238}
239
240/**
241 * Live PR when the checkout matches the thread branch; otherwise, for local
242 * checkouts only, a cached merged/closed PR for the thread. Local thread
243 * metadata follows the shared checkout, so the cached branch intentionally
244 * survives that metadata changing to the newly checked-out branch. Open PRs
245 * are never retained — their state can still change.
246 */
247export function resolveDisplayedThreadPr(input: {
248 threadBranch: string | null;
249 gitStatus: VcsStatusResult | null;
250 snapshot: ThreadChangeRequestSnapshot | null | undefined;
251 retainTerminalOnBranchMismatch: boolean;
252}): ThreadPr | null {
253 const { threadBranch, gitStatus, snapshot, retainTerminalOnBranchMismatch } = input;
254 if (
255 threadBranch !== null &&
256 gitStatus !== null &&
257 gitStatus.refName === threadBranch &&
258 gitStatus.pr != null
259 ) {
260 return gitStatus.pr;
261 }
262
263 if (
264 threadBranch !== null &&
265 retainTerminalOnBranchMismatch &&
266 snapshot != null &&
267 isTerminalChangeRequestState(snapshot.pr.state)
268 ) {
269 return snapshot.pr;
270 }
271
272 return null;
273}
274
275export function resolveDisplayedThreadPrProvider(input: {
276 threadBranch: string | null;
277 gitStatus: VcsStatusResult | null;
278 snapshot: ThreadChangeRequestSnapshot | null | undefined;
279 retainTerminalOnBranchMismatch: boolean;
280}): VcsStatusResult["sourceControlProvider"] | undefined {
281 const { threadBranch, gitStatus, snapshot, retainTerminalOnBranchMismatch } = input;
282 if (
283 threadBranch !== null &&
284 gitStatus !== null &&
285 gitStatus.refName === threadBranch &&
286 gitStatus.pr != null
287 ) {
288 return gitStatus.sourceControlProvider;
289 }
290
291 if (
292 threadBranch !== null &&
293 retainTerminalOnBranchMismatch &&
294 snapshot != null &&
295 isTerminalChangeRequestState(snapshot.pr.state)
296 ) {
297 return snapshot.sourceControlProvider;
298 }
299
300 return undefined;
301}
302
303export function terminalStatusFromRunningIds(
304 runningTerminalIds: ReadonlyArray<string>,
305): TerminalStatusIndicator | null {
306 if (runningTerminalIds.length === 0) {
307 return null;
308 }
309 return {
310 label: "Terminal process running",
311 colorClass: "text-teal-600 dark:text-teal-300/90",
312 pulse: true,
313 };
314}
315
316export function ThreadWorktreeIndicator({
317 thread,
318}: {
319 thread: Pick<SidebarThreadSummary, "id" | "branch" | "worktreePath">;
320}) {
321 const worktreePath = thread.worktreePath?.trim();
322 if (!worktreePath) {
323 return null;
324 }
325
326 const displayPath = formatWorktreePathForDisplay(worktreePath);
327 const tooltip = thread.branch
328 ? `Worktree: ${displayPath} (${thread.branch})`
329 : `Worktree: ${displayPath}`;
330
331 return (
332 <Tooltip>
333 <TooltipTrigger
334 render={
335 <span
336 role="img"
337 aria-label={tooltip}
338 data-testid={`thread-worktree-${thread.id}`}
339 className="inline-flex items-center justify-center"
340 />
341 }
342 >
343 <FolderGit2Icon className="size-3 text-muted-foreground/40" />
344 </TooltipTrigger>
345 <TooltipPopup side="top">{tooltip}</TooltipPopup>
346 </Tooltip>
347 );
348}
349
350export function ThreadStatusLabel({
351 status,
352 compact = false,
353}: {
354 status: ThreadStatusPill;
355 compact?: boolean;
356}) {
357 if (compact) {
358 return (
359 <Tooltip>
360 <TooltipTrigger
361 render={
362 <span
363 aria-label={status.label}
364 className={`inline-flex size-3.5 shrink-0 items-center justify-center ${status.colorClass}`}
365 />
366 }
367 >
368 <span
369 className={`size-[9px] rounded-full ${status.dotClass} ${
370 status.pulse ? "animate-status-pulse" : ""
371 }`}
372 />
373 </TooltipTrigger>
374 <TooltipPopup side="top">{status.label}</TooltipPopup>
375 </Tooltip>
376 );
377 }
378
379 return (
380 <Tooltip>
381 <TooltipTrigger
382 render={
383 <span
384 aria-label={status.label}
385 className={`inline-flex items-center gap-1 text-[10px] ${status.colorClass}`}
386 />
387 }
388 >
389 <span
390 className={`h-1.5 w-1.5 rounded-full ${status.dotClass} ${
391 status.pulse ? "animate-status-pulse" : ""
392 }`}
393 />
394 <span className="hidden md:inline">{status.label}</span>
395 </TooltipTrigger>
396 <TooltipPopup side="top">{status.label}</TooltipPopup>
397 </Tooltip>
398 );
399}
400
401/**
402 * Non-interactive leading status icons for a thread row in compact contexts
403 * like the command palette. Shows the change request state icon (if present) and the
404 * thread status dot, matching the sidebar's leading indicators.
405 */
406export function ThreadRowLeadingStatus({ thread }: { thread: SidebarThreadSummary }) {
407 const threadRef = scopeThreadRef(thread.environmentId, thread.id);
408 const lastVisitedAt = useUiStateStore(
409 (state) => state.threadLastVisitedAtById[scopedThreadKey(threadRef)],
410 );
411 const threadProject = useProject(
412 useMemo(
413 () => scopeProjectRef(thread.environmentId, thread.projectId),
414 [thread.environmentId, thread.projectId],
415 ),
416 );
417 const threadProjectCwd = threadProject?.workspaceRoot ?? null;
418 const gitCwd = thread.worktreePath ?? threadProjectCwd;
419 const gitStatus = useEnvironmentQuery(
420 (thread.branch != null || thread.worktreePath !== null) && gitCwd !== null
421 ? vcsEnvironment.status({
422 environmentId: thread.environmentId,
423 input: { cwd: gitCwd },
424 })
425 : null,
426 );
427 const pr = resolveThreadPr({
428 threadBranch: thread.branch,
429 gitStatus: gitStatus.data,
430 });
431 const prStatus = prStatusIndicator(pr, gitStatus.data?.sourceControlProvider);
432 const threadStatus = resolveThreadStatusPill({
433 thread: {
434 ...thread,
435 lastVisitedAt,
436 },
437 });
438
439 if (!prStatus && !threadStatus) {
440 return null;
441 }
442
443 return (
444 <span className="inline-flex shrink-0 items-center gap-1.5">
445 {prStatus ? (
446 <Tooltip>
447 <TooltipTrigger
448 render={
449 <span
450 aria-label={prStatus.tooltip}
451 className={`inline-flex items-center justify-center ${prStatus.colorClass}`}
452 />
453 }
454 >
455 <ChangeRequestStatusIcon className="size-3" />
456 </TooltipTrigger>
457 <TooltipPopup side="top">
458 <PrStatusTooltipContent status={prStatus} />
459 </TooltipPopup>
460 </Tooltip>
461 ) : null}
462 {threadStatus ? <ThreadStatusLabel status={threadStatus} /> : null}
463 </span>
464 );
465}
466
467/**
468 * Non-interactive trailing status icons for a thread row in compact contexts
469 * like the command palette. Shows a terminal-running indicator and a remote
470 * environment indicator, matching the sidebar's trailing indicators.
471 */
472export function ThreadRowTrailingStatus({ thread }: { thread: SidebarThreadSummary }) {
473 const runningTerminalIds = useThreadRunningTerminalIds({
474 environmentId: thread.environmentId,
475 threadId: thread.id,
476 });
477 const environment = useEnvironment(thread.environmentId);
478 const primaryEnvironmentId = usePrimaryEnvironmentId();
479 const isRemoteThread =
480 primaryEnvironmentId !== null && thread.environmentId !== primaryEnvironmentId;
481 const remoteEnvLabel = environment?.label ?? null;
482 const threadEnvironmentLabel = isRemoteThread ? (remoteEnvLabel ?? "Remote") : null;
483 const terminalStatus = terminalStatusFromRunningIds(runningTerminalIds);
484
485 if (!terminalStatus && !isRemoteThread) {
486 return null;
487 }
488
489 return (
490 <span className="inline-flex shrink-0 items-center gap-1.5">
491 {terminalStatus ? (
492 <Tooltip>
493 <TooltipTrigger
494 render={
495 <span
496 role="img"
497 aria-label={terminalStatus.label}
498 className={`inline-flex items-center justify-center ${terminalStatus.colorClass}`}
499 />
500 }
501 >
502 <TerminalIcon
503 className={`size-3 ${terminalStatus.pulse ? "animate-status-pulse" : ""}`}
504 />
505 </TooltipTrigger>
506 <TooltipPopup side="top">{terminalStatus.label}</TooltipPopup>
507 </Tooltip>
508 ) : null}
509 {isRemoteThread ? (
510 <Tooltip>
511 <TooltipTrigger
512 render={
513 <span
514 aria-label={threadEnvironmentLabel ?? "Remote"}
515 className="inline-flex items-center justify-center"
516 />
517 }
518 >
519 <CloudIcon className="size-3 text-muted-foreground/60" />
520 </TooltipTrigger>
521 <TooltipPopup side="top">{threadEnvironmentLabel}</TooltipPopup>
522 </Tooltip>
523 ) : null}
524 </span>
525 );
526}