Open History to see the last commit
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 type { ThreadRouteTarget } from "../threadRoutes";
12import { cn } from "../lib/utils";
13import { isLatestTurnSettled } from "../session-logic";
14import { resolveServerBackedAppStageLabel } from "../branding.logic";
15
16export const THREAD_SELECTION_SAFE_SELECTOR = "[data-thread-item], [data-thread-selection-safe]";
17export const THREAD_JUMP_HINT_SHOW_DELAY_MS = 100;
18// Visible sidebar rows are prewarmed into the thread-detail cache so opening a
19// nearby thread usually reuses an already-hot subscription.
20export const SIDEBAR_THREAD_PREWARM_LIMIT = 10;
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
38type LogicalSidebarProject = SidebarProject & {
39 projectKey: string;
40 memberProjectRefs: readonly {
41 environmentId: string;
42 projectId: string;
43 }[];
44};
45
46export type ThreadTraversalDirection = "previous" | "next";
47
48export async function archiveSelectedThreadEntries<
49 TEntry extends { readonly threadKey: string },
50 TResult extends { readonly _tag: "Success" | "Failure" },
51>(input: {
52 entries: readonly TEntry[];
53 archive: (entry: TEntry, onArchived: () => void) => Promise<TResult>;
54}): Promise<{
55 archivedThreadKeys: readonly string[];
56 mutationFailure: Extract<TResult, { readonly _tag: "Failure" }> | null;
57 followupFailures: readonly Extract<TResult, { readonly _tag: "Failure" }>[];
58}> {
59 const archivedThreadKeys: string[] = [];
60 const followupFailures: Extract<TResult, { readonly _tag: "Failure" }>[] = [];
61
62 for (const entry of input.entries) {
63 let didArchive = false;
64 const result = await input.archive(entry, () => {
65 didArchive = true;
66 });
67 if (didArchive || result._tag === "Success") {
68 archivedThreadKeys.push(entry.threadKey);
69 }
70 if (result._tag === "Success") continue;
71 const failure = result as Extract<TResult, { readonly _tag: "Failure" }>;
72 if (didArchive) {
73 followupFailures.push(failure);
74 continue;
75 }
76 return { archivedThreadKeys, mutationFailure: failure, followupFailures };
77 }
78
79 return { archivedThreadKeys, mutationFailure: null, followupFailures };
80}
81
82export function buildMultiSelectThreadContextMenuItems(input: {
83 count: number;
84 hasRunningThread: boolean;
85}): readonly ContextMenuItem<"mark-unread" | "archive" | "delete">[] {
86 return [
87 { id: "mark-unread", label: `Mark unread (${input.count})` },
88 {
89 id: "archive",
90 label: `Archive (${input.count})`,
91 disabled: input.hasRunningThread,
92 },
93 { id: "delete", label: `Delete (${input.count})`, destructive: true },
94 ];
95}
96
97export interface ThreadStatusPill {
98 label:
99 | "Working"
100 | "Connecting"
101 | "Completed"
102 | "Pending Approval"
103 | "Awaiting Input"
104 | "Plan Ready";
105 colorClass: string;
106 dotClass: string;
107 pulse: boolean;
108}
109
110const THREAD_STATUS_PRIORITY: Record<ThreadStatusPill["label"], number> = {
111 "Pending Approval": 5,
112 "Awaiting Input": 4,
113 Working: 3,
114 Connecting: 3,
115 "Plan Ready": 2,
116 Completed: 1,
117};
118
119type ThreadStatusInput = Pick<
120 SidebarThreadSummary,
121 | "hasActionableProposedPlan"
122 | "hasPendingApprovals"
123 | "hasPendingUserInput"
124 | "interactionMode"
125 | "latestTurn"
126 | "session"
127> & {
128 lastVisitedAt?: string | undefined;
129};
130
131export interface ThreadJumpHintVisibilityController {
132 sync: (shouldShow: boolean) => void;
133 dispose: () => void;
134}
135
136export function resolveSidebarStageBadgeLabel(input: {
137 primaryServerVersion: string | null | undefined;
138 fallbackStageLabel: string;
139}): string {
140 return resolveServerBackedAppStageLabel(input);
141}
142
143export function createThreadJumpHintVisibilityController(input: {
144 delayMs: number;
145 onVisibilityChange: (visible: boolean) => void;
146 setTimeoutFn?: typeof globalThis.setTimeout;
147 clearTimeoutFn?: typeof globalThis.clearTimeout;
148}): ThreadJumpHintVisibilityController {
149 const setTimeoutFn = input.setTimeoutFn ?? globalThis.setTimeout;
150 const clearTimeoutFn = input.clearTimeoutFn ?? globalThis.clearTimeout;
151 let isVisible = false;
152 let timeoutId: NodeJS.Timeout | null = null;
153
154 const clearPendingShow = () => {
155 if (timeoutId === null) {
156 return;
157 }
158 clearTimeoutFn(timeoutId);
159 timeoutId = null;
160 };
161
162 return {
163 sync: (shouldShow) => {
164 if (!shouldShow) {
165 clearPendingShow();
166 if (isVisible) {
167 isVisible = false;
168 input.onVisibilityChange(false);
169 }
170 return;
171 }
172
173 if (isVisible || timeoutId !== null) {
174 return;
175 }
176
177 timeoutId = setTimeoutFn(() => {
178 timeoutId = null;
179 isVisible = true;
180 input.onVisibilityChange(true);
181 }, input.delayMs);
182 },
183 dispose: () => {
184 clearPendingShow();
185 },
186 };
187}
188
189export function useThreadJumpHintVisibility(): {
190 showThreadJumpHints: boolean;
191 updateThreadJumpHintsVisibility: (shouldShow: boolean) => void;
192} {
193 const [showThreadJumpHints, setShowThreadJumpHints] = React.useState(false);
194 const controllerRef = React.useRef<ThreadJumpHintVisibilityController | null>(null);
195
196 React.useEffect(() => {
197 const controller = createThreadJumpHintVisibilityController({
198 delayMs: THREAD_JUMP_HINT_SHOW_DELAY_MS,
199 onVisibilityChange: (visible) => {
200 setShowThreadJumpHints(visible);
201 },
202 setTimeoutFn: window.setTimeout.bind(window),
203 clearTimeoutFn: window.clearTimeout.bind(window),
204 });
205 controllerRef.current = controller;
206
207 return () => {
208 controller.dispose();
209 controllerRef.current = null;
210 };
211 }, []);
212
213 const updateThreadJumpHintsVisibility = React.useCallback((shouldShow: boolean) => {
214 controllerRef.current?.sync(shouldShow);
215 }, []);
216
217 return {
218 showThreadJumpHints,
219 updateThreadJumpHintsVisibility,
220 };
221}
222
223export function hasUnseenCompletion(thread: ThreadStatusInput): boolean {
224 if (!thread.latestTurn?.completedAt) return false;
225 const completedAt = Date.parse(thread.latestTurn.completedAt);
226 if (Number.isNaN(completedAt)) return false;
227 if (!thread.lastVisitedAt) return false;
228
229 const lastVisitedAt = Date.parse(thread.lastVisitedAt);
230 if (Number.isNaN(lastVisitedAt)) return true;
231 return completedAt > lastVisitedAt;
232}
233
234export function shouldClearThreadSelectionOnMouseDown(target: HTMLElement | null): boolean {
235 if (target === null) return true;
236 return !target.closest(THREAD_SELECTION_SAFE_SELECTOR);
237}
238
239// A double-click dispatches two `click` events before `dblclick`: the first has
240// `detail === 1`, the second `detail === 2`. The second click must not run the
241// row's single-click navigation, otherwise double-click-to-rename would also
242// navigate. `MouseEvent.detail` is 0 for synthetic/keyboard activations, which
243// still count as a normal single activation.
244export function isTrailingDoubleClick(detail: number): boolean {
245 return detail > 1;
246}
247
248export function orderItemsByPreferredIds<TItem, TId>(input: {
249 items: readonly TItem[];
250 preferredIds: readonly TId[];
251 getId: (item: TItem) => TId;
252 getPreferenceIds?: (item: TItem) => readonly TId[];
253}): TItem[] {
254 const { getId, getPreferenceIds, items, preferredIds } = input;
255 if (preferredIds.length === 0) {
256 return [...items];
257 }
258
259 const indexesByPreferenceId = new Map<TId, number[]>();
260 for (const [index, item] of items.entries()) {
261 const preferenceIds = getPreferenceIds?.(item) ?? [getId(item)];
262 for (const preferenceId of new Set(preferenceIds)) {
263 const indexes = indexesByPreferenceId.get(preferenceId);
264 if (indexes) {
265 indexes.push(index);
266 } else {
267 indexesByPreferenceId.set(preferenceId, [index]);
268 }
269 }
270 }
271
272 const emittedIndexes = new Set<number>();
273 const ordered = preferredIds.flatMap((id) => {
274 const index = indexesByPreferenceId
275 .get(id)
276 ?.find((candidate) => !emittedIndexes.has(candidate));
277 if (index === undefined) {
278 return [];
279 }
280 emittedIndexes.add(index);
281 return [items[index]!];
282 });
283 const remaining = items.filter((_, index) => !emittedIndexes.has(index));
284 return [...ordered, ...remaining];
285}
286
287export function getVisibleSidebarThreadIds<TThreadId>(
288 renderedProjects: readonly {
289 shouldShowThreadPanel?: boolean;
290 renderedThreadIds: readonly TThreadId[];
291 }[],
292): TThreadId[] {
293 return renderedProjects.flatMap((renderedProject) =>
294 renderedProject.shouldShowThreadPanel === false ? [] : renderedProject.renderedThreadIds,
295 );
296}
297
298export function getSidebarThreadIdsToPrewarm<TThreadId>(
299 visibleThreadIds: readonly TThreadId[],
300 limit = SIDEBAR_THREAD_PREWARM_LIMIT,
301): TThreadId[] {
302 return visibleThreadIds.slice(0, Math.max(0, limit));
303}
304
305export function resolveAdjacentThreadId<T>(input: {
306 threadIds: readonly T[];
307 currentThreadId: T | null;
308 direction: ThreadTraversalDirection;
309}): T | null {
310 const { currentThreadId, direction, threadIds } = input;
311
312 if (threadIds.length === 0) {
313 return null;
314 }
315
316 if (currentThreadId === null) {
317 return direction === "previous" ? (threadIds.at(-1) ?? null) : (threadIds[0] ?? null);
318 }
319
320 const currentIndex = threadIds.indexOf(currentThreadId);
321 if (currentIndex === -1) {
322 return null;
323 }
324
325 if (direction === "previous") {
326 return currentIndex > 0 ? (threadIds[currentIndex - 1] ?? null) : null;
327 }
328
329 return currentIndex < threadIds.length - 1 ? (threadIds[currentIndex + 1] ?? null) : null;
330}
331
332export function shouldNavigateAfterProjectRemoval(input: {
333 routeTarget: ThreadRouteTarget | null;
334 projectThreads: readonly {
335 environmentId: string;
336 id: string;
337 }[];
338 projectDraftId: string | null;
339}): boolean {
340 const { projectDraftId, projectThreads, routeTarget } = input;
341 if (routeTarget?.kind === "draft") {
342 return projectDraftId === routeTarget.draftId;
343 }
344 if (routeTarget?.kind !== "server") {
345 return false;
346 }
347 return projectThreads.some(
348 (thread) =>
349 thread.environmentId === routeTarget.threadRef.environmentId &&
350 thread.id === routeTarget.threadRef.threadId,
351 );
352}
353
354export function isContextMenuPointerDown(input: {
355 button: number;
356 ctrlKey: boolean;
357 isMac: boolean;
358}): boolean {
359 if (input.button === 2) return true;
360 return input.isMac && input.button === 0 && input.ctrlKey;
361}
362
363export function resolveThreadRowClassName(input: {
364 isActive: boolean;
365 isSelected: boolean;
366}): string {
367 const baseClassName =
368 "h-8 w-full translate-x-0 cursor-pointer justify-start rounded-md px-2 text-left text-sm select-none focus-visible:ring-1 focus-visible:ring-inset focus-visible:ring-ring";
369
370 if (input.isSelected && input.isActive) {
371 return cn(
372 baseClassName,
373 "bg-sidebar-row-active text-sidebar-foreground font-medium hover:bg-sidebar-row-active hover:text-sidebar-foreground",
374 );
375 }
376
377 if (input.isSelected) {
378 return cn(
379 baseClassName,
380 "bg-sidebar-row-selected text-sidebar-foreground hover:bg-sidebar-row-active hover:text-sidebar-foreground",
381 );
382 }
383
384 if (input.isActive) {
385 return cn(
386 baseClassName,
387 "bg-sidebar-row-active text-sidebar-foreground font-medium hover:bg-sidebar-row-active hover:text-sidebar-foreground",
388 );
389 }
390
391 return cn(
392 baseClassName,
393 "text-sidebar-muted-foreground/80 hover:bg-sidebar-row-hover hover:text-sidebar-foreground",
394 );
395}
396
397// ── Sidebar v2 status model ─────────────────────────────────────────
398// Five visual states, three colors: color is reserved for "act now"
399// (approval), "in motion" (working), and "broken" (failed). Ready is the
400// unlabeled resting state — the agent stopped and is waiting on the user,
401// whether it finished, asked a question, or proposed a plan.
402// Unread completion is tracked separately: it describes whether a ready
403// thread needs attention, not what the thread is currently doing.
404export type SidebarV2Status = "approval" | "input" | "working" | "failed" | "ready";
405
406type SidebarV2StatusInput = Pick<
407 SidebarThreadSummary,
408 "hasPendingApprovals" | "hasPendingUserInput" | "session"
409>;
410
411export function resolveSidebarV2Status(thread: SidebarV2StatusInput): SidebarV2Status {
412 if (thread.hasPendingApprovals) {
413 return "approval";
414 }
415 if (thread.hasPendingUserInput) {
416 return "input";
417 }
418 if (thread.session?.status === "running" || thread.session?.status === "starting") {
419 return "working";
420 }
421 if (thread.session?.status === "error") {
422 return "failed";
423 }
424 return "ready";
425}
426
427/** NaN-safe Date.parse for sort comparators: a malformed timestamp must not
428 poison the whole ordering, so it sinks to the epoch instead. */
429export function parseTimestampMs(isoDate: string): number {
430 const parsed = Date.parse(isoDate);
431 return Number.isNaN(parsed) ? 0 : parsed;
432}
433
434/** First VALID timestamp wins: `a ?? b` falls through on null, but a present-
435 yet-malformed string must also fall through to the next candidate rather
436 than sink the row to the epoch. */
437export function firstValidTimestampMs(
438 ...candidates: ReadonlyArray<string | null | undefined>
439): number {
440 for (const candidate of candidates) {
441 if (candidate == null) continue;
442 const parsed = Date.parse(candidate);
443 if (!Number.isNaN(parsed)) return parsed;
444 }
445 return 0;
446}
447
448/** String twin of firstValidTimestampMs for callers that need the ISO string
449 (display labels, tick anchors) rather than epoch ms. */
450export function firstValidTimestamp(
451 ...candidates: ReadonlyArray<string | null | undefined>
452): string | null {
453 for (const candidate of candidates) {
454 if (candidate == null) continue;
455 if (!Number.isNaN(Date.parse(candidate))) return candidate;
456 }
457 return null;
458}
459
460// v2 sort: static creation order, newest thread on top. Activity NEVER
461// reorders the list — a row holds its position from open until settled, so
462// the screen only moves at lifecycle transitions. Status (including pending
463// approval) is carried by each card's edge strip, not by position.
464export function sortThreadsForSidebarV2<
465 T extends { readonly id: string; readonly createdAt: string },
466>(threads: readonly T[]): T[] {
467 return [...threads].toSorted(
468 (left, right) =>
469 parseTimestampMs(right.createdAt) - parseTimestampMs(left.createdAt) ||
470 left.id.localeCompare(right.id),
471 );
472}
473
474type SettledTimestampInput = Pick<
475 SidebarThreadSummary,
476 "settledAt" | "latestUserMessageAt" | "latestTurn" | "updatedAt"
477>;
478
479/** The timestamp a settled row sorts and labels by: settledAt when stamped
480 (explicit settles), otherwise last activity — the same candidates
481 threadLastActivityAt feeds the auto-settle window (user message plus all
482 latestTurn stamps), so a thread whose last activity was a turn completion
483 doesn't sort by an older message time. updatedAt is the final net. */
484export function resolveSettledTimestamp(thread: SettledTimestampInput): string | null {
485 const settledAt = firstValidTimestamp(thread.settledAt);
486 if (settledAt !== null) return settledAt;
487 let latest: string | null = null;
488 let latestMs = Number.NEGATIVE_INFINITY;
489 for (const candidate of [
490 thread.latestUserMessageAt,
491 thread.latestTurn?.requestedAt,
492 thread.latestTurn?.startedAt,
493 thread.latestTurn?.completedAt,
494 ]) {
495 if (candidate == null) continue;
496 const parsed = Date.parse(candidate);
497 if (!Number.isNaN(parsed) && parsed > latestMs) {
498 latest = candidate;
499 latestMs = parsed;
500 }
501 }
502 return latest ?? firstValidTimestamp(thread.updatedAt);
503}
504
505// Settled rows are history, so they order by when the work ENDED, not when
506// the thread was created or last touched.
507export function sortSettledThreadsForSidebarV2<
508 T extends SettledTimestampInput & { readonly id: string },
509>(threads: readonly T[]): T[] {
510 const timestampMs = (thread: T) => {
511 const timestamp = resolveSettledTimestamp(thread);
512 return timestamp === null ? 0 : Date.parse(timestamp);
513 };
514 return [...threads].toSorted(
515 (left, right) => timestampMs(right) - timestampMs(left) || left.id.localeCompare(right.id),
516 );
517}
518
519/** The timestamp a working thread's elapsed label counts from: the running
520 turn's start (request time until adoption), falling back to the session's
521 last transition when the turn projection lags behind. Malformed
522 timestamps fall through to the next candidate, not just missing ones. */
523export function resolveWorkingStartedAt(
524 thread: Pick<SidebarThreadSummary, "latestTurn" | "session">,
525): string | null {
526 const turn = thread.latestTurn;
527 if (turn && turn.completedAt === null) {
528 return firstValidTimestamp(turn.startedAt, turn.requestedAt, thread.session?.updatedAt);
529 }
530 return firstValidTimestamp(thread.session?.updatedAt);
531}
532
533export function formatWorkingDurationLabel(elapsedMs: number): string {
534 const seconds = Number.isFinite(elapsedMs) ? Math.max(0, Math.floor(elapsedMs / 1000)) : 0;
535 if (seconds < 60) return `${seconds}s`;
536 const minutes = Math.floor(seconds / 60);
537 if (minutes < 60) return `${minutes}m`;
538 return `${Math.floor(minutes / 60)}h ${minutes % 60}m`;
539}
540
541export function resolveThreadStatusPill(input: {
542 thread: ThreadStatusInput;
543}): ThreadStatusPill | null {
544 const { thread } = input;
545
546 if (thread.hasPendingApprovals) {
547 return {
548 label: "Pending Approval",
549 colorClass: "text-amber-600 dark:text-amber-300/90",
550 dotClass: "bg-amber-500 dark:bg-amber-300/90",
551 pulse: false,
552 };
553 }
554
555 if (thread.hasPendingUserInput) {
556 return {
557 label: "Awaiting Input",
558 colorClass: "text-indigo-600 dark:text-indigo-300/90",
559 dotClass: "bg-indigo-500 dark:bg-indigo-300/90",
560 pulse: false,
561 };
562 }
563
564 if (thread.session?.status === "running") {
565 return {
566 label: "Working",
567 colorClass: "text-sky-600 dark:text-sky-300/80",
568 dotClass: "bg-sky-500 dark:bg-sky-300/80",
569 pulse: true,
570 };
571 }
572
573 if (thread.session?.status === "starting") {
574 return {
575 label: "Connecting",
576 colorClass: "text-sky-600 dark:text-sky-300/80",
577 dotClass: "bg-sky-500 dark:bg-sky-300/80",
578 pulse: true,
579 };
580 }
581
582 const hasPlanReadyPrompt =
583 !thread.hasPendingUserInput &&
584 thread.interactionMode === "plan" &&
585 isLatestTurnSettled(thread.latestTurn, thread.session) &&
586 thread.hasActionableProposedPlan;
587 if (hasPlanReadyPrompt) {
588 return {
589 label: "Plan Ready",
590 colorClass: "text-violet-600 dark:text-violet-300/90",
591 dotClass: "bg-violet-500 dark:bg-violet-300/90",
592 pulse: false,
593 };
594 }
595
596 if (hasUnseenCompletion(thread)) {
597 return {
598 label: "Completed",
599 colorClass: "text-emerald-600 dark:text-emerald-300/90",
600 dotClass: "bg-emerald-500 dark:bg-emerald-300/90",
601 pulse: false,
602 };
603 }
604
605 return null;
606}
607
608export function resolveProjectStatusIndicator(
609 statuses: ReadonlyArray<ThreadStatusPill | null>,
610): ThreadStatusPill | null {
611 let highestPriorityStatus: ThreadStatusPill | null = null;
612
613 for (const status of statuses) {
614 if (status === null) continue;
615 if (
616 highestPriorityStatus === null ||
617 THREAD_STATUS_PRIORITY[status.label] > THREAD_STATUS_PRIORITY[highestPriorityStatus.label]
618 ) {
619 highestPriorityStatus = status;
620 }
621 }
622
623 return highestPriorityStatus;
624}
625
626export function getVisibleThreadsForProject<T extends Pick<Thread, "id">>(input: {
627 threads: readonly T[];
628 activeThreadId: T["id"] | undefined;
629 isThreadListExpanded: boolean;
630 previewLimit: number;
631}): {
632 hasHiddenThreads: boolean;
633 visibleThreads: T[];
634 hiddenThreads: T[];
635} {
636 const { activeThreadId, isThreadListExpanded, previewLimit, threads } = input;
637 const hasHiddenThreads = threads.length > previewLimit;
638
639 if (!hasHiddenThreads || isThreadListExpanded) {
640 return {
641 hasHiddenThreads,
642 hiddenThreads: [],
643 visibleThreads: [...threads],
644 };
645 }
646
647 const previewThreads = threads.slice(0, previewLimit);
648 if (!activeThreadId || previewThreads.some((thread) => thread.id === activeThreadId)) {
649 return {
650 hasHiddenThreads: true,
651 hiddenThreads: threads.slice(previewLimit),
652 visibleThreads: previewThreads,
653 };
654 }
655
656 const activeThread = threads.find((thread) => thread.id === activeThreadId);
657 if (!activeThread) {
658 return {
659 hasHiddenThreads: true,
660 hiddenThreads: threads.slice(previewLimit),
661 visibleThreads: previewThreads,
662 };
663 }
664
665 const visibleThreadIds = new Set([...previewThreads, activeThread].map((thread) => thread.id));
666
667 return {
668 hasHiddenThreads: true,
669 hiddenThreads: threads.filter((thread) => !visibleThreadIds.has(thread.id)),
670 visibleThreads: threads.filter((thread) => visibleThreadIds.has(thread.id)),
671 };
672}
673
674export function getFallbackThreadIdAfterDelete<
675 T extends Pick<Thread, "id" | "projectId" | "createdAt" | "updatedAt"> & ThreadSortInput,
676>(input: {
677 threads: readonly T[];
678 deletedThreadId: T["id"];
679 sortOrder: SidebarThreadSortOrder;
680 deletedThreadIds?: ReadonlySet<T["id"]>;
681}): T["id"] | null {
682 const { deletedThreadId, deletedThreadIds, sortOrder, threads } = input;
683 const deletedThread = threads.find((thread) => thread.id === deletedThreadId);
684 if (!deletedThread) {
685 return null;
686 }
687
688 return (
689 sortThreads(
690 threads.filter(
691 (thread) =>
692 thread.projectId === deletedThread.projectId &&
693 thread.id !== deletedThreadId &&
694 !deletedThreadIds?.has(thread.id),
695 ),
696 sortOrder,
697 )[0]?.id ?? null
698 );
699}
700export function getProjectSortTimestamp(
701 project: SidebarProject,
702 projectThreads: readonly ThreadSortInput[],
703 sortOrder: Exclude<SidebarProjectSortOrder, "manual">,
704): number {
705 if (projectThreads.length > 0) {
706 return projectThreads.reduce(
707 (latest, thread) => Math.max(latest, getThreadSortTimestamp(thread, sortOrder)),
708 Number.NEGATIVE_INFINITY,
709 );
710 }
711
712 if (sortOrder === "created_at") {
713 return toSortableTimestamp(project.createdAt) ?? Number.NEGATIVE_INFINITY;
714 }
715 return toSortableTimestamp(project.updatedAt ?? project.createdAt) ?? Number.NEGATIVE_INFINITY;
716}
717
718function sortProjectsByActivity<TProject extends SidebarProject>(
719 projects: readonly TProject[],
720 sortOrder: SidebarProjectSortOrder,
721 getProjectThreads: (project: TProject) => readonly ThreadSortInput[],
722 compareTies: (left: TProject, right: TProject) => number,
723): TProject[] {
724 if (sortOrder === "manual") {
725 return [...projects];
726 }
727
728 return [...projects].toSorted((left, right) => {
729 const rightTimestamp = getProjectSortTimestamp(right, getProjectThreads(right), sortOrder);
730 const leftTimestamp = getProjectSortTimestamp(left, getProjectThreads(left), sortOrder);
731 const byTimestamp =
732 rightTimestamp === leftTimestamp ? 0 : rightTimestamp > leftTimestamp ? 1 : -1;
733 return byTimestamp || compareTies(left, right);
734 });
735}
736
737export function sortProjectsForSidebar<
738 TProject extends SidebarProject,
739 TThread extends Pick<Thread, "projectId" | "createdAt" | "updatedAt"> & ThreadSortInput,
740>(
741 projects: readonly TProject[],
742 threads: readonly TThread[],
743 sortOrder: SidebarProjectSortOrder,
744): TProject[] {
745 const threadsByProjectId = new Map<string, TThread[]>();
746 for (const thread of threads) {
747 const existing = threadsByProjectId.get(thread.projectId) ?? [];
748 existing.push(thread);
749 threadsByProjectId.set(thread.projectId, existing);
750 }
751
752 return sortProjectsByActivity(
753 projects,
754 sortOrder,
755 (project) => threadsByProjectId.get(project.id) ?? [],
756 (left, right) => left.title.localeCompare(right.title) || left.id.localeCompare(right.id),
757 );
758}
759
760export function sortLogicalProjectsForSidebar<
761 TProject extends LogicalSidebarProject,
762 TThread extends ScopedSidebarThread,
763>(
764 projects: readonly TProject[],
765 threads: readonly TThread[],
766 sortOrder: SidebarProjectSortOrder,
767): TProject[] {
768 const groupKeyByProjectRef = new Map(
769 projects.flatMap((project) =>
770 project.memberProjectRefs.map(
771 (projectRef) =>
772 [`${projectRef.environmentId}\0${projectRef.projectId}`, project.projectKey] as const,
773 ),
774 ),
775 );
776 const threadsByProjectKey = new Map<string, TThread[]>();
777 for (const thread of threads) {
778 if (thread.archivedAt !== null) continue;
779 const projectKey = groupKeyByProjectRef.get(`${thread.environmentId}\0${thread.projectId}`);
780 if (!projectKey) continue;
781 const existing = threadsByProjectKey.get(projectKey);
782 if (existing) {
783 existing.push(thread);
784 } else {
785 threadsByProjectKey.set(projectKey, [thread]);
786 }
787 }
788
789 return sortProjectsByActivity(
790 projects,
791 sortOrder,
792 (project) => threadsByProjectKey.get(project.projectKey) ?? [],
793 (left, right) =>
794 left.title.localeCompare(right.title) || left.projectKey.localeCompare(right.projectKey),
795 );
796}
797
798/**
799 * Sorts the cross-environment project collection used by landing surfaces.
800 * Project ids are only unique within an environment, and archived threads
801 * must not make a project appear recently active.
802 */
803export function sortScopedProjectsForSidebar<
804 TProject extends ScopedSidebarProject,
805 TThread extends ScopedSidebarThread,
806>(
807 projects: readonly TProject[],
808 threads: readonly TThread[],
809 sortOrder: SidebarProjectSortOrder,
810): TProject[] {
811 const scopedKey = (environmentId: string, projectId: string) =>
812 `${environmentId}\u0000${projectId}`;
813 const threadsByProject = new Map<string, TThread[]>();
814 for (const thread of threads) {
815 if (thread.archivedAt !== null) {
816 continue;
817 }
818 const key = scopedKey(thread.environmentId, thread.projectId);
819 const existing = threadsByProject.get(key) ?? [];
820 existing.push(thread);
821 threadsByProject.set(key, existing);
822 }
823
824 return sortProjectsByActivity(
825 projects,
826 sortOrder,
827 (project) => threadsByProject.get(scopedKey(project.environmentId, project.id)) ?? [],
828 (left, right) =>
829 left.title.localeCompare(right.title) ||
830 left.environmentId.localeCompare(right.environmentId) ||
831 left.id.localeCompare(right.id),
832 );
833}