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

Sidebar.logic.ts

544 lines15.7 KB

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