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