Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

Sidebar.logic.ts

525 lines14.6 KB

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