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

Sidebar.logic.ts

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