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

Sidebar.logic.ts

674 lines19.8 KB

1import * as React from "react";
2import type { ContextMenuItem } from "@t3tools/contracts";
3import type { SidebarProjectSortOrder, SidebarThreadSortOrder } from "@t3tools/contracts/settings";
4import {
5 getThreadSortTimestamp,
6 sortThreads,
7 toSortableTimestamp,
8 type ThreadSortInput,
9} from "../lib/threadSort";
10import type { SidebarThreadSummary, Thread } from "../types";
11import { cn } from "../lib/utils";
12import { isLatestTurnSettled } from "../session-logic";
13import { resolveServerBackedAppStageLabel } from "../branding.logic";
14​
15export const THREAD_SELECTION_SAFE_SELECTOR = "[data-thread-item], [data-thread-selection-safe]";
16export const THREAD_JUMP_HINT_SHOW_DELAY_MS = 100;
17// Visible sidebar rows are prewarmed into the thread-detail cache so opening a
18// nearby thread usually reuses an already-hot subscription.
19export const SIDEBAR_THREAD_PREWARM_LIMIT = 10;
20export type SidebarNewThreadEnvMode = "local" | "worktree";
21type SidebarProject = {
22 id: string;
23 title: string;
24 createdAt?: string | undefined;
25 updatedAt?: string | undefined;
26};
27​
28type ScopedSidebarProject = SidebarProject & {
29 environmentId: string;
30};
31​
32type ScopedSidebarThread = ThreadSortInput & {
33 environmentId: string;
34 projectId: string;
35 archivedAt: string | null;
36};
37​
38export type ThreadTraversalDirection = "previous" | "next";
39​
40export async function archiveSelectedThreadEntries<
41 TEntry extends { readonly threadKey: string },
42 TResult extends { readonly _tag: "Success" | "Failure" },
43>(input: {
44 entries: readonly TEntry[];
45 archive: (entry: TEntry, onArchived: () => void) => Promise<TResult>;
46}): Promise<{
47 archivedThreadKeys: readonly string[];
48 mutationFailure: Extract<TResult, { readonly _tag: "Failure" }> | null;
49 followupFailures: readonly Extract<TResult, { readonly _tag: "Failure" }>[];
50}> {
51 const archivedThreadKeys: string[] = [];
52 const followupFailures: Extract<TResult, { readonly _tag: "Failure" }>[] = [];
53​
54 for (const entry of input.entries) {
55 let didArchive = false;
56 const result = await input.archive(entry, () => {
57 didArchive = true;
58 });
59 if (didArchive || result._tag === "Success") {
60 archivedThreadKeys.push(entry.threadKey);
61 }
62 if (result._tag === "Success") continue;
63 const failure = result as Extract<TResult, { readonly _tag: "Failure" }>;
64 if (didArchive) {
65 followupFailures.push(failure);
66 continue;
67 }
68 return { archivedThreadKeys, mutationFailure: failure, followupFailures };
69 }
70​
71 return { archivedThreadKeys, mutationFailure: null, followupFailures };
73​
74export function buildMultiSelectThreadContextMenuItems(input: {
75 count: number;
76 hasRunningThread: boolean;
77}): readonly ContextMenuItem<"mark-unread" | "archive" | "delete">[] {
78 return [
79 { id: "mark-unread", label: `Mark unread (${input.count})` },
80 {
81 id: "archive",
82 label: `Archive (${input.count})`,
83 disabled: input.hasRunningThread,
84 },
85 { id: "delete", label: `Delete (${input.count})`, destructive: true },
86 ];
88​
89export interface ThreadStatusPill {
90 label:
91 | "Working"
92 | "Connecting"
93 | "Completed"
94 | "Pending Approval"
95 | "Awaiting Input"
96 | "Plan Ready";
97 colorClass: string;
98 dotClass: string;
99 pulse: boolean;
101​
102const THREAD_STATUS_PRIORITY: Record<ThreadStatusPill["label"], number> = {
103 "Pending Approval": 5,
104 "Awaiting Input": 4,
105 Working: 3,
106 Connecting: 3,
107 "Plan Ready": 2,
108 Completed: 1,
109};
110​
111type ThreadStatusInput = Pick<
112 SidebarThreadSummary,
113 | "hasActionableProposedPlan"
114 | "hasPendingApprovals"
115 | "hasPendingUserInput"
116 | "interactionMode"
117 | "latestTurn"
118 | "session"
119> & {
120 lastVisitedAt?: string | undefined;
121};
122​
123export interface ThreadJumpHintVisibilityController {
124 sync: (shouldShow: boolean) => void;
125 dispose: () => void;
127​
128export function resolveSidebarStageBadgeLabel(input: {
129 primaryServerVersion: string | null | undefined;
130 fallbackStageLabel: string;
131}): string {
132 return resolveServerBackedAppStageLabel(input);
134​
135export function createThreadJumpHintVisibilityController(input: {
136 delayMs: number;
137 onVisibilityChange: (visible: boolean) => void;
138 setTimeoutFn?: typeof globalThis.setTimeout;
139 clearTimeoutFn?: typeof globalThis.clearTimeout;
140}): ThreadJumpHintVisibilityController {
141 const setTimeoutFn = input.setTimeoutFn ?? globalThis.setTimeout;
142 const clearTimeoutFn = input.clearTimeoutFn ?? globalThis.clearTimeout;
143 let isVisible = false;
144 let timeoutId: NodeJS.Timeout | null = null;
145​
146 const clearPendingShow = () => {
147 if (timeoutId === null) {
148 return;
149 }
150 clearTimeoutFn(timeoutId);
151 timeoutId = null;
152 };
153​
154 return {
155 sync: (shouldShow) => {
156 if (!shouldShow) {
157 clearPendingShow();
158 if (isVisible) {
159 isVisible = false;
160 input.onVisibilityChange(false);
161 }
162 return;
163 }
164​
165 if (isVisible || timeoutId !== null) {
166 return;
167 }
168​
169 timeoutId = setTimeoutFn(() => {
170 timeoutId = null;
171 isVisible = true;
172 input.onVisibilityChange(true);
173 }, input.delayMs);
174 },
175 dispose: () => {
176 clearPendingShow();
177 },
178 };
180​
181export function useThreadJumpHintVisibility(): {
182 showThreadJumpHints: boolean;
183 updateThreadJumpHintsVisibility: (shouldShow: boolean) => void;
184} {
185 const [showThreadJumpHints, setShowThreadJumpHints] = React.useState(false);
186 const controllerRef = React.useRef<ThreadJumpHintVisibilityController | null>(null);
187​
188 React.useEffect(() => {
189 const controller = createThreadJumpHintVisibilityController({
190 delayMs: THREAD_JUMP_HINT_SHOW_DELAY_MS,
191 onVisibilityChange: (visible) => {
192 setShowThreadJumpHints(visible);
193 },
194 setTimeoutFn: window.setTimeout.bind(window),
195 clearTimeoutFn: window.clearTimeout.bind(window),
196 });
197 controllerRef.current = controller;
198​
199 return () => {
200 controller.dispose();
201 controllerRef.current = null;
202 };
203 }, []);
204​
205 const updateThreadJumpHintsVisibility = React.useCallback((shouldShow: boolean) => {
206 controllerRef.current?.sync(shouldShow);
207 }, []);
208​
209 return {
210 showThreadJumpHints,
211 updateThreadJumpHintsVisibility,
212 };
214​
215export function hasUnseenCompletion(thread: ThreadStatusInput): boolean {
216 if (!thread.latestTurn?.completedAt) return false;
217 const completedAt = Date.parse(thread.latestTurn.completedAt);
218 if (Number.isNaN(completedAt)) return false;
219 if (!thread.lastVisitedAt) return false;
220​
221 const lastVisitedAt = Date.parse(thread.lastVisitedAt);
222 if (Number.isNaN(lastVisitedAt)) return true;
223 return completedAt > lastVisitedAt;
225​
226export function shouldClearThreadSelectionOnMouseDown(target: HTMLElement | null): boolean {
227 if (target === null) return true;
228 return !target.closest(THREAD_SELECTION_SAFE_SELECTOR);
230​
231// A double-click dispatches two `click` events before `dblclick`: the first has
232// `detail === 1`, the second `detail === 2`. The second click must not run the
233// row's single-click navigation, otherwise double-click-to-rename would also
234// navigate. `MouseEvent.detail` is 0 for synthetic/keyboard activations, which
235// still count as a normal single activation.
236export function isTrailingDoubleClick(detail: number): boolean {
237 return detail > 1;
239​
240export function resolveSidebarNewThreadEnvMode(input: {
241 requestedEnvMode?: SidebarNewThreadEnvMode;
242 defaultEnvMode: SidebarNewThreadEnvMode;
243}): SidebarNewThreadEnvMode {
244 return input.requestedEnvMode ?? input.defaultEnvMode;
246​
247export function resolveSidebarNewThreadSeedContext(input: {
248 projectId: string;
249 defaultEnvMode: SidebarNewThreadEnvMode;
250 activeThread?: {
251 projectId: string;
252 branch: string | null;
253 worktreePath: string | null;
254 } | null;
255 activeDraftThread?: {
256 projectId: string;
257 branch: string | null;
258 worktreePath: string | null;
259 envMode: SidebarNewThreadEnvMode;
260 startFromOrigin: boolean;
261 } | null;
262}): {
263 branch?: string | null;
264 worktreePath?: string | null;
265 envMode: SidebarNewThreadEnvMode;
266 startFromOrigin?: boolean;
267} {
268 if (input.defaultEnvMode === "worktree") {
269 return {
270 envMode: "worktree",
271 };
272 }
273​
274 if (input.activeDraftThread?.projectId === input.projectId) {
275 return {
276 branch: input.activeDraftThread.branch,
277 worktreePath: input.activeDraftThread.worktreePath,
278 envMode: input.activeDraftThread.envMode,
279 startFromOrigin: input.activeDraftThread.startFromOrigin,
280 };
281 }
282​
283 if (input.activeThread?.projectId === input.projectId) {
284 return {
285 branch: input.activeThread.branch,
286 worktreePath: input.activeThread.worktreePath,
287 envMode: input.activeThread.worktreePath ? "worktree" : "local",
288 };
289 }
290​
291 return {
292 envMode: input.defaultEnvMode,
293 };
295​
296export function orderItemsByPreferredIds<TItem, TId>(input: {
297 items: readonly TItem[];
298 preferredIds: readonly TId[];
299 getId: (item: TItem) => TId;
300 getPreferenceIds?: (item: TItem) => readonly TId[];
301}): TItem[] {
302 const { getId, getPreferenceIds, items, preferredIds } = input;
303 if (preferredIds.length === 0) {
304 return [...items];
305 }
306​
307 const indexesByPreferenceId = new Map<TId, number[]>();
308 for (const [index, item] of items.entries()) {
309 const preferenceIds = getPreferenceIds?.(item) ?? [getId(item)];
310 for (const preferenceId of new Set(preferenceIds)) {
311 const indexes = indexesByPreferenceId.get(preferenceId);
312 if (indexes) {
313 indexes.push(index);
314 } else {
315 indexesByPreferenceId.set(preferenceId, [index]);
316 }
317 }
318 }
319​
320 const emittedIndexes = new Set<number>();
321 const ordered = preferredIds.flatMap((id) => {
322 const index = indexesByPreferenceId
323 .get(id)
324 ?.find((candidate) => !emittedIndexes.has(candidate));
325 if (index === undefined) {
326 return [];
327 }
328 emittedIndexes.add(index);
329 return [items[index]!];
330 });
331 const remaining = items.filter((_, index) => !emittedIndexes.has(index));
332 return [...ordered, ...remaining];
334​
335export function getVisibleSidebarThreadIds<TThreadId>(
336 renderedProjects: readonly {
337 shouldShowThreadPanel?: boolean;
338 renderedThreadIds: readonly TThreadId[];
339 }[],
340): TThreadId[] {
341 return renderedProjects.flatMap((renderedProject) =>
342 renderedProject.shouldShowThreadPanel === false ? [] : renderedProject.renderedThreadIds,
343 );
345​
346export function getSidebarThreadIdsToPrewarm<TThreadId>(
347 visibleThreadIds: readonly TThreadId[],
348 limit = SIDEBAR_THREAD_PREWARM_LIMIT,
349): TThreadId[] {
350 return visibleThreadIds.slice(0, Math.max(0, limit));
352​
353export function resolveAdjacentThreadId<T>(input: {
354 threadIds: readonly T[];
355 currentThreadId: T | null;
356 direction: ThreadTraversalDirection;
357}): T | null {
358 const { currentThreadId, direction, threadIds } = input;
359​
360 if (threadIds.length === 0) {
361 return null;
362 }
363​
364 if (currentThreadId === null) {
365 return direction === "previous" ? (threadIds.at(-1) ?? null) : (threadIds[0] ?? null);
366 }
367​
368 const currentIndex = threadIds.indexOf(currentThreadId);
369 if (currentIndex === -1) {
370 return null;
371 }
372​
373 if (direction === "previous") {
374 return currentIndex > 0 ? (threadIds[currentIndex - 1] ?? null) : null;
375 }
376​
377 return currentIndex < threadIds.length - 1 ? (threadIds[currentIndex + 1] ?? null) : null;
379​
380export function isContextMenuPointerDown(input: {
381 button: number;
382 ctrlKey: boolean;
383 isMac: boolean;
384}): boolean {
385 if (input.button === 2) return true;
386 return input.isMac && input.button === 0 && input.ctrlKey;
388​
389export function resolveThreadRowClassName(input: {
390 isActive: boolean;
391 isSelected: boolean;
392}): string {
393 const baseClassName =
394 "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";
395​
396 if (input.isSelected && input.isActive) {
397 return cn(
398 baseClassName,
399 "bg-primary/22 text-foreground font-medium hover:bg-primary/26 hover:text-foreground dark:bg-primary/30 dark:hover:bg-primary/36",
400 );
401 }
402​
403 if (input.isSelected) {
404 return cn(
405 baseClassName,
406 "bg-primary/15 text-foreground hover:bg-primary/19 hover:text-foreground dark:bg-primary/22 dark:hover:bg-primary/28",
407 );
408 }
409​
410 if (input.isActive) {
411 return cn(
412 baseClassName,
413 "bg-accent/85 text-foreground font-medium hover:bg-accent hover:text-foreground dark:bg-accent/55 dark:hover:bg-accent/70",
414 );
415 }
416​
417 return cn(baseClassName, "text-muted-foreground hover:bg-accent hover:text-foreground");
419​
420export function resolveThreadStatusPill(input: {
421 thread: ThreadStatusInput;
422}): ThreadStatusPill | null {
423 const { thread } = input;
424​
425 if (thread.hasPendingApprovals) {
426 return {
427 label: "Pending Approval",
428 colorClass: "text-amber-600 dark:text-amber-300/90",
429 dotClass: "bg-amber-500 dark:bg-amber-300/90",
430 pulse: false,
431 };
432 }
433​
434 if (thread.hasPendingUserInput) {
435 return {
436 label: "Awaiting Input",
437 colorClass: "text-indigo-600 dark:text-indigo-300/90",
438 dotClass: "bg-indigo-500 dark:bg-indigo-300/90",
439 pulse: false,
440 };
441 }
442​
443 if (thread.session?.status === "running") {
444 return {
445 label: "Working",
446 colorClass: "text-sky-600 dark:text-sky-300/80",
447 dotClass: "bg-sky-500 dark:bg-sky-300/80",
448 pulse: true,
449 };
450 }
451​
452 if (thread.session?.status === "starting") {
453 return {
454 label: "Connecting",
455 colorClass: "text-sky-600 dark:text-sky-300/80",
456 dotClass: "bg-sky-500 dark:bg-sky-300/80",
457 pulse: true,
458 };
459 }
460​
461 const hasPlanReadyPrompt =
462 !thread.hasPendingUserInput &&
463 thread.interactionMode === "plan" &&
464 isLatestTurnSettled(thread.latestTurn, thread.session) &&
465 thread.hasActionableProposedPlan;
466 if (hasPlanReadyPrompt) {
467 return {
468 label: "Plan Ready",
469 colorClass: "text-violet-600 dark:text-violet-300/90",
470 dotClass: "bg-violet-500 dark:bg-violet-300/90",
471 pulse: false,
472 };
473 }
474​
475 if (hasUnseenCompletion(thread)) {
476 return {
477 label: "Completed",
478 colorClass: "text-emerald-600 dark:text-emerald-300/90",
479 dotClass: "bg-emerald-500 dark:bg-emerald-300/90",
480 pulse: false,
481 };
482 }
483​
484 return null;
486​
487export function resolveProjectStatusIndicator(
488 statuses: ReadonlyArray<ThreadStatusPill | null>,
489): ThreadStatusPill | null {
490 let highestPriorityStatus: ThreadStatusPill | null = null;
491​
492 for (const status of statuses) {
493 if (status === null) continue;
494 if (
495 highestPriorityStatus === null ||
496 THREAD_STATUS_PRIORITY[status.label] > THREAD_STATUS_PRIORITY[highestPriorityStatus.label]
497 ) {
498 highestPriorityStatus = status;
499 }
500 }
501​
502 return highestPriorityStatus;
504​
505export function getVisibleThreadsForProject<T extends Pick<Thread, "id">>(input: {
506 threads: readonly T[];
507 activeThreadId: T["id"] | undefined;
508 isThreadListExpanded: boolean;
509 previewLimit: number;
510}): {
511 hasHiddenThreads: boolean;
512 visibleThreads: T[];
513 hiddenThreads: T[];
514} {
515 const { activeThreadId, isThreadListExpanded, previewLimit, threads } = input;
516 const hasHiddenThreads = threads.length > previewLimit;
517​
518 if (!hasHiddenThreads || isThreadListExpanded) {
519 return {
520 hasHiddenThreads,
521 hiddenThreads: [],
522 visibleThreads: [...threads],
523 };
524 }
525​
526 const previewThreads = threads.slice(0, previewLimit);
527 if (!activeThreadId || previewThreads.some((thread) => thread.id === activeThreadId)) {
528 return {
529 hasHiddenThreads: true,
530 hiddenThreads: threads.slice(previewLimit),
531 visibleThreads: previewThreads,
532 };
533 }
534​
535 const activeThread = threads.find((thread) => thread.id === activeThreadId);
536 if (!activeThread) {
537 return {
538 hasHiddenThreads: true,
539 hiddenThreads: threads.slice(previewLimit),
540 visibleThreads: previewThreads,
541 };
542 }
543​
544 const visibleThreadIds = new Set([...previewThreads, activeThread].map((thread) => thread.id));
545​
546 return {
547 hasHiddenThreads: true,
548 hiddenThreads: threads.filter((thread) => !visibleThreadIds.has(thread.id)),
549 visibleThreads: threads.filter((thread) => visibleThreadIds.has(thread.id)),
550 };
552​
553export function getFallbackThreadIdAfterDelete<
554 T extends Pick<Thread, "id" | "projectId" | "createdAt" | "updatedAt"> & ThreadSortInput,
555>(input: {
556 threads: readonly T[];
557 deletedThreadId: T["id"];
558 sortOrder: SidebarThreadSortOrder;
559 deletedThreadIds?: ReadonlySet<T["id"]>;
560}): T["id"] | null {
561 const { deletedThreadId, deletedThreadIds, sortOrder, threads } = input;
562 const deletedThread = threads.find((thread) => thread.id === deletedThreadId);
563 if (!deletedThread) {
564 return null;
565 }
566​
567 return (
568 sortThreads(
569 threads.filter(
570 (thread) =>
571 thread.projectId === deletedThread.projectId &&
572 thread.id !== deletedThreadId &&
573 !deletedThreadIds?.has(thread.id),
574 ),
575 sortOrder,
576 )[0]?.id ?? null
577 );
579export function getProjectSortTimestamp(
580 project: SidebarProject,
581 projectThreads: readonly ThreadSortInput[],
582 sortOrder: Exclude<SidebarProjectSortOrder, "manual">,
583): number {
584 if (projectThreads.length > 0) {
585 return projectThreads.reduce(
586 (latest, thread) => Math.max(latest, getThreadSortTimestamp(thread, sortOrder)),
587 Number.NEGATIVE_INFINITY,
588 );
589 }
590​
591 if (sortOrder === "created_at") {
592 return toSortableTimestamp(project.createdAt) ?? Number.NEGATIVE_INFINITY;
593 }
594 return toSortableTimestamp(project.updatedAt ?? project.createdAt) ?? Number.NEGATIVE_INFINITY;
596​
597function sortProjectsByActivity<TProject extends SidebarProject>(
598 projects: readonly TProject[],
599 sortOrder: SidebarProjectSortOrder,
600 getProjectThreads: (project: TProject) => readonly ThreadSortInput[],
601 compareTies: (left: TProject, right: TProject) => number,
602): TProject[] {
603 if (sortOrder === "manual") {
604 return [...projects];
605 }
606​
607 return [...projects].toSorted((left, right) => {
608 const rightTimestamp = getProjectSortTimestamp(right, getProjectThreads(right), sortOrder);
609 const leftTimestamp = getProjectSortTimestamp(left, getProjectThreads(left), sortOrder);
610 const byTimestamp =
611 rightTimestamp === leftTimestamp ? 0 : rightTimestamp > leftTimestamp ? 1 : -1;
612 return byTimestamp || compareTies(left, right);
613 });
615​
616export function sortProjectsForSidebar<
617 TProject extends SidebarProject,
618 TThread extends Pick<Thread, "projectId" | "createdAt" | "updatedAt"> & ThreadSortInput,
619>(
620 projects: readonly TProject[],
621 threads: readonly TThread[],
622 sortOrder: SidebarProjectSortOrder,
623): TProject[] {
624 const threadsByProjectId = new Map<string, TThread[]>();
625 for (const thread of threads) {
626 const existing = threadsByProjectId.get(thread.projectId) ?? [];
627 existing.push(thread);
628 threadsByProjectId.set(thread.projectId, existing);
629 }
630​
631 return sortProjectsByActivity(
632 projects,
633 sortOrder,
634 (project) => threadsByProjectId.get(project.id) ?? [],
635 (left, right) => left.title.localeCompare(right.title) || left.id.localeCompare(right.id),
636 );
638​
639/**
640 * Sorts the cross-environment project collection used by landing surfaces.
641 * Project ids are only unique within an environment, and archived threads
642 * must not make a project appear recently active.
643 */
644export function sortScopedProjectsForSidebar<
645 TProject extends ScopedSidebarProject,
646 TThread extends ScopedSidebarThread,
647>(
648 projects: readonly TProject[],
649 threads: readonly TThread[],
650 sortOrder: SidebarProjectSortOrder,
651): TProject[] {
652 const scopedKey = (environmentId: string, projectId: string) =>
653 `${environmentId}\u0000${projectId}`;
654 const threadsByProject = new Map<string, TThread[]>();
655 for (const thread of threads) {
656 if (thread.archivedAt !== null) {
657 continue;
658 }
659 const key = scopedKey(thread.environmentId, thread.projectId);
660 const existing = threadsByProject.get(key) ?? [];
661 existing.push(thread);
662 threadsByProject.set(key, existing);
663 }
664​
665 return sortProjectsByActivity(
666 projects,
667 sortOrder,
668 (project) => threadsByProject.get(scopedKey(project.environmentId, project.id)) ?? [],
669 (left, right) =>
670 left.title.localeCompare(right.title) ||
671 left.environmentId.localeCompare(right.environmentId) ||
672 left.id.localeCompare(right.id),
673 );