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

Sidebar.logic.ts

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