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

Sidebar.logic.ts

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