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

Sidebar.logic.ts

866 lines27.0 KB

1import * as React from "react";
2import type { ContextMenuItem } from "@t3tools/contracts";
3import type { SidebarProjectSortOrder, SidebarThreadSortOrder } from "@t3tools/contracts/settings";
4import {
5 getThreadSortTimestamp,
6 sortThreads,
7 toSortableTimestamp,
8 type ThreadSortInput,
9} from "../lib/threadSort";
10import type { SidebarThreadSummary, Thread } from "../types";
11import 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 };
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 ];
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 };
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;
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;
154​
155export function resolveSidebarStageBadgeLabel(input: {
156 primaryServerVersion: string | null | undefined;
157 fallbackStageLabel: string;
158}): string {
159 return resolveServerBackedAppStageLabel(input);
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 };
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 };
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;
252​
253export function shouldClearThreadSelectionOnMouseDown(target: HTMLElement | null): boolean {
254 if (target === null) return true;
255 return !target.closest(THREAD_SELECTION_SAFE_SELECTOR);
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;
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];
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 );
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));
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;
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 );
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;
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 );
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";
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;
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;
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;
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 );
492​
493/**
494 * Search the already-ordered sidebar thread collection by title only.
495 * Keeping the input order means lifecycle ordering (active, snoozed, settled)
496 * remains stable while the user narrows the list.
497 */
498export function searchSidebarThreadsByTitle<T extends { readonly title: string }>(
499 threads: readonly T[],
500 query: string,
501): T[] {
502 const normalizedQuery = query.trim().toLowerCase();
503 if (normalizedQuery.length === 0) return [];
504 return threads.filter((thread) => thread.title.toLowerCase().includes(normalizedQuery));
506​
507type SettledTimestampInput = Pick<
508 SidebarThreadSummary,
509 "settledAt" | "latestUserMessageAt" | "latestTurn" | "updatedAt"
510>;
511​
512/** The timestamp a settled row sorts and labels by: settledAt when stamped
513 (explicit settles), otherwise last activity — the same candidates
514 threadLastActivityAt feeds the auto-settle window (user message plus all
515 latestTurn stamps), so a thread whose last activity was a turn completion
516 doesn't sort by an older message time. updatedAt is the final net. */
517export function resolveSettledTimestamp(thread: SettledTimestampInput): string | null {
518 const settledAt = firstValidTimestamp(thread.settledAt);
519 if (settledAt !== null) return settledAt;
520 let latest: string | null = null;
521 let latestMs = Number.NEGATIVE_INFINITY;
522 for (const candidate of [
523 thread.latestUserMessageAt,
524 thread.latestTurn?.requestedAt,
525 thread.latestTurn?.startedAt,
526 thread.latestTurn?.completedAt,
527 ]) {
528 if (candidate == null) continue;
529 const parsed = Date.parse(candidate);
530 if (!Number.isNaN(parsed) && parsed > latestMs) {
531 latest = candidate;
532 latestMs = parsed;
533 }
534 }
535 return latest ?? firstValidTimestamp(thread.updatedAt);
537​
538// Settled rows are history, so they order by when the work ENDED, not when
539// the thread was created or last touched.
540export function sortSettledThreadsForSidebarV2<
541 T extends SettledTimestampInput & { readonly id: string },
542>(threads: readonly T[]): T[] {
543 const timestampMs = (thread: T) => {
544 const timestamp = resolveSettledTimestamp(thread);
545 return timestamp === null ? 0 : Date.parse(timestamp);
546 };
547 return [...threads].toSorted(
548 (left, right) => timestampMs(right) - timestampMs(left) || left.id.localeCompare(right.id),
549 );
551​
552/** The timestamp a working thread's elapsed label counts from: the running
553 turn's start (request time until adoption), falling back to the session's
554 last transition when the turn projection lags behind. Malformed
555 timestamps fall through to the next candidate, not just missing ones. */
556export function resolveWorkingStartedAt(
557 thread: Pick<SidebarThreadSummary, "latestTurn" | "session">,
558): string | null {
559 const turn = thread.latestTurn;
560 if (turn && turn.completedAt === null) {
561 return firstValidTimestamp(turn.startedAt, turn.requestedAt, thread.session?.updatedAt);
562 }
563 return firstValidTimestamp(thread.session?.updatedAt);
565​
566export function formatWorkingDurationLabel(elapsedMs: number): string {
567 const seconds = Number.isFinite(elapsedMs) ? Math.max(0, Math.floor(elapsedMs / 1000)) : 0;
568 if (seconds < 60) return `${seconds}s`;
569 const minutes = Math.floor(seconds / 60);
570 if (minutes < 60) return `${minutes}m`;
571 return `${Math.floor(minutes / 60)}h ${minutes % 60}m`;
573​
574export function resolveThreadStatusPill(input: {
575 thread: ThreadStatusInput;
576}): ThreadStatusPill | null {
577 const { thread } = input;
578​
579 if (thread.hasPendingApprovals) {
580 return {
581 label: "Pending Approval",
582 colorClass: "text-amber-600 dark:text-amber-300/90",
583 dotClass: "bg-amber-500 dark:bg-amber-300/90",
584 pulse: false,
585 };
586 }
587​
588 if (thread.hasPendingUserInput) {
589 return {
590 label: "Awaiting Input",
591 colorClass: "text-indigo-600 dark:text-indigo-300/90",
592 dotClass: "bg-indigo-500 dark:bg-indigo-300/90",
593 pulse: false,
594 };
595 }
596​
597 if (thread.session?.status === "running") {
598 return {
599 label: "Working",
600 colorClass: "text-sky-600 dark:text-sky-300/80",
601 dotClass: "bg-sky-500 dark:bg-sky-300/80",
602 pulse: true,
603 };
604 }
605​
606 if (thread.session?.status === "starting") {
607 return {
608 label: "Connecting",
609 colorClass: "text-sky-600 dark:text-sky-300/80",
610 dotClass: "bg-sky-500 dark:bg-sky-300/80",
611 pulse: true,
612 };
613 }
614​
615 const hasPlanReadyPrompt =
616 !thread.hasPendingUserInput &&
617 thread.interactionMode === "plan" &&
618 isLatestTurnSettled(thread.latestTurn, thread.session) &&
619 thread.hasActionableProposedPlan;
620 if (hasPlanReadyPrompt) {
621 return {
622 label: "Plan Ready",
623 colorClass: "text-violet-600 dark:text-violet-300/90",
624 dotClass: "bg-violet-500 dark:bg-violet-300/90",
625 pulse: false,
626 };
627 }
628​
629 if (hasUnseenCompletion(thread)) {
630 return {
631 label: "Completed",
632 colorClass: "text-emerald-600 dark:text-emerald-300/90",
633 dotClass: "bg-emerald-500 dark:bg-emerald-300/90",
634 pulse: false,
635 };
636 }
637​
638 return null;
640​
641export function resolveProjectStatusIndicator(
642 statuses: ReadonlyArray<ThreadStatusPill | null>,
643): ThreadStatusPill | null {
644 let highestPriorityStatus: ThreadStatusPill | null = null;
645​
646 for (const status of statuses) {
647 if (status === null) continue;
648 if (
649 highestPriorityStatus === null ||
650 THREAD_STATUS_PRIORITY[status.label] > THREAD_STATUS_PRIORITY[highestPriorityStatus.label]
651 ) {
652 highestPriorityStatus = status;
653 }
654 }
655​
656 return highestPriorityStatus;
658​
659export function getVisibleThreadsForProject<T extends Pick<Thread, "id">>(input: {
660 threads: readonly T[];
661 activeThreadId: T["id"] | undefined;
662 isThreadListExpanded: boolean;
663 previewLimit: number;
664}): {
665 hasHiddenThreads: boolean;
666 visibleThreads: T[];
667 hiddenThreads: T[];
668} {
669 const { activeThreadId, isThreadListExpanded, previewLimit, threads } = input;
670 const hasHiddenThreads = threads.length > previewLimit;
671​
672 if (!hasHiddenThreads || isThreadListExpanded) {
673 return {
674 hasHiddenThreads,
675 hiddenThreads: [],
676 visibleThreads: [...threads],
677 };
678 }
679​
680 const previewThreads = threads.slice(0, previewLimit);
681 if (!activeThreadId || previewThreads.some((thread) => thread.id === activeThreadId)) {
682 return {
683 hasHiddenThreads: true,
684 hiddenThreads: threads.slice(previewLimit),
685 visibleThreads: previewThreads,
686 };
687 }
688​
689 const activeThread = threads.find((thread) => thread.id === activeThreadId);
690 if (!activeThread) {
691 return {
692 hasHiddenThreads: true,
693 hiddenThreads: threads.slice(previewLimit),
694 visibleThreads: previewThreads,
695 };
696 }
697​
698 const visibleThreadIds = new Set([...previewThreads, activeThread].map((thread) => thread.id));
699​
700 return {
701 hasHiddenThreads: true,
702 hiddenThreads: threads.filter((thread) => !visibleThreadIds.has(thread.id)),
703 visibleThreads: threads.filter((thread) => visibleThreadIds.has(thread.id)),
704 };
706​
707export function getFallbackThreadIdAfterDelete<
708 T extends Pick<Thread, "id" | "projectId" | "createdAt" | "updatedAt"> & ThreadSortInput,
709>(input: {
710 threads: readonly T[];
711 deletedThreadId: T["id"];
712 sortOrder: SidebarThreadSortOrder;
713 deletedThreadIds?: ReadonlySet<T["id"]>;
714}): T["id"] | null {
715 const { deletedThreadId, deletedThreadIds, sortOrder, threads } = input;
716 const deletedThread = threads.find((thread) => thread.id === deletedThreadId);
717 if (!deletedThread) {
718 return null;
719 }
720​
721 return (
722 sortThreads(
723 threads.filter(
724 (thread) =>
725 thread.projectId === deletedThread.projectId &&
726 thread.id !== deletedThreadId &&
727 !deletedThreadIds?.has(thread.id),
728 ),
729 sortOrder,
730 )[0]?.id ?? null
731 );
733export function getProjectSortTimestamp(
734 project: SidebarProject,
735 projectThreads: readonly ThreadSortInput[],
736 sortOrder: Exclude<SidebarProjectSortOrder, "manual">,
737): number {
738 if (projectThreads.length > 0) {
739 return projectThreads.reduce(
740 (latest, thread) => Math.max(latest, getThreadSortTimestamp(thread, sortOrder)),
741 Number.NEGATIVE_INFINITY,
742 );
743 }
744​
745 if (sortOrder === "created_at") {
746 return toSortableTimestamp(project.createdAt) ?? Number.NEGATIVE_INFINITY;
747 }
748 return toSortableTimestamp(project.updatedAt ?? project.createdAt) ?? Number.NEGATIVE_INFINITY;
750​
751function sortProjectsByActivity<TProject extends SidebarProject>(
752 projects: readonly TProject[],
753 sortOrder: SidebarProjectSortOrder,
754 getProjectThreads: (project: TProject) => readonly ThreadSortInput[],
755 compareTies: (left: TProject, right: TProject) => number,
756): TProject[] {
757 if (sortOrder === "manual") {
758 return [...projects];
759 }
760​
761 return [...projects].toSorted((left, right) => {
762 const rightTimestamp = getProjectSortTimestamp(right, getProjectThreads(right), sortOrder);
763 const leftTimestamp = getProjectSortTimestamp(left, getProjectThreads(left), sortOrder);
764 const byTimestamp =
765 rightTimestamp === leftTimestamp ? 0 : rightTimestamp > leftTimestamp ? 1 : -1;
766 return byTimestamp || compareTies(left, right);
767 });
769​
770export function sortProjectsForSidebar<
771 TProject extends SidebarProject,
772 TThread extends Pick<Thread, "projectId" | "createdAt" | "updatedAt"> & ThreadSortInput,
773>(
774 projects: readonly TProject[],
775 threads: readonly TThread[],
776 sortOrder: SidebarProjectSortOrder,
777): TProject[] {
778 const threadsByProjectId = new Map<string, TThread[]>();
779 for (const thread of threads) {
780 const existing = threadsByProjectId.get(thread.projectId) ?? [];
781 existing.push(thread);
782 threadsByProjectId.set(thread.projectId, existing);
783 }
784​
785 return sortProjectsByActivity(
786 projects,
787 sortOrder,
788 (project) => threadsByProjectId.get(project.id) ?? [],
789 (left, right) => left.title.localeCompare(right.title) || left.id.localeCompare(right.id),
790 );
792​
793export function sortLogicalProjectsForSidebar<
794 TProject extends LogicalSidebarProject,
795 TThread extends ScopedSidebarThread,
796>(
797 projects: readonly TProject[],
798 threads: readonly TThread[],
799 sortOrder: SidebarProjectSortOrder,
800): TProject[] {
801 const groupKeyByProjectRef = new Map(
802 projects.flatMap((project) =>
803 project.memberProjectRefs.map(
804 (projectRef) =>
805 [`${projectRef.environmentId}\0${projectRef.projectId}`, project.projectKey] as const,
806 ),
807 ),
808 );
809 const threadsByProjectKey = new Map<string, TThread[]>();
810 for (const thread of threads) {
811 if (thread.archivedAt !== null) continue;
812 const projectKey = groupKeyByProjectRef.get(`${thread.environmentId}\0${thread.projectId}`);
813 if (!projectKey) continue;
814 const existing = threadsByProjectKey.get(projectKey);
815 if (existing) {
816 existing.push(thread);
817 } else {
818 threadsByProjectKey.set(projectKey, [thread]);
819 }
820 }
821​
822 return sortProjectsByActivity(
823 projects,
824 sortOrder,
825 (project) => threadsByProjectKey.get(project.projectKey) ?? [],
826 (left, right) =>
827 left.title.localeCompare(right.title) || left.projectKey.localeCompare(right.projectKey),
828 );
830​
831/**
832 * Sorts the cross-environment project collection used by landing surfaces.
833 * Project ids are only unique within an environment, and archived threads
834 * must not make a project appear recently active.
835 */
836export function sortScopedProjectsForSidebar<
837 TProject extends ScopedSidebarProject,
838 TThread extends ScopedSidebarThread,
839>(
840 projects: readonly TProject[],
841 threads: readonly TThread[],
842 sortOrder: SidebarProjectSortOrder,
843): TProject[] {
844 const scopedKey = (environmentId: string, projectId: string) =>
845 `${environmentId}\u0000${projectId}`;
846 const threadsByProject = new Map<string, TThread[]>();
847 for (const thread of threads) {
848 if (thread.archivedAt !== null) {
849 continue;
850 }
851 const key = scopedKey(thread.environmentId, thread.projectId);
852 const existing = threadsByProject.get(key) ?? [];
853 existing.push(thread);
854 threadsByProject.set(key, existing);
855 }
856​
857 return sortProjectsByActivity(
858 projects,
859 sortOrder,
860 (project) => threadsByProject.get(scopedKey(project.environmentId, project.id)) ?? [],
861 (left, right) =>
862 left.title.localeCompare(right.title) ||
863 left.environmentId.localeCompare(right.environmentId) ||
864 left.id.localeCompare(right.id),
865 );