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

Sidebar.logic.ts

936 lines29.7 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​
277// Shift+click on the new thread button creates directly in the current
278// project, skipping the command palette's project picker. With a single
279// project there is nothing to pick, so a plain click already creates
280// immediately and the modifier changes nothing.
281export function shouldCreateNewThreadInCurrentProject(
282 shiftKey: boolean,
283 projectGroupCount: number,
284): boolean {
285 return shiftKey || projectGroupCount <= 1;
287​
288export function orderItemsByPreferredIds<TItem, TId>(input: {
289 items: readonly TItem[];
290 preferredIds: readonly TId[];
291 getId: (item: TItem) => TId;
292 getPreferenceIds?: (item: TItem) => readonly TId[];
293}): TItem[] {
294 const { getId, getPreferenceIds, items, preferredIds } = input;
295 if (preferredIds.length === 0) {
296 return [...items];
297 }
298​
299 const indexesByPreferenceId = new Map<TId, number[]>();
300 for (const [index, item] of items.entries()) {
301 const preferenceIds = getPreferenceIds?.(item) ?? [getId(item)];
302 for (const preferenceId of new Set(preferenceIds)) {
303 const indexes = indexesByPreferenceId.get(preferenceId);
304 if (indexes) {
305 indexes.push(index);
306 } else {
307 indexesByPreferenceId.set(preferenceId, [index]);
308 }
309 }
310 }
311​
312 const emittedIndexes = new Set<number>();
313 const ordered = preferredIds.flatMap((id) => {
314 const index = indexesByPreferenceId
315 .get(id)
316 ?.find((candidate) => !emittedIndexes.has(candidate));
317 if (index === undefined) {
318 return [];
319 }
320 emittedIndexes.add(index);
321 return [items[index]!];
322 });
323 const remaining = items.filter((_, index) => !emittedIndexes.has(index));
324 return [...ordered, ...remaining];
326​
327export function getVisibleSidebarThreadIds<TThreadId>(
328 renderedProjects: readonly {
329 shouldShowThreadPanel?: boolean;
330 renderedThreadIds: readonly TThreadId[];
331 }[],
332): TThreadId[] {
333 return renderedProjects.flatMap((renderedProject) =>
334 renderedProject.shouldShowThreadPanel === false ? [] : renderedProject.renderedThreadIds,
335 );
337​
338export function getSidebarThreadIdsToPrewarm<TThreadId>(
339 visibleThreadIds: readonly TThreadId[],
340 limit = SIDEBAR_THREAD_PREWARM_LIMIT,
341): TThreadId[] {
342 return visibleThreadIds.slice(0, Math.max(0, limit));
344​
345export function resolveAdjacentThreadId<T>(input: {
346 threadIds: readonly T[];
347 currentThreadId: T | null;
348 direction: ThreadTraversalDirection;
349}): T | null {
350 const { currentThreadId, direction, threadIds } = input;
351​
352 if (threadIds.length === 0) {
353 return null;
354 }
355​
356 if (currentThreadId === null) {
357 return direction === "previous" ? (threadIds.at(-1) ?? null) : (threadIds[0] ?? null);
358 }
359​
360 const currentIndex = threadIds.indexOf(currentThreadId);
361 if (currentIndex === -1) {
362 return null;
363 }
364​
365 if (direction === "previous") {
366 return currentIndex > 0 ? (threadIds[currentIndex - 1] ?? null) : null;
367 }
368​
369 return currentIndex < threadIds.length - 1 ? (threadIds[currentIndex + 1] ?? null) : null;
371​
372export function shouldNavigateAfterProjectRemoval(input: {
373 routeTarget: ThreadRouteTarget | null;
374 projectThreads: readonly {
375 environmentId: string;
376 id: string;
377 }[];
378 projectDraftId: string | null;
379}): boolean {
380 const { projectDraftId, projectThreads, routeTarget } = input;
381 if (routeTarget?.kind === "draft") {
382 return projectDraftId === routeTarget.draftId;
383 }
384 if (routeTarget?.kind !== "server") {
385 return false;
386 }
387 return projectThreads.some(
388 (thread) =>
389 thread.environmentId === routeTarget.threadRef.environmentId &&
390 thread.id === routeTarget.threadRef.threadId,
391 );
393​
394export function isContextMenuPointerDown(input: {
395 button: number;
396 ctrlKey: boolean;
397 isMac: boolean;
398}): boolean {
399 if (input.button === 2) return true;
400 return input.isMac && input.button === 0 && input.ctrlKey;
402​
403export function resolveThreadRowClassName(input: {
404 isActive: boolean;
405 isSelected: boolean;
406}): string {
407 const baseClassName =
408 "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";
409​
410 if (input.isSelected && input.isActive) {
411 return cn(
412 baseClassName,
413 "bg-sidebar-row-active text-sidebar-foreground font-medium hover:bg-sidebar-row-active hover:text-sidebar-foreground",
414 );
415 }
416​
417 if (input.isSelected) {
418 return cn(
419 baseClassName,
420 "bg-sidebar-row-selected text-sidebar-foreground hover:bg-sidebar-row-active hover:text-sidebar-foreground",
421 );
422 }
423​
424 if (input.isActive) {
425 return cn(
426 baseClassName,
427 "bg-sidebar-row-active text-sidebar-foreground font-medium hover:bg-sidebar-row-active hover:text-sidebar-foreground",
428 );
429 }
430​
431 return cn(
432 baseClassName,
433 "text-sidebar-muted-foreground/80 hover:bg-sidebar-row-hover hover:text-sidebar-foreground",
434 );
436​
437// ── Sidebar thread status model ─────────────────────────────────────
438// Five visual states, three colors: color is reserved for "act now"
439// (approval), "in motion" (working), and "broken" (failed). Ready is the
440// unlabeled resting state — the agent stopped and is waiting on the user,
441// whether it finished, asked a question, or proposed a plan.
442// Unread completion is tracked separately: it describes whether a ready
443// thread needs attention, not what the thread is currently doing.
444export type SidebarThreadStatus =
445 | "approval"
446 | "input"
447 | "working"
448 | "monitoring"
449 | "failed"
450 | "ready";
451​
452type SidebarThreadStatusInput = Pick<
453 SidebarThreadSummary,
454 "hasPendingApprovals" | "hasPendingUserInput" | "session" | "backgroundLiveness"
455>;
456​
457export function resolveSidebarThreadStatus(thread: SidebarThreadStatusInput): SidebarThreadStatus {
458 if (thread.hasPendingApprovals) {
459 return "approval";
460 }
461 if (thread.hasPendingUserInput) {
462 return "input";
463 }
464 if (thread.session?.status === "running" || thread.session?.status === "starting") {
465 return "working";
466 }
467 // A failed session outranks lingering background liveness: the user must
468 // see the failure, not a stale Working (review finding).
469 if (thread.session?.status === "error") {
470 return "failed";
471 }
472 // Background work outlives the turn: fleets read as working; monitoring
473 // only when watch loops are the sole live work.
474 if (thread.backgroundLiveness === "working") {
475 return "working";
476 }
477 if (thread.backgroundLiveness === "monitoring") {
478 return "monitoring";
479 }
480 return "ready";
482​
483/** NaN-safe Date.parse for sort comparators: a malformed timestamp must not
484 poison the whole ordering, so it sinks to the epoch instead. */
485export function parseTimestampMs(isoDate: string): number {
486 const parsed = Date.parse(isoDate);
487 return Number.isNaN(parsed) ? 0 : parsed;
489​
490/** First VALID timestamp wins: `a ?? b` falls through on null, but a present-
491 yet-malformed string must also fall through to the next candidate rather
492 than sink the row to the epoch. */
493export function firstValidTimestampMs(
494 ...candidates: ReadonlyArray<string | null | undefined>
495): number {
496 for (const candidate of candidates) {
497 if (candidate == null) continue;
498 const parsed = Date.parse(candidate);
499 if (!Number.isNaN(parsed)) return parsed;
500 }
501 return 0;
503​
504/** String twin of firstValidTimestampMs for callers that need the ISO string
505 (display labels, tick anchors) rather than epoch ms. */
506export function firstValidTimestamp(
507 ...candidates: ReadonlyArray<string | null | undefined>
508): string | null {
509 for (const candidate of candidates) {
510 if (candidate == null) continue;
511 if (!Number.isNaN(Date.parse(candidate))) return candidate;
512 }
513 return null;
515​
516// Sidebar sort: static creation order, newest thread on top. Activity NEVER
517// reorders the list — a row holds its position from open until settled, so
518// the screen only moves at lifecycle transitions. Status (including pending
519// approval) is carried by each card's edge strip, not by position.
520export function sortThreadsForSidebar<
521 T extends { readonly id: string; readonly createdAt: string },
522>(threads: readonly T[]): T[] {
523 return [...threads].toSorted(
524 (left, right) =>
525 parseTimestampMs(right.createdAt) - parseTimestampMs(left.createdAt) ||
526 left.id.localeCompare(right.id),
527 );
529​
530// Pinned-reorder key math and the keyed sort live in client-runtime
531// (state/thread-sort) so web and mobile compute identical pinned orders.
532export {
533 generateSpreadPinOrderKeys,
534 pinOrderKeyBetween,
535 planPinnedReorder,
536} from "@t3tools/client-runtime/state/thread-sort";
537export { sortPinnedThreadsByOrderKey as sortPinnedThreadsForSidebar } from "@t3tools/client-runtime/state/thread-sort";
538​
539/**
540 * Search the already-ordered sidebar thread collection by title only.
541 * Keeping the input order means lifecycle ordering (active, snoozed, settled)
542 * remains stable while the user narrows the list.
543 */
544export function searchSidebarThreadsByTitle<T extends { readonly title: string }>(
545 threads: readonly T[],
546 query: string,
547): T[] {
548 const normalizedQuery = query.trim().toLowerCase();
549 if (normalizedQuery.length === 0) return [];
550 return threads.filter((thread) => thread.title.toLowerCase().includes(normalizedQuery));
552​
553type SettledTimestampInput = Pick<
554 SidebarThreadSummary,
555 "settledAt" | "latestUserMessageAt" | "latestTurn" | "updatedAt"
556>;
557​
558/** The timestamp a settled row sorts and labels by: settledAt when stamped
559 (explicit settles), otherwise last activity — the same candidates
560 threadLastActivityAt feeds the auto-settle window (user message plus all
561 latestTurn stamps), so a thread whose last activity was a turn completion
562 doesn't sort by an older message time. updatedAt is the final net. */
563export function resolveSettledTimestamp(thread: SettledTimestampInput): string | null {
564 const settledAt = firstValidTimestamp(thread.settledAt);
565 if (settledAt !== null) return settledAt;
566 let latest: string | null = null;
567 let latestMs = Number.NEGATIVE_INFINITY;
568 for (const candidate of [
569 thread.latestUserMessageAt,
570 thread.latestTurn?.requestedAt,
571 thread.latestTurn?.startedAt,
572 thread.latestTurn?.completedAt,
573 ]) {
574 if (candidate == null) continue;
575 const parsed = Date.parse(candidate);
576 if (!Number.isNaN(parsed) && parsed > latestMs) {
577 latest = candidate;
578 latestMs = parsed;
579 }
580 }
581 return latest ?? firstValidTimestamp(thread.updatedAt);
583​
584// Settled rows are history, so they order by when the work ENDED, not when
585// the thread was created or last touched.
586export function sortSettledThreadsForSidebar<
587 T extends SettledTimestampInput & { readonly id: string },
588>(threads: readonly T[]): T[] {
589 const timestampMs = (thread: T) => {
590 const timestamp = resolveSettledTimestamp(thread);
591 return timestamp === null ? 0 : Date.parse(timestamp);
592 };
593 return [...threads].toSorted(
594 (left, right) => timestampMs(right) - timestampMs(left) || left.id.localeCompare(right.id),
595 );
597​
598/** The timestamp a working thread's elapsed label counts from: the running
599 turn's start (request time until adoption), falling back to the session's
600 last transition when the turn projection lags behind. Malformed
601 timestamps fall through to the next candidate, not just missing ones. */
602export function resolveWorkingStartedAt(
603 thread: Pick<SidebarThreadSummary, "latestTurn" | "session">,
604): string | null {
605 const turn = thread.latestTurn;
606 if (turn && turn.completedAt === null) {
607 return firstValidTimestamp(turn.startedAt, turn.requestedAt, thread.session?.updatedAt);
608 }
609 return firstValidTimestamp(thread.session?.updatedAt);
611​
612export function formatWorkingDurationLabel(elapsedMs: number): string {
613 const seconds = Number.isFinite(elapsedMs) ? Math.max(0, Math.floor(elapsedMs / 1000)) : 0;
614 if (seconds < 60) return `${seconds}s`;
615 const minutes = Math.floor(seconds / 60);
616 if (minutes < 60) return `${minutes}m`;
617 return `${Math.floor(minutes / 60)}h ${minutes % 60}m`;
619​
620export function resolveThreadStatusPill(input: {
621 thread: ThreadStatusInput;
622}): ThreadStatusPill | null {
623 const { thread } = input;
624​
625 if (thread.hasPendingApprovals) {
626 return {
627 label: "Pending Approval",
628 colorClass: "text-amber-600 dark:text-amber-300/90",
629 dotClass: "bg-amber-500 dark:bg-amber-300/90",
630 pulse: false,
631 };
632 }
633​
634 if (thread.hasPendingUserInput) {
635 return {
636 label: "Awaiting Input",
637 colorClass: "text-indigo-600 dark:text-indigo-300/90",
638 dotClass: "bg-indigo-500 dark:bg-indigo-300/90",
639 pulse: false,
640 };
641 }
642​
643 if (thread.session?.status === "running") {
644 return {
645 label: "Working",
646 colorClass: "text-sky-600 dark:text-sky-300/80",
647 dotClass: "bg-sky-500 dark:bg-sky-300/80",
648 pulse: true,
649 };
650 }
651​
652 if (thread.session?.status === "starting") {
653 return {
654 label: "Connecting",
655 colorClass: "text-sky-600 dark:text-sky-300/80",
656 dotClass: "bg-sky-500 dark:bg-sky-300/80",
657 pulse: true,
658 };
659 }
660​
661 // An actionable plan prompt outranks lingering background work: it needs
662 // the user's decision, while liveness merely reports (review finding).
663 const hasPlanReadyPrompt =
664 !thread.hasPendingUserInput &&
665 thread.interactionMode === "plan" &&
666 isLatestTurnSettled(thread.latestTurn, thread.session) &&
667 thread.hasActionableProposedPlan;
668 if (hasPlanReadyPrompt) {
669 return {
670 label: "Plan Ready",
671 colorClass: "text-violet-600 dark:text-violet-300/90",
672 dotClass: "bg-violet-500 dark:bg-violet-300/90",
673 pulse: false,
674 };
675 }
676​
677 // The turn can settle while native background work runs on. Subagent and
678 // workflow fleets read as plain Working; Monitoring is reserved for watch
679 // loops (a parent agent babysitting a PR, tailing checks) with no other
680 // live work. Same recede treatment as Working per inbox-zero.
681 if (thread.backgroundLiveness === "working") {
682 return {
683 label: "Working",
684 colorClass: "text-sky-600 dark:text-sky-300/80",
685 dotClass: "bg-sky-500 dark:bg-sky-300/80",
686 pulse: true,
687 };
688 }
689​
690 if (thread.backgroundLiveness === "monitoring") {
691 return {
692 label: "Monitoring",
693 colorClass: "text-sky-600 dark:text-sky-300/80",
694 dotClass: "bg-sky-500 dark:bg-sky-300/80",
695 pulse: false,
696 };
697 }
698​
699 if (hasUnseenCompletion(thread)) {
700 return {
701 label: "Completed",
702 colorClass: "text-emerald-600 dark:text-emerald-300/90",
703 dotClass: "bg-emerald-500 dark:bg-emerald-300/90",
704 pulse: false,
705 };
706 }
707​
708 return null;
710​
711export function resolveProjectStatusIndicator(
712 statuses: ReadonlyArray<ThreadStatusPill | null>,
713): ThreadStatusPill | null {
714 let highestPriorityStatus: ThreadStatusPill | null = null;
715​
716 for (const status of statuses) {
717 if (status === null) continue;
718 if (
719 highestPriorityStatus === null ||
720 THREAD_STATUS_PRIORITY[status.label] > THREAD_STATUS_PRIORITY[highestPriorityStatus.label]
721 ) {
722 highestPriorityStatus = status;
723 }
724 }
725​
726 return highestPriorityStatus;
728​
729export function getVisibleThreadsForProject<T extends Pick<Thread, "id">>(input: {
730 threads: readonly T[];
731 activeThreadId: T["id"] | undefined;
732 isThreadListExpanded: boolean;
733 previewLimit: number;
734}): {
735 hasHiddenThreads: boolean;
736 visibleThreads: T[];
737 hiddenThreads: T[];
738} {
739 const { activeThreadId, isThreadListExpanded, previewLimit, threads } = input;
740 const hasHiddenThreads = threads.length > previewLimit;
741​
742 if (!hasHiddenThreads || isThreadListExpanded) {
743 return {
744 hasHiddenThreads,
745 hiddenThreads: [],
746 visibleThreads: [...threads],
747 };
748 }
749​
750 const previewThreads = threads.slice(0, previewLimit);
751 if (!activeThreadId || previewThreads.some((thread) => thread.id === activeThreadId)) {
752 return {
753 hasHiddenThreads: true,
754 hiddenThreads: threads.slice(previewLimit),
755 visibleThreads: previewThreads,
756 };
757 }
758​
759 const activeThread = threads.find((thread) => thread.id === activeThreadId);
760 if (!activeThread) {
761 return {
762 hasHiddenThreads: true,
763 hiddenThreads: threads.slice(previewLimit),
764 visibleThreads: previewThreads,
765 };
766 }
767​
768 const visibleThreadIds = new Set([...previewThreads, activeThread].map((thread) => thread.id));
769​
770 return {
771 hasHiddenThreads: true,
772 hiddenThreads: threads.filter((thread) => !visibleThreadIds.has(thread.id)),
773 visibleThreads: threads.filter((thread) => visibleThreadIds.has(thread.id)),
774 };
776​
777export function getFallbackThreadIdAfterDelete<
778 T extends Pick<Thread, "id" | "projectId" | "createdAt" | "updatedAt"> & ThreadSortInput,
779>(input: {
780 threads: readonly T[];
781 deletedThreadId: T["id"];
782 sortOrder: SidebarThreadSortOrder;
783 deletedThreadIds?: ReadonlySet<T["id"]>;
784}): T["id"] | null {
785 const { deletedThreadId, deletedThreadIds, sortOrder, threads } = input;
786 const deletedThread = threads.find((thread) => thread.id === deletedThreadId);
787 if (!deletedThread) {
788 return null;
789 }
790​
791 return (
792 sortThreads(
793 threads.filter(
794 (thread) =>
795 thread.projectId === deletedThread.projectId &&
796 thread.id !== deletedThreadId &&
797 !deletedThreadIds?.has(thread.id),
798 ),
799 sortOrder,
800 )[0]?.id ?? null
801 );
803export function getProjectSortTimestamp(
804 project: SidebarProject,
805 projectThreads: readonly ThreadSortInput[],
806 sortOrder: Exclude<SidebarProjectSortOrder, "manual">,
807): number {
808 if (projectThreads.length > 0) {
809 return projectThreads.reduce(
810 (latest, thread) => Math.max(latest, getThreadSortTimestamp(thread, sortOrder)),
811 Number.NEGATIVE_INFINITY,
812 );
813 }
814​
815 if (sortOrder === "created_at") {
816 return toSortableTimestamp(project.createdAt) ?? Number.NEGATIVE_INFINITY;
817 }
818 return toSortableTimestamp(project.updatedAt ?? project.createdAt) ?? Number.NEGATIVE_INFINITY;
820​
821function sortProjectsByActivity<TProject extends SidebarProject>(
822 projects: readonly TProject[],
823 sortOrder: SidebarProjectSortOrder,
824 getProjectThreads: (project: TProject) => readonly ThreadSortInput[],
825 compareTies: (left: TProject, right: TProject) => number,
826): TProject[] {
827 if (sortOrder === "manual") {
828 return [...projects];
829 }
830​
831 return [...projects].toSorted((left, right) => {
832 const rightTimestamp = getProjectSortTimestamp(right, getProjectThreads(right), sortOrder);
833 const leftTimestamp = getProjectSortTimestamp(left, getProjectThreads(left), sortOrder);
834 const byTimestamp =
835 rightTimestamp === leftTimestamp ? 0 : rightTimestamp > leftTimestamp ? 1 : -1;
836 return byTimestamp || compareTies(left, right);
837 });
839​
840export function sortProjectsForSidebar<
841 TProject extends SidebarProject,
842 TThread extends Pick<Thread, "projectId" | "createdAt" | "updatedAt"> & ThreadSortInput,
843>(
844 projects: readonly TProject[],
845 threads: readonly TThread[],
846 sortOrder: SidebarProjectSortOrder,
847): TProject[] {
848 const threadsByProjectId = new Map<string, TThread[]>();
849 for (const thread of threads) {
850 const existing = threadsByProjectId.get(thread.projectId) ?? [];
851 existing.push(thread);
852 threadsByProjectId.set(thread.projectId, existing);
853 }
854​
855 return sortProjectsByActivity(
856 projects,
857 sortOrder,
858 (project) => threadsByProjectId.get(project.id) ?? [],
859 (left, right) => left.title.localeCompare(right.title) || left.id.localeCompare(right.id),
860 );
862​
863export function sortLogicalProjectsForSidebar<
864 TProject extends LogicalSidebarProject,
865 TThread extends ScopedSidebarThread,
866>(
867 projects: readonly TProject[],
868 threads: readonly TThread[],
869 sortOrder: SidebarProjectSortOrder,
870): TProject[] {
871 const groupKeyByProjectRef = new Map(
872 projects.flatMap((project) =>
873 project.memberProjectRefs.map(
874 (projectRef) =>
875 [`${projectRef.environmentId}\0${projectRef.projectId}`, project.projectKey] as const,
876 ),
877 ),
878 );
879 const threadsByProjectKey = new Map<string, TThread[]>();
880 for (const thread of threads) {
881 if (thread.archivedAt !== null) continue;
882 const projectKey = groupKeyByProjectRef.get(`${thread.environmentId}\0${thread.projectId}`);
883 if (!projectKey) continue;
884 const existing = threadsByProjectKey.get(projectKey);
885 if (existing) {
886 existing.push(thread);
887 } else {
888 threadsByProjectKey.set(projectKey, [thread]);
889 }
890 }
891​
892 return sortProjectsByActivity(
893 projects,
894 sortOrder,
895 (project) => threadsByProjectKey.get(project.projectKey) ?? [],
896 (left, right) =>
897 left.title.localeCompare(right.title) || left.projectKey.localeCompare(right.projectKey),
898 );
900​
901/**
902 * Sorts the cross-environment project collection used by landing surfaces.
903 * Project ids are only unique within an environment, and archived threads
904 * must not make a project appear recently active.
905 */
906export function sortScopedProjectsForSidebar<
907 TProject extends ScopedSidebarProject,
908 TThread extends ScopedSidebarThread,
909>(
910 projects: readonly TProject[],
911 threads: readonly TThread[],
912 sortOrder: SidebarProjectSortOrder,
913): TProject[] {
914 const scopedKey = (environmentId: string, projectId: string) =>
915 `${environmentId}\u0000${projectId}`;
916 const threadsByProject = new Map<string, TThread[]>();
917 for (const thread of threads) {
918 if (thread.archivedAt !== null) {
919 continue;
920 }
921 const key = scopedKey(thread.environmentId, thread.projectId);
922 const existing = threadsByProject.get(key) ?? [];
923 existing.push(thread);
924 threadsByProject.set(key, existing);
925 }
926​
927 return sortProjectsByActivity(
928 projects,
929 sortOrder,
930 (project) => threadsByProject.get(scopedKey(project.environmentId, project.id)) ?? [],
931 (left, right) =>
932 left.title.localeCompare(right.title) ||
933 left.environmentId.localeCompare(right.environmentId) ||
934 left.id.localeCompare(right.id),
935 );