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