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

Sidebar.logic.ts

925 lines29.3 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. 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 };
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 ];
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 };
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;
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;
164​
165export function resolveSidebarStageBadgeLabel(input: {
166 primaryServerVersion: string | null | undefined;
167 fallbackStageLabel: string;
168}): string {
169 return resolveServerBackedAppStageLabel(input);
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 };
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 };
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;
262​
263export function shouldClearThreadSelectionOnMouseDown(target: HTMLElement | null): boolean {
264 if (target === null) return true;
265 return !target.closest(THREAD_SELECTION_SAFE_SELECTOR);
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;
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];
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 );
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));
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;
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 );
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;
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 );
425​
426// ── Sidebar thread 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 SidebarThreadStatus =
434 | "approval"
435 | "input"
436 | "working"
437 | "monitoring"
438 | "failed"
439 | "ready";
440​
441type SidebarThreadStatusInput = Pick<
442 SidebarThreadSummary,
443 "hasPendingApprovals" | "hasPendingUserInput" | "session" | "backgroundLiveness"
444>;
445​
446export function resolveSidebarThreadStatus(thread: SidebarThreadStatusInput): SidebarThreadStatus {
447 if (thread.hasPendingApprovals) {
448 return "approval";
449 }
450 if (thread.hasPendingUserInput) {
451 return "input";
452 }
453 if (thread.session?.status === "running" || thread.session?.status === "starting") {
454 return "working";
455 }
456 // A failed session outranks lingering background liveness: the user must
457 // see the failure, not a stale Working (review finding).
458 if (thread.session?.status === "error") {
459 return "failed";
460 }
461 // Background work outlives the turn: fleets read as working; monitoring
462 // only when watch loops are the sole live work.
463 if (thread.backgroundLiveness === "working") {
464 return "working";
465 }
466 if (thread.backgroundLiveness === "monitoring") {
467 return "monitoring";
468 }
469 return "ready";
471​
472/** NaN-safe Date.parse for sort comparators: a malformed timestamp must not
473 poison the whole ordering, so it sinks to the epoch instead. */
474export function parseTimestampMs(isoDate: string): number {
475 const parsed = Date.parse(isoDate);
476 return Number.isNaN(parsed) ? 0 : parsed;
478​
479/** First VALID timestamp wins: `a ?? b` falls through on null, but a present-
480 yet-malformed string must also fall through to the next candidate rather
481 than sink the row to the epoch. */
482export function firstValidTimestampMs(
483 ...candidates: ReadonlyArray<string | null | undefined>
484): number {
485 for (const candidate of candidates) {
486 if (candidate == null) continue;
487 const parsed = Date.parse(candidate);
488 if (!Number.isNaN(parsed)) return parsed;
489 }
490 return 0;
492​
493/** String twin of firstValidTimestampMs for callers that need the ISO string
494 (display labels, tick anchors) rather than epoch ms. */
495export function firstValidTimestamp(
496 ...candidates: ReadonlyArray<string | null | undefined>
497): string | null {
498 for (const candidate of candidates) {
499 if (candidate == null) continue;
500 if (!Number.isNaN(Date.parse(candidate))) return candidate;
501 }
502 return null;
504​
505// Sidebar sort: static creation order, newest thread on top. Activity NEVER
506// reorders the list — a row holds its position from open until settled, so
507// the screen only moves at lifecycle transitions. Status (including pending
508// approval) is carried by each card's edge strip, not by position.
509export function sortThreadsForSidebar<
510 T extends { readonly id: string; readonly createdAt: string },
511>(threads: readonly T[]): T[] {
512 return [...threads].toSorted(
513 (left, right) =>
514 parseTimestampMs(right.createdAt) - parseTimestampMs(left.createdAt) ||
515 left.id.localeCompare(right.id),
516 );
518​
519// Pinned-reorder key math and the keyed sort live in client-runtime
520// (state/thread-sort) so web and mobile compute identical pinned orders.
521export {
522 generateSpreadPinOrderKeys,
523 pinOrderKeyBetween,
524 planPinnedReorder,
525} from "@t3tools/client-runtime/state/thread-sort";
526export { sortPinnedThreadsByOrderKey as sortPinnedThreadsForSidebar } from "@t3tools/client-runtime/state/thread-sort";
527​
528/**
529 * Search the already-ordered sidebar thread collection by title only.
530 * Keeping the input order means lifecycle ordering (active, snoozed, settled)
531 * remains stable while the user narrows the list.
532 */
533export function searchSidebarThreadsByTitle<T extends { readonly title: string }>(
534 threads: readonly T[],
535 query: string,
536): T[] {
537 const normalizedQuery = query.trim().toLowerCase();
538 if (normalizedQuery.length === 0) return [];
539 return threads.filter((thread) => thread.title.toLowerCase().includes(normalizedQuery));
541​
542type SettledTimestampInput = Pick<
543 SidebarThreadSummary,
544 "settledAt" | "latestUserMessageAt" | "latestTurn" | "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 latestTurn stamps), so a thread whose last activity was a turn 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.latestTurn?.requestedAt,
560 thread.latestTurn?.startedAt,
561 thread.latestTurn?.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 sortSettledThreadsForSidebar<
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, "latestTurn" | "session">,
593): string | null {
594 const turn = thread.latestTurn;
595 if (turn && turn.completedAt === null) {
596 return firstValidTimestamp(turn.startedAt, turn.requestedAt, thread.session?.updatedAt);
597 }
598 return firstValidTimestamp(thread.session?.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.session?.status === "running") {
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 (thread.session?.status === "starting") {
642 return {
643 label: "Connecting",
644 colorClass: "text-sky-600 dark:text-sky-300/80",
645 dotClass: "bg-sky-500 dark:bg-sky-300/80",
646 pulse: true,
647 };
648 }
649​
650 // An actionable plan prompt outranks lingering background work: it needs
651 // the user's decision, while liveness merely reports (review finding).
652 const hasPlanReadyPrompt =
653 !thread.hasPendingUserInput &&
654 thread.interactionMode === "plan" &&
655 isLatestTurnSettled(thread.latestTurn, thread.session) &&
656 thread.hasActionableProposedPlan;
657 if (hasPlanReadyPrompt) {
658 return {
659 label: "Plan Ready",
660 colorClass: "text-violet-600 dark:text-violet-300/90",
661 dotClass: "bg-violet-500 dark:bg-violet-300/90",
662 pulse: false,
663 };
664 }
665​
666 // The turn can settle while native background work runs on. Subagent and
667 // workflow fleets read as plain Working; Monitoring is reserved for watch
668 // loops (a parent agent babysitting a PR, tailing checks) with no other
669 // live work. Same recede treatment as Working per inbox-zero.
670 if (thread.backgroundLiveness === "working") {
671 return {
672 label: "Working",
673 colorClass: "text-sky-600 dark:text-sky-300/80",
674 dotClass: "bg-sky-500 dark:bg-sky-300/80",
675 pulse: true,
676 };
677 }
678​
679 if (thread.backgroundLiveness === "monitoring") {
680 return {
681 label: "Monitoring",
682 colorClass: "text-sky-600 dark:text-sky-300/80",
683 dotClass: "bg-sky-500 dark:bg-sky-300/80",
684 pulse: false,
685 };
686 }
687​
688 if (hasUnseenCompletion(thread)) {
689 return {
690 label: "Completed",
691 colorClass: "text-emerald-600 dark:text-emerald-300/90",
692 dotClass: "bg-emerald-500 dark:bg-emerald-300/90",
693 pulse: false,
694 };
695 }
696​
697 return null;
699​
700export function resolveProjectStatusIndicator(
701 statuses: ReadonlyArray<ThreadStatusPill | null>,
702): ThreadStatusPill | null {
703 let highestPriorityStatus: ThreadStatusPill | null = null;
704​
705 for (const status of statuses) {
706 if (status === null) continue;
707 if (
708 highestPriorityStatus === null ||
709 THREAD_STATUS_PRIORITY[status.label] > THREAD_STATUS_PRIORITY[highestPriorityStatus.label]
710 ) {
711 highestPriorityStatus = status;
712 }
713 }
714​
715 return highestPriorityStatus;
717​
718export function getVisibleThreadsForProject<T extends Pick<Thread, "id">>(input: {
719 threads: readonly T[];
720 activeThreadId: T["id"] | undefined;
721 isThreadListExpanded: boolean;
722 previewLimit: number;
723}): {
724 hasHiddenThreads: boolean;
725 visibleThreads: T[];
726 hiddenThreads: T[];
727} {
728 const { activeThreadId, isThreadListExpanded, previewLimit, threads } = input;
729 const hasHiddenThreads = threads.length > previewLimit;
730​
731 if (!hasHiddenThreads || isThreadListExpanded) {
732 return {
733 hasHiddenThreads,
734 hiddenThreads: [],
735 visibleThreads: [...threads],
736 };
737 }
738​
739 const previewThreads = threads.slice(0, previewLimit);
740 if (!activeThreadId || previewThreads.some((thread) => thread.id === activeThreadId)) {
741 return {
742 hasHiddenThreads: true,
743 hiddenThreads: threads.slice(previewLimit),
744 visibleThreads: previewThreads,
745 };
746 }
747​
748 const activeThread = threads.find((thread) => thread.id === activeThreadId);
749 if (!activeThread) {
750 return {
751 hasHiddenThreads: true,
752 hiddenThreads: threads.slice(previewLimit),
753 visibleThreads: previewThreads,
754 };
755 }
756​
757 const visibleThreadIds = new Set([...previewThreads, activeThread].map((thread) => thread.id));
758​
759 return {
760 hasHiddenThreads: true,
761 hiddenThreads: threads.filter((thread) => !visibleThreadIds.has(thread.id)),
762 visibleThreads: threads.filter((thread) => visibleThreadIds.has(thread.id)),
763 };
765​
766export function getFallbackThreadIdAfterDelete<
767 T extends Pick<Thread, "id" | "projectId" | "createdAt" | "updatedAt"> & ThreadSortInput,
768>(input: {
769 threads: readonly T[];
770 deletedThreadId: T["id"];
771 sortOrder: SidebarThreadSortOrder;
772 deletedThreadIds?: ReadonlySet<T["id"]>;
773}): T["id"] | null {
774 const { deletedThreadId, deletedThreadIds, sortOrder, threads } = input;
775 const deletedThread = threads.find((thread) => thread.id === deletedThreadId);
776 if (!deletedThread) {
777 return null;
778 }
779​
780 return (
781 sortThreads(
782 threads.filter(
783 (thread) =>
784 thread.projectId === deletedThread.projectId &&
785 thread.id !== deletedThreadId &&
786 !deletedThreadIds?.has(thread.id),
787 ),
788 sortOrder,
789 )[0]?.id ?? null
790 );
792export function getProjectSortTimestamp(
793 project: SidebarProject,
794 projectThreads: readonly ThreadSortInput[],
795 sortOrder: Exclude<SidebarProjectSortOrder, "manual">,
796): number {
797 if (projectThreads.length > 0) {
798 return projectThreads.reduce(
799 (latest, thread) => Math.max(latest, getThreadSortTimestamp(thread, sortOrder)),
800 Number.NEGATIVE_INFINITY,
801 );
802 }
803​
804 if (sortOrder === "created_at") {
805 return toSortableTimestamp(project.createdAt) ?? Number.NEGATIVE_INFINITY;
806 }
807 return toSortableTimestamp(project.updatedAt ?? project.createdAt) ?? Number.NEGATIVE_INFINITY;
809​
810function sortProjectsByActivity<TProject extends SidebarProject>(
811 projects: readonly TProject[],
812 sortOrder: SidebarProjectSortOrder,
813 getProjectThreads: (project: TProject) => readonly ThreadSortInput[],
814 compareTies: (left: TProject, right: TProject) => number,
815): TProject[] {
816 if (sortOrder === "manual") {
817 return [...projects];
818 }
819​
820 return [...projects].toSorted((left, right) => {
821 const rightTimestamp = getProjectSortTimestamp(right, getProjectThreads(right), sortOrder);
822 const leftTimestamp = getProjectSortTimestamp(left, getProjectThreads(left), sortOrder);
823 const byTimestamp =
824 rightTimestamp === leftTimestamp ? 0 : rightTimestamp > leftTimestamp ? 1 : -1;
825 return byTimestamp || compareTies(left, right);
826 });
828​
829export function sortProjectsForSidebar<
830 TProject extends SidebarProject,
831 TThread extends Pick<Thread, "projectId" | "createdAt" | "updatedAt"> & ThreadSortInput,
832>(
833 projects: readonly TProject[],
834 threads: readonly TThread[],
835 sortOrder: SidebarProjectSortOrder,
836): TProject[] {
837 const threadsByProjectId = new Map<string, TThread[]>();
838 for (const thread of threads) {
839 const existing = threadsByProjectId.get(thread.projectId) ?? [];
840 existing.push(thread);
841 threadsByProjectId.set(thread.projectId, existing);
842 }
843​
844 return sortProjectsByActivity(
845 projects,
846 sortOrder,
847 (project) => threadsByProjectId.get(project.id) ?? [],
848 (left, right) => left.title.localeCompare(right.title) || left.id.localeCompare(right.id),
849 );
851​
852export function sortLogicalProjectsForSidebar<
853 TProject extends LogicalSidebarProject,
854 TThread extends ScopedSidebarThread,
855>(
856 projects: readonly TProject[],
857 threads: readonly TThread[],
858 sortOrder: SidebarProjectSortOrder,
859): TProject[] {
860 const groupKeyByProjectRef = new Map(
861 projects.flatMap((project) =>
862 project.memberProjectRefs.map(
863 (projectRef) =>
864 [`${projectRef.environmentId}\0${projectRef.projectId}`, project.projectKey] as const,
865 ),
866 ),
867 );
868 const threadsByProjectKey = new Map<string, TThread[]>();
869 for (const thread of threads) {
870 if (thread.archivedAt !== null) continue;
871 const projectKey = groupKeyByProjectRef.get(`${thread.environmentId}\0${thread.projectId}`);
872 if (!projectKey) continue;
873 const existing = threadsByProjectKey.get(projectKey);
874 if (existing) {
875 existing.push(thread);
876 } else {
877 threadsByProjectKey.set(projectKey, [thread]);
878 }
879 }
880​
881 return sortProjectsByActivity(
882 projects,
883 sortOrder,
884 (project) => threadsByProjectKey.get(project.projectKey) ?? [],
885 (left, right) =>
886 left.title.localeCompare(right.title) || left.projectKey.localeCompare(right.projectKey),
887 );
889​
890/**
891 * Sorts the cross-environment project collection used by landing surfaces.
892 * Project ids are only unique within an environment, and archived threads
893 * must not make a project appear recently active.
894 */
895export function sortScopedProjectsForSidebar<
896 TProject extends ScopedSidebarProject,
897 TThread extends ScopedSidebarThread,
898>(
899 projects: readonly TProject[],
900 threads: readonly TThread[],
901 sortOrder: SidebarProjectSortOrder,
902): TProject[] {
903 const scopedKey = (environmentId: string, projectId: string) =>
904 `${environmentId}\u0000${projectId}`;
905 const threadsByProject = new Map<string, TThread[]>();
906 for (const thread of threads) {
907 if (thread.archivedAt !== null) {
908 continue;
909 }
910 const key = scopedKey(thread.environmentId, thread.projectId);
911 const existing = threadsByProject.get(key) ?? [];
912 existing.push(thread);
913 threadsByProject.set(key, existing);
914 }
915​
916 return sortProjectsByActivity(
917 projects,
918 sortOrder,
919 (project) => threadsByProject.get(scopedKey(project.environmentId, project.id)) ?? [],
920 (left, right) =>
921 left.title.localeCompare(right.title) ||
922 left.environmentId.localeCompare(right.environmentId) ||
923 left.id.localeCompare(right.id),
924 );