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