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