Open History to see the last commit
1import * as React from "react";
2import type { SidebarProjectSortOrder, SidebarThreadSortOrder } from "@t3tools/contracts/settings";
3import {
4 getThreadSortTimestamp,
5 sortThreads,
6 toSortableTimestamp,
7 type ThreadSortInput,
8} from "../lib/threadSort";
9import type { SidebarThreadSummary, Thread } from "../types";
10import { cn } from "../lib/utils";
11import { isLatestRunSettled } from "../session-logic";
12import { resolveServerBackedAppStageLabel } from "../branding.logic";
13
14export const THREAD_SELECTION_SAFE_SELECTOR = "[data-thread-item], [data-thread-selection-safe]";
15export const THREAD_JUMP_HINT_SHOW_DELAY_MS = 100;
16// Visible sidebar rows are prewarmed into the thread-detail cache so opening a
17// nearby thread usually reuses an already-hot subscription.
18export const SIDEBAR_THREAD_PREWARM_LIMIT = 10;
19export type SidebarNewThreadEnvMode = "local" | "worktree";
20type SidebarProject = {
21 id: string;
22 title: string;
23 createdAt?: string | undefined;
24 updatedAt?: string | undefined;
25};
26
27export type ThreadTraversalDirection = "previous" | "next";
28
29export function isSidebarSubagentThread(thread: Pick<SidebarThreadSummary, "lineage">): boolean {
30 return thread.lineage.relationshipToParent === "subagent";
31}
32
33export function getSidebarForkParentThreadId(
34 thread: Pick<SidebarThreadSummary, "forkedFrom" | "lineage">,
35) {
36 if (thread.lineage.relationshipToParent !== "fork") {
37 return null;
38 }
39 return thread.forkedFrom?.type === "run"
40 ? thread.forkedFrom.threadId
41 : thread.lineage.parentThreadId;
42}
43
44export interface ThreadStatusPill {
45 label:
46 | "Working"
47 | "Connecting"
48 | "Completed"
49 | "Pending Approval"
50 | "Awaiting Input"
51 | "Plan Ready";
52 colorClass: string;
53 dotClass: string;
54 pulse: boolean;
55}
56
57const THREAD_STATUS_PRIORITY: Record<ThreadStatusPill["label"], number> = {
58 "Pending Approval": 5,
59 "Awaiting Input": 4,
60 Working: 3,
61 Connecting: 3,
62 "Plan Ready": 2,
63 Completed: 1,
64};
65
66type ThreadStatusInput = Pick<
67 SidebarThreadSummary,
68 | "hasActionableProposedPlan"
69 | "hasPendingApprovals"
70 | "hasPendingUserInput"
71 | "interactionMode"
72 | "latestRun"
73 | "runtime"
74> & {
75 lastVisitedAt?: string | undefined;
76};
77
78export interface ThreadJumpHintVisibilityController {
79 sync: (shouldShow: boolean) => void;
80 dispose: () => void;
81}
82
83export function resolveSidebarStageBadgeLabel(input: {
84 primaryServerVersion: string | null | undefined;
85 fallbackStageLabel: string;
86}): string {
87 return resolveServerBackedAppStageLabel(input);
88}
89
90export function createThreadJumpHintVisibilityController(input: {
91 delayMs: number;
92 onVisibilityChange: (visible: boolean) => void;
93 setTimeoutFn?: typeof globalThis.setTimeout;
94 clearTimeoutFn?: typeof globalThis.clearTimeout;
95}): ThreadJumpHintVisibilityController {
96 const setTimeoutFn = input.setTimeoutFn ?? globalThis.setTimeout;
97 const clearTimeoutFn = input.clearTimeoutFn ?? globalThis.clearTimeout;
98 let isVisible = false;
99 let timeoutId: NodeJS.Timeout | null = null;
100
101 const clearPendingShow = () => {
102 if (timeoutId === null) {
103 return;
104 }
105 clearTimeoutFn(timeoutId);
106 timeoutId = null;
107 };
108
109 return {
110 sync: (shouldShow) => {
111 if (!shouldShow) {
112 clearPendingShow();
113 if (isVisible) {
114 isVisible = false;
115 input.onVisibilityChange(false);
116 }
117 return;
118 }
119
120 if (isVisible || timeoutId !== null) {
121 return;
122 }
123
124 timeoutId = setTimeoutFn(() => {
125 timeoutId = null;
126 isVisible = true;
127 input.onVisibilityChange(true);
128 }, input.delayMs);
129 },
130 dispose: () => {
131 clearPendingShow();
132 },
133 };
134}
135
136export function useThreadJumpHintVisibility(): {
137 showThreadJumpHints: boolean;
138 updateThreadJumpHintsVisibility: (shouldShow: boolean) => void;
139} {
140 const [showThreadJumpHints, setShowThreadJumpHints] = React.useState(false);
141 const controllerRef = React.useRef<ThreadJumpHintVisibilityController | null>(null);
142
143 React.useEffect(() => {
144 const controller = createThreadJumpHintVisibilityController({
145 delayMs: THREAD_JUMP_HINT_SHOW_DELAY_MS,
146 onVisibilityChange: (visible) => {
147 setShowThreadJumpHints(visible);
148 },
149 setTimeoutFn: window.setTimeout.bind(window),
150 clearTimeoutFn: window.clearTimeout.bind(window),
151 });
152 controllerRef.current = controller;
153
154 return () => {
155 controller.dispose();
156 controllerRef.current = null;
157 };
158 }, []);
159
160 const updateThreadJumpHintsVisibility = React.useCallback((shouldShow: boolean) => {
161 controllerRef.current?.sync(shouldShow);
162 }, []);
163
164 return {
165 showThreadJumpHints,
166 updateThreadJumpHintsVisibility,
167 };
168}
169
170export function hasUnseenCompletion(thread: ThreadStatusInput): boolean {
171 if (!thread.latestRun?.completedAt) return false;
172 const completedAt = Date.parse(thread.latestRun.completedAt);
173 if (Number.isNaN(completedAt)) return false;
174 if (!thread.lastVisitedAt) return false;
175
176 const lastVisitedAt = Date.parse(thread.lastVisitedAt);
177 if (Number.isNaN(lastVisitedAt)) return true;
178 return completedAt > lastVisitedAt;
179}
180
181export function shouldClearThreadSelectionOnMouseDown(target: HTMLElement | null): boolean {
182 if (target === null) return true;
183 return !target.closest(THREAD_SELECTION_SAFE_SELECTOR);
184}
185
186// A double-click dispatches two `click` events before `dblclick`: the first has
187// `detail === 1`, the second `detail === 2`. The second click must not run the
188// row's single-click navigation, otherwise double-click-to-rename would also
189// navigate. `MouseEvent.detail` is 0 for synthetic/keyboard activations, which
190// still count as a normal single activation.
191export function isTrailingDoubleClick(detail: number): boolean {
192 return detail > 1;
193}
194
195export function resolveSidebarNewThreadEnvMode(input: {
196 requestedEnvMode?: SidebarNewThreadEnvMode;
197 defaultEnvMode: SidebarNewThreadEnvMode;
198}): SidebarNewThreadEnvMode {
199 return input.requestedEnvMode ?? input.defaultEnvMode;
200}
201
202export function resolveSidebarNewThreadSeedContext(input: {
203 projectId: string;
204 defaultEnvMode: SidebarNewThreadEnvMode;
205 activeThread?: {
206 projectId: string;
207 branch: string | null;
208 worktreePath: string | null;
209 } | null;
210 activeDraftThread?: {
211 projectId: string;
212 branch: string | null;
213 worktreePath: string | null;
214 envMode: SidebarNewThreadEnvMode;
215 startFromOrigin: boolean;
216 } | null;
217}): {
218 branch?: string | null;
219 worktreePath?: string | null;
220 envMode: SidebarNewThreadEnvMode;
221 startFromOrigin?: boolean;
222} {
223 if (input.defaultEnvMode === "worktree") {
224 return {
225 envMode: "worktree",
226 };
227 }
228
229 if (input.activeDraftThread?.projectId === input.projectId) {
230 return {
231 branch: input.activeDraftThread.branch,
232 worktreePath: input.activeDraftThread.worktreePath,
233 envMode: input.activeDraftThread.envMode,
234 startFromOrigin: input.activeDraftThread.startFromOrigin,
235 };
236 }
237
238 if (input.activeThread?.projectId === input.projectId) {
239 return {
240 branch: input.activeThread.branch,
241 worktreePath: input.activeThread.worktreePath,
242 envMode: input.activeThread.worktreePath ? "worktree" : "local",
243 };
244 }
245
246 return {
247 envMode: input.defaultEnvMode,
248 };
249}
250
251export function orderItemsByPreferredIds<TItem, TId>(input: {
252 items: readonly TItem[];
253 preferredIds: readonly TId[];
254 getId: (item: TItem) => TId;
255 getPreferenceIds?: (item: TItem) => readonly TId[];
256}): TItem[] {
257 const { getId, getPreferenceIds, items, preferredIds } = input;
258 if (preferredIds.length === 0) {
259 return [...items];
260 }
261
262 const indexesByPreferenceId = new Map<TId, number[]>();
263 for (const [index, item] of items.entries()) {
264 const preferenceIds = getPreferenceIds?.(item) ?? [getId(item)];
265 for (const preferenceId of new Set(preferenceIds)) {
266 const indexes = indexesByPreferenceId.get(preferenceId);
267 if (indexes) {
268 indexes.push(index);
269 } else {
270 indexesByPreferenceId.set(preferenceId, [index]);
271 }
272 }
273 }
274
275 const emittedIndexes = new Set<number>();
276 const ordered = preferredIds.flatMap((id) => {
277 const index = indexesByPreferenceId
278 .get(id)
279 ?.find((candidate) => !emittedIndexes.has(candidate));
280 if (index === undefined) {
281 return [];
282 }
283 emittedIndexes.add(index);
284 return [items[index]!];
285 });
286 const remaining = items.filter((_, index) => !emittedIndexes.has(index));
287 return [...ordered, ...remaining];
288}
289
290export function getVisibleSidebarThreadIds<TThreadId>(
291 renderedProjects: readonly {
292 shouldShowThreadPanel?: boolean;
293 renderedThreadIds: readonly TThreadId[];
294 }[],
295): TThreadId[] {
296 return renderedProjects.flatMap((renderedProject) =>
297 renderedProject.shouldShowThreadPanel === false ? [] : renderedProject.renderedThreadIds,
298 );
299}
300
301export function getSidebarThreadIdsToPrewarm<TThreadId>(
302 visibleThreadIds: readonly TThreadId[],
303 limit = SIDEBAR_THREAD_PREWARM_LIMIT,
304): TThreadId[] {
305 return visibleThreadIds.slice(0, Math.max(0, limit));
306}
307
308export function resolveAdjacentThreadId<T>(input: {
309 threadIds: readonly T[];
310 currentThreadId: T | null;
311 direction: ThreadTraversalDirection;
312}): T | null {
313 const { currentThreadId, direction, threadIds } = input;
314
315 if (threadIds.length === 0) {
316 return null;
317 }
318
319 if (currentThreadId === null) {
320 return direction === "previous" ? (threadIds.at(-1) ?? null) : (threadIds[0] ?? null);
321 }
322
323 const currentIndex = threadIds.indexOf(currentThreadId);
324 if (currentIndex === -1) {
325 return null;
326 }
327
328 if (direction === "previous") {
329 return currentIndex > 0 ? (threadIds[currentIndex - 1] ?? null) : null;
330 }
331
332 return currentIndex < threadIds.length - 1 ? (threadIds[currentIndex + 1] ?? null) : null;
333}
334
335export function isContextMenuPointerDown(input: {
336 button: number;
337 ctrlKey: boolean;
338 isMac: boolean;
339}): boolean {
340 if (input.button === 2) return true;
341 return input.isMac && input.button === 0 && input.ctrlKey;
342}
343
344export function resolveThreadRowClassName(input: {
345 isActive: boolean;
346 isSelected: boolean;
347}): string {
348 const baseClassName =
349 "h-6 w-full translate-x-0 cursor-pointer justify-start px-2 text-left select-none focus-visible:ring-1 focus-visible:ring-inset focus-visible:ring-ring sm:h-7";
350
351 if (input.isSelected && input.isActive) {
352 return cn(
353 baseClassName,
354 "bg-primary/22 text-foreground font-medium hover:bg-primary/26 hover:text-foreground dark:bg-primary/30 dark:hover:bg-primary/36",
355 );
356 }
357
358 if (input.isSelected) {
359 return cn(
360 baseClassName,
361 "bg-primary/15 text-foreground hover:bg-primary/19 hover:text-foreground dark:bg-primary/22 dark:hover:bg-primary/28",
362 );
363 }
364
365 if (input.isActive) {
366 return cn(
367 baseClassName,
368 "bg-accent/85 text-foreground font-medium hover:bg-accent hover:text-foreground dark:bg-accent/55 dark:hover:bg-accent/70",
369 );
370 }
371
372 return cn(baseClassName, "text-muted-foreground hover:bg-accent hover:text-foreground");
373}
374
375export function resolveThreadStatusPill(input: {
376 thread: ThreadStatusInput;
377}): ThreadStatusPill | null {
378 const { thread } = input;
379
380 if (thread.hasPendingApprovals) {
381 return {
382 label: "Pending Approval",
383 colorClass: "text-amber-600 dark:text-amber-300/90",
384 dotClass: "bg-amber-500 dark:bg-amber-300/90",
385 pulse: false,
386 };
387 }
388
389 if (thread.hasPendingUserInput) {
390 return {
391 label: "Awaiting Input",
392 colorClass: "text-indigo-600 dark:text-indigo-300/90",
393 dotClass: "bg-indigo-500 dark:bg-indigo-300/90",
394 pulse: false,
395 };
396 }
397
398 if (thread.runtime?.status === "running" || thread.runtime?.status === "waiting") {
399 return {
400 label: "Working",
401 colorClass: "text-sky-600 dark:text-sky-300/80",
402 dotClass: "bg-sky-500 dark:bg-sky-300/80",
403 pulse: true,
404 };
405 }
406
407 if (
408 thread.runtime?.status === "preparing" ||
409 thread.runtime?.status === "starting" ||
410 thread.runtime?.status === "queued"
411 ) {
412 return {
413 label: "Connecting",
414 colorClass: "text-sky-600 dark:text-sky-300/80",
415 dotClass: "bg-sky-500 dark:bg-sky-300/80",
416 pulse: true,
417 };
418 }
419
420 const hasPlanReadyPrompt =
421 !thread.hasPendingUserInput &&
422 thread.interactionMode === "plan" &&
423 isLatestRunSettled(thread.latestRun, thread.runtime) &&
424 thread.hasActionableProposedPlan;
425 if (hasPlanReadyPrompt) {
426 return {
427 label: "Plan Ready",
428 colorClass: "text-violet-600 dark:text-violet-300/90",
429 dotClass: "bg-violet-500 dark:bg-violet-300/90",
430 pulse: false,
431 };
432 }
433
434 if (hasUnseenCompletion(thread)) {
435 return {
436 label: "Completed",
437 colorClass: "text-emerald-600 dark:text-emerald-300/90",
438 dotClass: "bg-emerald-500 dark:bg-emerald-300/90",
439 pulse: false,
440 };
441 }
442
443 return null;
444}
445
446export function resolveProjectStatusIndicator(
447 statuses: ReadonlyArray<ThreadStatusPill | null>,
448): ThreadStatusPill | null {
449 let highestPriorityStatus: ThreadStatusPill | null = null;
450
451 for (const status of statuses) {
452 if (status === null) continue;
453 if (
454 highestPriorityStatus === null ||
455 THREAD_STATUS_PRIORITY[status.label] > THREAD_STATUS_PRIORITY[highestPriorityStatus.label]
456 ) {
457 highestPriorityStatus = status;
458 }
459 }
460
461 return highestPriorityStatus;
462}
463
464export function getVisibleThreadsForProject<T extends Pick<Thread, "id">>(input: {
465 threads: readonly T[];
466 activeThreadId: T["id"] | undefined;
467 isThreadListExpanded: boolean;
468 previewLimit: number;
469}): {
470 hasHiddenThreads: boolean;
471 visibleThreads: T[];
472 hiddenThreads: T[];
473} {
474 const { activeThreadId, isThreadListExpanded, previewLimit, threads } = input;
475 const hasHiddenThreads = threads.length > previewLimit;
476
477 if (!hasHiddenThreads || isThreadListExpanded) {
478 return {
479 hasHiddenThreads,
480 hiddenThreads: [],
481 visibleThreads: [...threads],
482 };
483 }
484
485 const previewThreads = threads.slice(0, previewLimit);
486 if (!activeThreadId || previewThreads.some((thread) => thread.id === activeThreadId)) {
487 return {
488 hasHiddenThreads: true,
489 hiddenThreads: threads.slice(previewLimit),
490 visibleThreads: previewThreads,
491 };
492 }
493
494 const activeThread = threads.find((thread) => thread.id === activeThreadId);
495 if (!activeThread) {
496 return {
497 hasHiddenThreads: true,
498 hiddenThreads: threads.slice(previewLimit),
499 visibleThreads: previewThreads,
500 };
501 }
502
503 const visibleThreadIds = new Set([...previewThreads, activeThread].map((thread) => thread.id));
504
505 return {
506 hasHiddenThreads: true,
507 hiddenThreads: threads.filter((thread) => !visibleThreadIds.has(thread.id)),
508 visibleThreads: threads.filter((thread) => visibleThreadIds.has(thread.id)),
509 };
510}
511
512export function getFallbackThreadIdAfterDelete<
513 T extends Pick<Thread, "id" | "projectId" | "createdAt" | "updatedAt"> & ThreadSortInput,
514>(input: {
515 threads: readonly T[];
516 deletedThreadId: T["id"];
517 sortOrder: SidebarThreadSortOrder;
518 deletedThreadIds?: ReadonlySet<T["id"]>;
519}): T["id"] | null {
520 const { deletedThreadId, deletedThreadIds, sortOrder, threads } = input;
521 const deletedThread = threads.find((thread) => thread.id === deletedThreadId);
522 if (!deletedThread) {
523 return null;
524 }
525
526 return (
527 sortThreads(
528 threads.filter(
529 (thread) =>
530 thread.projectId === deletedThread.projectId &&
531 thread.id !== deletedThreadId &&
532 !deletedThreadIds?.has(thread.id),
533 ),
534 sortOrder,
535 )[0]?.id ?? null
536 );
537}
538export function getProjectSortTimestamp(
539 project: SidebarProject,
540 projectThreads: readonly ThreadSortInput[],
541 sortOrder: Exclude<SidebarProjectSortOrder, "manual">,
542): number {
543 if (projectThreads.length > 0) {
544 return projectThreads.reduce(
545 (latest, thread) => Math.max(latest, getThreadSortTimestamp(thread, sortOrder)),
546 Number.NEGATIVE_INFINITY,
547 );
548 }
549
550 if (sortOrder === "created_at") {
551 return toSortableTimestamp(project.createdAt) ?? Number.NEGATIVE_INFINITY;
552 }
553 return toSortableTimestamp(project.updatedAt ?? project.createdAt) ?? Number.NEGATIVE_INFINITY;
554}
555
556export function sortProjectsForSidebar<
557 TProject extends SidebarProject,
558 TThread extends Pick<Thread, "projectId" | "createdAt" | "updatedAt"> & ThreadSortInput,
559>(
560 projects: readonly TProject[],
561 threads: readonly TThread[],
562 sortOrder: SidebarProjectSortOrder,
563): TProject[] {
564 if (sortOrder === "manual") {
565 return [...projects];
566 }
567
568 const threadsByProjectId = new Map<string, TThread[]>();
569 for (const thread of threads) {
570 const existing = threadsByProjectId.get(thread.projectId) ?? [];
571 existing.push(thread);
572 threadsByProjectId.set(thread.projectId, existing);
573 }
574
575 return [...projects].toSorted((left, right) => {
576 const rightTimestamp = getProjectSortTimestamp(
577 right,
578 threadsByProjectId.get(right.id) ?? [],
579 sortOrder,
580 );
581 const leftTimestamp = getProjectSortTimestamp(
582 left,
583 threadsByProjectId.get(left.id) ?? [],
584 sortOrder,
585 );
586 const byTimestamp =
587 rightTimestamp === leftTimestamp ? 0 : rightTimestamp > leftTimestamp ? 1 : -1;
588 if (byTimestamp !== 0) return byTimestamp;
589 return left.title.localeCompare(right.title) || left.id.localeCompare(right.id);
590 });
591}