Open History to see the last commit
1import { resolveThreadWorkingStartedAt } from "@t3tools/client-runtime/state/models";
2import { backgroundWorkHoldsCompletion } from "@t3tools/shared/orchestrationV2PendingBackgroundWork";
3import { threadPullRequestSearchTerms } from "@t3tools/shared/threadPullRequests";
4import * as React from "react";
5import {
6 isAtomCommandInterrupted,
7 type AtomCommandResult,
8} from "@t3tools/client-runtime/state/runtime";
9import { defaultAnimateLayoutChanges, type AnimateLayoutChanges } from "@dnd-kit/sortable";
10import {
11 threadSearchMatchKey,
12 threadSearchSubject,
13 type ThreadSearchShell,
14} from "@t3tools/client-runtime/state/thread-search";
15import { foldSearchQuery, rankSearchItems, scoreThreadSearch } from "@t3tools/shared/paletteSearch";
16import type { ContextMenuItem, EnvironmentId, ThreadId } from "@t3tools/contracts";
17import type { SidebarProjectSortOrder, SidebarThreadSortOrder } from "@t3tools/contracts/settings";
18import type { AsyncResult } from "effect/reactivity";
19import { planPinnedReorder } from "@t3tools/client-runtime/state/thread-sort";
20import {
21 effectiveSnoozed,
22 type ThreadSnoozeShell,
23} from "@t3tools/client-runtime/state/thread-settled";
24import {
25 getThreadSortTimestamp,
26 sortThreads,
27 toSortableTimestamp,
28 type ThreadSortInput,
29} from "../lib/threadSort";
30import type { SidebarThreadSummary, Thread } from "../types";
31import { normalizeSearchText } from "../lib/utils";
32import { isLatestRunSettled } from "../session-logic";
33
34export function shouldNavigateAfterThreadPark(input: {
35 readonly threadKey: string;
36 readonly currentThreadKey: string | null;
37 readonly action: "settle" | "snooze";
38 readonly now: string;
39 readonly thread: (ThreadSnoozeShell & Pick<SidebarThreadSummary, "settledOverride">) | null;
40}): boolean {
41 return (
42 input.threadKey === input.currentThreadKey &&
43 input.thread !== null &&
44 (input.action === "settle"
45 ? input.thread.settledOverride === "settled"
46 : effectiveSnoozed(input.thread, { now: input.now }))
47 );
48}
49
50const THREAD_SELECTION_SAFE_SELECTOR = "[data-thread-item], [data-thread-selection-safe]";
51const THREAD_JUMP_HINT_SHOW_DELAY_MS = 200;
52
53export function resolveSidebarRowAccessibility(input: {
54 readonly title: string;
55 readonly statusLabel: string | null;
56 readonly projectDisplayName: string | null;
57 readonly isActive: boolean;
58}): { readonly label: string; readonly current: "page" | undefined } {
59 return {
60 label: [input.title, input.statusLabel, input.projectDisplayName].filter(Boolean).join(", "),
61 current: input.isActive ? "page" : undefined,
62 };
63}
64
65// Each prewarm retains growing thread detail and a live subscription, multiplying heap and server load.
66const SIDEBAR_THREAD_PREWARM_LIMIT = 3;
67const SIDEBAR_ROW_SUBSCRIPTION_OVERSCAN_PX = 160;
68
69export function useSidebarRowSubscriptionLease(isActive: boolean): {
70 readonly leaseLiveStatus: boolean;
71 readonly rowRef: React.Dispatch<React.SetStateAction<HTMLElement | null>>;
72} {
73 const [row, setRow] = React.useState<HTMLElement | null>(null);
74 const [isNearViewport, setIsNearViewport] = React.useState(isActive);
75 if (isActive && !isNearViewport) setIsNearViewport(true);
76 const canObserve = typeof IntersectionObserver !== "undefined";
77
78 React.useEffect(() => {
79 if (isActive || row === null || !canObserve) return;
80
81 const scrollRoot = row.closest<HTMLElement>('[data-slot="scroll-area-viewport"]');
82 const observer = new IntersectionObserver(
83 ([entry]) => setIsNearViewport(entry?.isIntersecting === true),
84 {
85 root: scrollRoot,
86 rootMargin: `${SIDEBAR_ROW_SUBSCRIPTION_OVERSCAN_PX}px 0px`,
87 },
88 );
89 observer.observe(row);
90 return () => observer.disconnect();
91 }, [canObserve, isActive, row]);
92
93 return {
94 leaseLiveStatus: isActive || isNearViewport || !canObserve,
95 rowRef: setRow,
96 };
97}
98
99export function useRetainedValue<T>(key: string | null, value: T | null): T | null {
100 const [retained, setRetained] = React.useState<{
101 readonly key: string;
102 readonly value: T;
103 } | null>(null);
104 if (key !== null && value !== null && (retained?.key !== key || retained.value !== value)) {
105 setRetained({ key, value });
106 }
107 if (value !== null) return value;
108 return key !== null && retained?.key === key ? retained.value : null;
109}
110
111// Sortable owns drag transforms; replaying committed order would animate drops twice.
112export const animateSidebarLayoutChanges: AnimateLayoutChanges = (args) =>
113 args.isSorting ? defaultAnimateLayoutChanges(args) : false;
114
115// Snoozed rows cannot accept drops without a wake time. Working rows only drag out as chat context.
116
117export type SidebarSection = "pinned" | "active" | "working" | "snoozed" | "settled";
118
119export function resolveSidebarThreadSection(input: {
120 readonly snoozed: boolean;
121 readonly settled: boolean;
122 readonly pinned: boolean;
123}): SidebarSection {
124 if (input.snoozed) return "snoozed";
125 if (input.settled) return "settled";
126 if (input.pinned) return "pinned";
127 return "active";
128}
129
130const SIDEBAR_MARKER_PREFIX = "sidebar-marker-";
131
132export type SidebarListMarker =
133 | "pinned-header"
134 | "active-placeholder"
135 | "settled-placeholder"
136 | "pinned-divider"
137 | "working-header"
138 | "snoozed-header"
139 | "settled-header";
140
141export function sidebarMarkerId(marker: SidebarListMarker): string {
142 return `${SIDEBAR_MARKER_PREFIX}${marker}`;
143}
144
145export type SidebarListItem =
146 | { readonly kind: "thread"; readonly key: string; readonly section: SidebarSection }
147 | { readonly kind: "marker"; readonly marker: SidebarListMarker };
148
149export function sidebarListItemId(item: SidebarListItem): string {
150 return item.kind === "thread" ? item.key : sidebarMarkerId(item.marker);
151}
152
153function sectionAtSidebarSlot(items: readonly SidebarListItem[], index: number): SidebarSection {
154 let section: SidebarSection = "pinned";
155 for (let i = 0; i < index && i < items.length; i += 1) {
156 const item = items[i]!;
157 if (item.kind !== "marker") continue;
158 if (item.marker === "pinned-divider") section = "active";
159 else if (item.marker === "working-header") section = "working";
160 else if (item.marker === "snoozed-header") section = "snoozed";
161 else if (item.marker === "settled-header") section = "settled";
162 }
163 return section;
164}
165
166export type SidebarDropTarget = {
167 readonly section: "pinned" | "active" | "settled";
168 readonly pinnedOrder: readonly string[];
169 readonly activeOrder: readonly string[];
170};
171
172export function resolveSidebarDropTarget(
173 items: readonly SidebarListItem[],
174 activeKey: string,
175 overId: string,
176): SidebarDropTarget | null {
177 const activeIndex = items.findIndex((item) => sidebarListItemId(item) === activeKey);
178 const overIndex = items.findIndex((item) => sidebarListItemId(item) === overId);
179 if (activeIndex === -1 || overIndex === -1 || items[activeIndex]?.kind !== "thread") return null;
180 const moved = items.filter((_, index) => index !== activeIndex);
181 moved.splice(overIndex, 0, items[activeIndex]!);
182 const section = sectionAtSidebarSlot(moved, overIndex);
183 if (section === "working" || section === "snoozed") return null;
184 const pinnedOrder: string[] = [];
185 const activeOrder: string[] = [];
186 let currentSection: SidebarSection = "pinned";
187 for (const item of moved) {
188 if (item.kind === "marker") {
189 if (item.marker === "pinned-divider") currentSection = "active";
190 else if (
191 item.marker === "working-header" ||
192 item.marker === "snoozed-header" ||
193 item.marker === "settled-header"
194 )
195 break;
196 } else if (currentSection === "pinned") pinnedOrder.push(item.key);
197 else activeOrder.push(item.key);
198 }
199 return { section, pinnedOrder, activeOrder };
200}
201
202export type SidebarThreadDropPlan =
203 | { readonly kind: "none" }
204 | {
205 readonly kind: "reorder-pinned";
206 readonly order: readonly string[];
207 readonly assignments: ReadonlyArray<{ readonly id: string; readonly orderKey: string }>;
208 }
209 | {
210 readonly kind: "pin";
211 readonly order: readonly string[];
212 readonly orderKey: string | undefined;
213 readonly extraAssignments: ReadonlyArray<{ readonly id: string; readonly orderKey: string }>;
214 }
215 | {
216 readonly kind: "move-active";
217 readonly order: readonly string[] | null;
218 readonly assignments: ReadonlyArray<{ readonly id: string; readonly orderKey: string }>;
219 readonly unpin: boolean;
220 readonly unsettle: boolean;
221 readonly unsnooze: boolean;
222 }
223 | { readonly kind: "settle" };
224
225export type SidebarDropVerb = "pin" | "unpin" | "settle" | "unsettle" | "wake";
226
227export function resolveSidebarDropVerb(
228 from: SidebarSection,
229 to: SidebarSection | null,
230): SidebarDropVerb | null {
231 if (to === null || to === from || to === "working" || to === "snoozed") return null;
232 if (to === "pinned") return "pin";
233 if (to === "settled") return "settle";
234 if (from === "pinned") return "unpin";
235 if (from === "settled") return "unsettle";
236 return "wake";
237}
238
239export function resolveSidebarSweepKeys(
240 orderedKeys: readonly string[],
241 originKey: string,
242 targetKey: string,
243 canApply: (key: string) => boolean,
244): string[] {
245 const origin = orderedKeys.indexOf(originKey);
246 const target = orderedKeys.indexOf(targetKey);
247 if (origin === -1 || target === -1) return [];
248 return orderedKeys.slice(Math.min(origin, target), Math.max(origin, target) + 1).filter(canApply);
249}
250
251export function sidebarThreadKeyAtY(list: HTMLElement, y: number): string | null {
252 const viewport = list.closest('[data-slot="scroll-area-viewport"]')?.getBoundingClientRect();
253 const visibleY = viewport ? Math.min(Math.max(y, viewport.top), viewport.bottom - 1) : y;
254 let key: string | null = null;
255 for (const row of list.querySelectorAll<HTMLElement>("li[data-thread-item]")) {
256 if (key !== null && row.getBoundingClientRect().top > visibleY) break;
257 key = row.dataset.threadItem ?? null;
258 }
259 return key;
260}
261
262export function planSidebarThreadDrop(input: {
263 readonly activeKey: string;
264 readonly activeSection: SidebarSection;
265 readonly activePinned?: boolean;
266 readonly activeSettled?: boolean;
267 readonly supportsSettlement?: boolean;
268 readonly target: SidebarDropTarget;
269 readonly pinnedOrder: readonly string[];
270 readonly pinnedKeysById: ReadonlyMap<string, string | null | undefined>;
271 readonly reorderableKeys?: ReadonlySet<string>;
272 readonly activeOrder: readonly string[];
273 readonly activeKeysById: ReadonlyMap<string, string | null | undefined>;
274 readonly activeReorderableKeys?: ReadonlySet<string>;
275 readonly activeTimeOrdered?: boolean;
276}): SidebarThreadDropPlan {
277 const {
278 activeKey,
279 activeSection,
280 activePinned = activeSection === "pinned",
281 activeSettled = activeSection === "settled",
282 target,
283 pinnedOrder,
284 pinnedKeysById,
285 reorderableKeys,
286 activeOrder,
287 activeKeysById,
288 activeReorderableKeys,
289 } = input;
290 if (activeSection === "working") return { kind: "none" };
291 if (input.supportsSettlement === false && (target.section === "settled" || activeSettled)) {
292 return { kind: "none" };
293 }
294 const arrange = (
295 order: readonly string[],
296 keysById: ReadonlyMap<string, string | null | undefined>,
297 writable: ReadonlySet<string> | undefined,
298 ) => {
299 if (!writable) return planPinnedReorder({ orderedIds: order, keysById, movedId: activeKey });
300 if (!writable.has(activeKey)) return null;
301 const assignments = planPinnedReorder({
302 orderedIds: order.filter((key) => writable.has(key) || keysById.get(key) != null),
303 keysById,
304 movedId: activeKey,
305 });
306 return assignments.every(({ id }) => writable.has(id)) ? assignments : null;
307 };
308 switch (target.section) {
309 case "active": {
310 if (input.activeTimeOrdered) {
311 return activeSection === "active"
312 ? { kind: "none" }
313 : {
314 kind: "move-active",
315 order: null,
316 assignments: [],
317 unpin: activePinned,
318 unsettle: activeSettled,
319 unsnooze: activeSection === "snoozed",
320 };
321 }
322 const order = target.activeOrder;
323 if (
324 activeSection === "active" &&
325 order.length === activeOrder.length &&
326 order.every((key, index) => key === activeOrder[index])
327 ) {
328 return { kind: "none" };
329 }
330 const assignments = arrange(order, activeKeysById, activeReorderableKeys);
331 if (assignments === null) return { kind: "none" };
332 return {
333 kind: "move-active",
334 order,
335 assignments,
336 unpin: activePinned,
337 unsettle: activeSettled,
338 unsnooze: activeSection === "snoozed",
339 };
340 }
341 case "settled":
342 return activeSection === "settled" ? { kind: "none" } : { kind: "settle" };
343 case "pinned": {
344 const order = target.pinnedOrder;
345 if (
346 activeSection === "pinned" &&
347 order.length === pinnedOrder.length &&
348 order.every((key, index) => key === pinnedOrder[index])
349 ) {
350 return { kind: "none" };
351 }
352 const assignments = arrange(order, pinnedKeysById, reorderableKeys);
353 if (assignments === null) return { kind: "none" };
354 if (activeSection === "pinned") {
355 return assignments.length === 0
356 ? { kind: "none" }
357 : { kind: "reorder-pinned", order, assignments };
358 }
359 return {
360 kind: "pin",
361 order,
362 orderKey: assignments.find((assignment) => assignment.id === activeKey)?.orderKey,
363 extraAssignments: activePinned
364 ? assignments
365 : assignments.filter((assignment) => assignment.id !== activeKey),
366 };
367 }
368 }
369}
370
371export function applySidebarThreadDrop<
372 T extends Pick<
373 SidebarThreadSummary,
374 | "pinnedAt"
375 | "pinOrderKey"
376 | "activeOrderKey"
377 | "snoozedAt"
378 | "snoozedUntil"
379 | "settledAt"
380 | "settledOverride"
381 | "unsettledAt"
382 >,
383>(thread: T, section: "pinned" | "active" | "settled", now: string, orderKey?: string): T {
384 const wasSettled = thread.settledOverride === "settled";
385 const awake = { ...thread, snoozedAt: null, snoozedUntil: null };
386 if (section === "settled") {
387 return {
388 ...awake,
389 pinnedAt: null,
390 pinOrderKey: null,
391 activeOrderKey: null,
392 settledOverride: "settled",
393 settledAt: wasSettled ? (thread.settledAt ?? now) : now,
394 unsettledAt: null,
395 };
396 }
397 const resumed = wasSettled
398 ? { ...awake, settledOverride: "active" as const, settledAt: null, unsettledAt: now }
399 : awake;
400 return {
401 ...resumed,
402 pinnedAt: section === "pinned" ? (thread.pinnedAt ?? now) : null,
403 pinOrderKey: section === "pinned" ? (orderKey ?? thread.pinOrderKey) : null,
404 ...(section === "active" && orderKey !== undefined ? { activeOrderKey: orderKey } : {}),
405 };
406}
407
408type SidebarProject = {
409 id: string;
410 title: string;
411 createdAt?: string | undefined;
412 updatedAt?: string | undefined;
413};
414
415type ScopedSidebarProject = SidebarProject & {
416 environmentId: string;
417};
418
419type ScopedSidebarThread = ThreadSortInput & {
420 environmentId: string;
421 projectId: string;
422 archivedAt: string | null;
423};
424
425type LogicalSidebarProject = SidebarProject & {
426 projectKey: string;
427 memberProjectRefs: readonly {
428 environmentId: string;
429 projectId: string;
430 }[];
431};
432
433export type ThreadTraversalDirection = "previous" | "next";
434
435/** Exclude only successful deletions from shared-worktree checks. */
436export async function deleteSelectedThreadEntries<
437 TEntry extends { readonly threadKey: string },
438>(input: {
439 entries: readonly TEntry[];
440 delete: (
441 entry: TEntry,
442 deletedThreadKeys: ReadonlySet<string>,
443 ) => Promise<AtomCommandResult<unknown, unknown> | null>;
444}) {
445 const deletedThreadKeys = new Set<string>();
446 let firstFailure: AsyncResult.Failure<unknown, unknown> | null = null;
447
448 for (const entry of input.entries) {
449 const result = await input.delete(entry, deletedThreadKeys);
450 if (result === null) continue;
451 if (result._tag === "Failure") {
452 if (isAtomCommandInterrupted(result)) break;
453 firstFailure ??= result;
454 continue;
455 }
456 deletedThreadKeys.add(entry.threadKey);
457 }
458
459 return { deletedThreadKeys, firstFailure };
460}
461
462export async function archiveSelectedThreadEntries<
463 TEntry extends { readonly threadKey: string },
464 TResult extends { readonly _tag: "Success" | "Failure" },
465>(input: {
466 entries: readonly TEntry[];
467 archive: (entry: TEntry, onArchived: () => void) => Promise<TResult>;
468}): Promise<{
469 archivedThreadKeys: readonly string[];
470 mutationFailure: Extract<TResult, { readonly _tag: "Failure" }> | null;
471 followupFailures: readonly Extract<TResult, { readonly _tag: "Failure" }>[];
472}> {
473 const archivedThreadKeys: string[] = [];
474 const followupFailures: Extract<TResult, { readonly _tag: "Failure" }>[] = [];
475
476 for (const entry of input.entries) {
477 let didArchive = false;
478 const result = await input.archive(entry, () => {
479 didArchive = true;
480 });
481 if (didArchive || result._tag === "Success") archivedThreadKeys.push(entry.threadKey);
482 if (result._tag === "Success") continue;
483 const failure = result as Extract<TResult, { readonly _tag: "Failure" }>;
484 if (didArchive) {
485 followupFailures.push(failure);
486 continue;
487 }
488 return { archivedThreadKeys, mutationFailure: failure, followupFailures };
489 }
490
491 return { archivedThreadKeys, mutationFailure: null, followupFailures };
492}
493
494export function buildMultiSelectThreadContextMenuItems(input: {
495 count: number;
496 hasRunningThread: boolean;
497}): readonly ContextMenuItem<"mark-unread" | "archive" | "delete">[] {
498 return [
499 { id: "mark-unread", label: `Mark unread (${input.count})` },
500 {
501 id: "archive",
502 label: `Archive (${input.count})`,
503 disabled: input.hasRunningThread,
504 },
505 { id: "delete", label: `Delete (${input.count})`, destructive: true },
506 ];
507}
508
509export function isSidebarSubagentThread(thread: Pick<SidebarThreadSummary, "lineage">): boolean {
510 return thread.lineage.relationshipToParent === "subagent";
511}
512
513// Subagent threads have no sidebar row, so an open subagent is represented by
514// its nearest non-subagent ancestor. A broken chain (missing parent, cycle,
515// other environment) resolves to the thread itself, which then matches no row.
516export function resolveSidebarRowThreadId(
517 threadId: ThreadId,
518 environmentId: EnvironmentId,
519 threads: readonly Pick<SidebarThreadSummary, "id" | "environmentId" | "lineage">[],
520): ThreadId {
521 const findThread = (id: ThreadId) =>
522 threads.find((thread) => thread.id === id && thread.environmentId === environmentId);
523 const visited = new Set<ThreadId>();
524 let thread = findThread(threadId);
525 while (thread !== undefined && isSidebarSubagentThread(thread)) {
526 if (thread.lineage.parentThreadId === null || visited.has(thread.id)) return threadId;
527 visited.add(thread.id);
528 thread = findThread(thread.lineage.parentThreadId);
529 }
530 return thread?.id ?? threadId;
531}
532
533export function filterSidebarV2VisibleThreads<
534 T extends Pick<SidebarThreadSummary, "archivedAt" | "lineage"> & {
535 environmentId: string;
536 projectId: string;
537 },
538>(threads: readonly T[], scopedProjectKeys: ReadonlySet<string> | null): T[] {
539 return threads.filter(
540 (thread) =>
541 thread.archivedAt === null &&
542 !isSidebarSubagentThread(thread) &&
543 (scopedProjectKeys === null ||
544 scopedProjectKeys.has(`${thread.environmentId}:${thread.projectId}`)),
545 );
546}
547
548export function buildBulkTitleRegenerationContextMenuItem(input: {
549 supportedCount: number;
550 actionableCount: number;
551}): ContextMenuItem<"regenerate-title"> | null {
552 if (input.supportedCount === 0) return null;
553 if (input.actionableCount === 0) {
554 return {
555 id: "regenerate-title",
556 label: `Regenerating… (${input.supportedCount})`,
557 disabled: true,
558 };
559 }
560 return {
561 id: "regenerate-title",
562 label: `Regenerate titles (${input.actionableCount})`,
563 };
564}
565
566export function buildBulkUnpinContextMenuItem(input: {
567 pinnedCount: number;
568}): ContextMenuItem<"unpin"> | null {
569 if (input.pinnedCount === 0) return null;
570 return { id: "unpin", label: `Unpin (${input.pinnedCount})` };
571}
572
573export interface ThreadStatusPill {
574 label:
575 | "Working"
576 | "Connecting"
577 | "Completed"
578 | "Failed"
579 | "Pending Approval"
580 | "Awaiting Input"
581 | "Guest Request"
582 | "Waiting"
583 | "Plan Ready";
584 colorClass: string;
585 dotClass: string;
586 pulse: boolean;
587}
588
589const THREAD_STATUS_PRIORITY: Record<ThreadStatusPill["label"], number> = {
590 "Pending Approval": 5,
591 "Awaiting Input": 4,
592 "Guest Request": 3.75,
593 Failed: 3.5,
594 Working: 3,
595 Connecting: 3,
596 Waiting: 2.5,
597 "Plan Ready": 2,
598 Completed: 1,
599};
600
601type ThreadStatusInput = Pick<
602 SidebarThreadSummary,
603 | "hasActionableProposedPlan"
604 | "hasPendingApprovals"
605 | "hasPendingUserInput"
606 | "pendingSubagentRequest"
607 | "pendingGuestMessageCount"
608 | "interactionMode"
609 | "latestRun"
610 | "runtime"
611> & {
612 lastVisitedAt?: string | null | undefined;
613 pendingBackgroundTasks?: SidebarThreadSummary["pendingBackgroundTasks"] | undefined;
614 blockedOnThreadWait?: boolean | undefined;
615};
616
617export interface ThreadJumpHintVisibilityController {
618 sync: (shouldShow: boolean) => void;
619 dispose: () => void;
620}
621
622function createThreadJumpHintVisibilityController(input: {
623 delayMs: number;
624 onVisibilityChange: (visible: boolean) => void;
625 setTimeoutFn?: typeof globalThis.setTimeout;
626 clearTimeoutFn?: typeof globalThis.clearTimeout;
627}): ThreadJumpHintVisibilityController {
628 const setTimeoutFn = input.setTimeoutFn ?? globalThis.setTimeout;
629 const clearTimeoutFn = input.clearTimeoutFn ?? globalThis.clearTimeout;
630 let isVisible = false;
631 let timeoutId: NodeJS.Timeout | null = null;
632
633 const clearPendingShow = () => {
634 if (timeoutId === null) {
635 return;
636 }
637 clearTimeoutFn(timeoutId);
638 timeoutId = null;
639 };
640
641 return {
642 sync: (shouldShow) => {
643 if (!shouldShow) {
644 clearPendingShow();
645 if (isVisible) {
646 isVisible = false;
647 input.onVisibilityChange(false);
648 }
649 return;
650 }
651
652 if (isVisible || timeoutId !== null) {
653 return;
654 }
655
656 timeoutId = setTimeoutFn(() => {
657 timeoutId = null;
658 isVisible = true;
659 input.onVisibilityChange(true);
660 }, input.delayMs);
661 },
662 dispose: () => {
663 clearPendingShow();
664 },
665 };
666}
667
668export function useThreadJumpHintVisibility(): {
669 showThreadJumpHints: boolean;
670 updateThreadJumpHintsVisibility: (shouldShow: boolean) => void;
671} {
672 const [showThreadJumpHints, setShowThreadJumpHints] = React.useState(false);
673 const controllerRef = React.useRef<ThreadJumpHintVisibilityController | null>(null);
674
675 React.useEffect(() => {
676 const controller = createThreadJumpHintVisibilityController({
677 delayMs: THREAD_JUMP_HINT_SHOW_DELAY_MS,
678 onVisibilityChange: (visible) => {
679 setShowThreadJumpHints(visible);
680 },
681 setTimeoutFn: window.setTimeout.bind(window),
682 clearTimeoutFn: window.clearTimeout.bind(window),
683 });
684 controllerRef.current = controller;
685
686 return () => {
687 controller.dispose();
688 controllerRef.current = null;
689 };
690 }, []);
691
692 const updateThreadJumpHintsVisibility = (shouldShow: boolean) => {
693 controllerRef.current?.sync(shouldShow);
694 };
695
696 return {
697 showThreadJumpHints,
698 updateThreadJumpHintsVisibility,
699 };
700}
701
702export function resolveThreadLastVisitedAt(
703 serverLastVisitedAt: string | null | undefined,
704 localLastVisitedAt: string | undefined,
705): string | undefined {
706 // Server visits override local watermarks, including mark-unread rewinds; use local values only on older
707 // servers.
708 if (serverLastVisitedAt === undefined) return localLastVisitedAt;
709 return serverLastVisitedAt ?? undefined;
710}
711
712export function hasUnseenCompletion(thread: ThreadStatusInput): boolean {
713 if (!thread.latestRun?.completedAt) return false;
714 const completedAt = Date.parse(thread.latestRun.completedAt);
715 if (Number.isNaN(completedAt)) return false;
716 if (!thread.lastVisitedAt) return false;
717
718 const lastVisitedAt = Date.parse(thread.lastVisitedAt);
719 if (Number.isNaN(lastVisitedAt)) return true;
720 return completedAt > lastVisitedAt;
721}
722
723/** Unopened threads' failures still count as unseen, unlike completions. */
724function hasUnseenFailure(thread: ThreadStatusInput): boolean {
725 if (thread.latestRun?.status !== "failed") return false;
726 if (!thread.lastVisitedAt) return true;
727 const completedAt = Date.parse(thread.latestRun.completedAt ?? "");
728 const lastVisitedAt = Date.parse(thread.lastVisitedAt);
729 if (Number.isNaN(completedAt) || Number.isNaN(lastVisitedAt)) return true;
730 return completedAt > lastVisitedAt;
731}
732
733export function shouldClearThreadSelectionOnMouseDown(target: HTMLElement | null): boolean {
734 if (target === null) return true;
735 return !target.closest(THREAD_SELECTION_SAFE_SELECTOR);
736}
737
738// Suppress trailing double-click navigation; keyboard and synthetic clicks use detail 0.
739export function isTrailingDoubleClick(detail: number): boolean {
740 return detail > 1;
741}
742
743function nodeClosest(node: object | null, selector: string): unknown {
744 if (node === null || !("closest" in node) || typeof node.closest !== "function") return null;
745 return node.closest(selector);
746}
747
748export function isSidebarNestedLinkClick(target: EventTarget | null): boolean {
749 if (target == null || typeof target !== "object") return false;
750 if (nodeClosest(target, "a[href]") !== null) return true;
751 const parent =
752 "parentElement" in target &&
753 target.parentElement !== null &&
754 typeof target.parentElement === "object"
755 ? target.parentElement
756 : null;
757 return nodeClosest(parent, "a[href]") !== null;
758}
759
760export function shouldCreateNewThreadInCurrentProject(
761 shiftKey: boolean,
762 projectGroupCount: number,
763): boolean {
764 return shiftKey || projectGroupCount <= 1;
765}
766
767export function orderItemsByPreferredIds<TItem, TId>(input: {
768 items: readonly TItem[];
769 preferredIds: readonly TId[];
770 getId: (item: TItem) => TId;
771 getPreferenceIds?: (item: TItem) => readonly TId[];
772}): TItem[] {
773 const { getId, getPreferenceIds, items, preferredIds } = input;
774 if (preferredIds.length === 0) {
775 return [...items];
776 }
777
778 const indexesByPreferenceId = new Map<TId, number[]>();
779 for (const [index, item] of items.entries()) {
780 const preferenceIds = getPreferenceIds?.(item) ?? [getId(item)];
781 for (const preferenceId of new Set(preferenceIds)) {
782 const indexes = indexesByPreferenceId.get(preferenceId);
783 if (indexes) {
784 indexes.push(index);
785 } else {
786 indexesByPreferenceId.set(preferenceId, [index]);
787 }
788 }
789 }
790
791 const emittedIndexes = new Set<number>();
792 const ordered = preferredIds.flatMap((id) => {
793 const index = indexesByPreferenceId
794 .get(id)
795 ?.find((candidate) => !emittedIndexes.has(candidate));
796 if (index === undefined) {
797 return [];
798 }
799 emittedIndexes.add(index);
800 return [items[index]!];
801 });
802 const remaining = items.filter((_, index) => !emittedIndexes.has(index));
803 return [...ordered, ...remaining];
804}
805
806export function getSidebarThreadIdsToPrewarm<TThreadId>(
807 visibleThreadIds: readonly TThreadId[],
808 limit = SIDEBAR_THREAD_PREWARM_LIMIT,
809): TThreadId[] {
810 return visibleThreadIds.slice(0, Math.max(0, limit));
811}
812
813export function resolveAdjacentThreadId<T>(input: {
814 threadIds: readonly T[];
815 currentThreadId: T | null;
816 direction: ThreadTraversalDirection;
817}): T | null {
818 const { currentThreadId, direction, threadIds } = input;
819
820 if (threadIds.length === 0) {
821 return null;
822 }
823
824 if (currentThreadId === null) {
825 return direction === "previous" ? (threadIds.at(-1) ?? null) : (threadIds[0] ?? null);
826 }
827
828 const currentIndex = threadIds.indexOf(currentThreadId);
829 if (currentIndex === -1) {
830 return null;
831 }
832
833 if (direction === "previous") {
834 return currentIndex > 0 ? (threadIds[currentIndex - 1] ?? null) : null;
835 }
836
837 return currentIndex < threadIds.length - 1 ? (threadIds[currentIndex + 1] ?? null) : null;
838}
839
840export function isContextMenuPointerDown(input: {
841 button: number;
842 ctrlKey: boolean;
843 isMac: boolean;
844}): boolean {
845 if (input.button === 2) return true;
846 return input.isMac && input.button === 0 && input.ctrlKey;
847}
848
849export type SidebarThreadStatus =
850 | "approval"
851 | "input"
852 | "request"
853 | "working"
854 | "waiting"
855 | "failed"
856 | "limited"
857 | "ready";
858
859export function shouldRecedeSidebarThread(input: {
860 status: SidebarThreadStatus;
861 isUnread: boolean;
862 isWoke: boolean;
863 isActive: boolean;
864 isSelected: boolean;
865}): boolean {
866 if (
867 input.isActive ||
868 input.isSelected ||
869 input.status === "input" ||
870 input.status === "request"
871 ) {
872 return false;
873 }
874 if (input.status === "working" || input.status === "waiting") return true;
875 if (input.status === "ready" || input.status === "approval") {
876 return !input.isUnread && !input.isWoke;
877 }
878 return false;
879}
880
881type SidebarThreadStatusInput = Pick<
882 SidebarThreadSummary,
883 | "hasPendingApprovals"
884 | "hasPendingUserInput"
885 | "pendingSubagentRequest"
886 | "pendingGuestMessageCount"
887 | "runtime"
888 | "blockedOnThreadWait"
889>;
890
891export function resolveSidebarThreadStatus(thread: SidebarThreadStatusInput): SidebarThreadStatus {
892 if (thread.hasPendingApprovals || thread.pendingSubagentRequest === "approval") {
893 return "approval";
894 }
895 if (thread.hasPendingUserInput || thread.pendingSubagentRequest === "user_input") {
896 return "input";
897 }
898 // A guest is waiting on the owner; the agent's own requests come first.
899 if ((thread.pendingGuestMessageCount ?? 0) > 0) {
900 return "request";
901 }
902 if (thread.runtime?.status === "running" && thread.blockedOnThreadWait === true) {
903 return "waiting";
904 }
905 if (
906 thread.runtime !== null &&
907 ["preparing", "queued", "starting", "running", "waiting"].includes(thread.runtime.status)
908 ) {
909 return "working";
910 }
911 if (thread.runtime?.status === "idle") {
912 return "waiting";
913 }
914 if (thread.runtime?.status === "failed") {
915 return thread.runtime.lastErrorClass === "usage_limit" ? "limited" : "failed";
916 }
917 return "ready";
918}
919
920export type SidebarV2TopStatusKind =
921 | "approval"
922 | "done"
923 | "failed"
924 | "limited"
925 | "input"
926 | "request"
927 | "waiting"
928 | "woke"
929 | "working";
930
931export function resolveSidebarV2TopStatus(input: {
932 readonly status: SidebarThreadStatus;
933 readonly isUnread: boolean;
934 readonly isWoke: boolean;
935}): SidebarV2TopStatusKind | null {
936 if (input.status === "working") {
937 return "working";
938 }
939 if (input.status === "waiting") {
940 return "waiting";
941 }
942 if (input.status === "approval") {
943 return "approval";
944 }
945 if (input.status === "input" || input.status === "request") {
946 return input.status;
947 }
948 if (input.status === "failed" || input.status === "limited") {
949 return input.status;
950 }
951 if (input.isWoke) {
952 return "woke";
953 }
954 return input.isUnread ? "done" : null;
955}
956
957export function firstValidTimestampMs(
958 ...candidates: ReadonlyArray<string | null | undefined>
959): number {
960 for (const candidate of candidates) {
961 if (candidate == null) continue;
962 const parsed = Date.parse(candidate);
963 if (!Number.isNaN(parsed)) return parsed;
964 }
965 return 0;
966}
967
968export { sortActiveThreadsByOrderKey as sortThreadsForSidebar } from "@t3tools/client-runtime/state/thread-sort";
969export {
970 isThreadWorking as isSidebarThreadWorking,
971 sortInboxThreadsByReturn,
972 sortWorkingThreadsBySend,
973} from "@t3tools/client-runtime/state/thread-inbox";
974
975export { pinOrderKeyBetween } from "@t3tools/client-runtime/state/thread-sort";
976export { sortPinnedThreadsByOrderKey as sortPinnedThreadsForSidebar } from "@t3tools/client-runtime/state/thread-sort";
977
978const EMPTY_CONTENT_MATCH_KEYS: ReadonlySet<string> = new Set<string>();
979
980/**
981 * Sidebar search results: title, branch, and pull request matches ranked as
982 * the command palette ranks them, then threads listed only because their
983 * messages match, in `contentMatchKeys` order.
984 */
985export function searchSidebarThreads<
986 T extends ThreadSearchShell & {
987 readonly environmentId: EnvironmentId;
988 readonly id: ThreadId;
989 },
990>(
991 threads: readonly T[],
992 query: string,
993 contentMatchKeys: ReadonlySet<string> = EMPTY_CONTENT_MATCH_KEYS,
994 now = Date.now(),
995): { readonly titleMatches: T[]; readonly contentMatches: T[] } {
996 const normalizedQuery = foldSearchQuery(query);
997 if (normalizedQuery.length === 0) return { titleMatches: [], contentMatches: [] };
998 const titleMatches = rankSearchItems(threads, (thread, options) =>
999 scoreThreadSearch(normalizedQuery, threadSearchSubject(thread, null), now, {
1000 ...options,
1001 picks: false,
1002 }),
1003 ).map(({ item }) => item);
1004 const listed = new Set(titleMatches);
1005 // In the order the server ranked their messages, as the palette lists them.
1006 const threadByKey = new Map(
1007 threads.map((thread) => [
1008 threadSearchMatchKey({ environmentId: thread.environmentId, threadId: thread.id }),
1009 thread,
1010 ]),
1011 );
1012 const contentMatches = [...contentMatchKeys].flatMap((key) => {
1013 const thread = threadByKey.get(key);
1014 return thread && !listed.has(thread) ? [thread] : [];
1015 });
1016 return { titleMatches, contentMatches };
1017}
1018
1019export function pullRequestMatchesSearchQuery(
1020 pullRequest: Parameters<typeof threadPullRequestSearchTerms>[0],
1021 query: string,
1022): boolean {
1023 const normalizedQuery = normalizeSearchText(query);
1024 if (normalizedQuery.length === 0) return false;
1025 const haystack = normalizeSearchText(threadPullRequestSearchTerms(pullRequest).join(" "));
1026 return normalizedQuery.split(" ").every((token) => haystack.includes(token));
1027}
1028
1029export function filterSidebarProjectScopeItems<TItem extends { readonly value: string }>(input: {
1030 items: readonly TItem[];
1031 query: string;
1032 matches: (item: TItem, query: string) => boolean;
1033}): readonly TItem[] {
1034 const query = input.query.trim();
1035 if (query.length === 0) return input.items;
1036 return input.items.filter((item) => item.value !== "all" && input.matches(item, query));
1037}
1038
1039export interface SidebarProjectScopeMenuState {
1040 readonly open: boolean;
1041 readonly query: string;
1042}
1043
1044export type SidebarProjectScopeMenuAction =
1045 | { readonly type: "query-changed"; readonly query: string }
1046 | { readonly type: "open-changed"; readonly open: boolean }
1047 | { readonly type: "project-settings-opened" };
1048
1049export function reduceSidebarProjectScopeMenuState(
1050 state: SidebarProjectScopeMenuState,
1051 action: SidebarProjectScopeMenuAction,
1052): SidebarProjectScopeMenuState {
1053 switch (action.type) {
1054 case "query-changed":
1055 return { ...state, query: action.query };
1056 case "open-changed":
1057 return { open: action.open, query: "" };
1058 case "project-settings-opened":
1059 return { open: false, query: "" };
1060 }
1061}
1062
1063export function resolveWorkingStartedAt(
1064 thread: Pick<SidebarThreadSummary, "latestRun" | "runtime">,
1065): string | null {
1066 return resolveThreadWorkingStartedAt(thread);
1067}
1068
1069export function resolveThreadStatusPill(input: {
1070 thread: ThreadStatusInput;
1071}): ThreadStatusPill | null {
1072 const { thread } = input;
1073
1074 if (thread.hasPendingApprovals || thread.pendingSubagentRequest === "approval") {
1075 return {
1076 label: "Pending Approval",
1077 colorClass: "text-amber-600 dark:text-amber-300/90",
1078 dotClass: "bg-amber-500 dark:bg-amber-300/90",
1079 pulse: false,
1080 };
1081 }
1082
1083 if (thread.hasPendingUserInput || thread.pendingSubagentRequest === "user_input") {
1084 return {
1085 label: "Awaiting Input",
1086 colorClass: "text-indigo-600 dark:text-indigo-300/90",
1087 dotClass: "bg-indigo-500 dark:bg-indigo-300/90",
1088 pulse: false,
1089 };
1090 }
1091
1092 if ((thread.pendingGuestMessageCount ?? 0) > 0) {
1093 return {
1094 label: "Guest Request",
1095 colorClass: "text-guest-foreground",
1096 dotClass: "bg-guest",
1097 pulse: false,
1098 };
1099 }
1100
1101 if (
1102 (thread.runtime?.status === "running" && thread.blockedOnThreadWait !== true) ||
1103 thread.runtime?.status === "waiting"
1104 ) {
1105 return {
1106 label: "Working",
1107 colorClass: "text-sky-600 dark:text-sky-300/80",
1108 dotClass: "bg-sky-500 dark:bg-sky-300/80",
1109 pulse: true,
1110 };
1111 }
1112
1113 if (
1114 thread.runtime?.status === "preparing" ||
1115 thread.runtime?.status === "starting" ||
1116 thread.runtime?.status === "queued"
1117 ) {
1118 return {
1119 label: "Connecting",
1120 colorClass: "text-sky-600 dark:text-sky-300/80",
1121 dotClass: "bg-sky-500 dark:bg-sky-300/80",
1122 pulse: true,
1123 };
1124 }
1125
1126 if (
1127 (thread.runtime?.status === "running" && thread.blockedOnThreadWait === true) ||
1128 backgroundWorkHoldsCompletion(thread.pendingBackgroundTasks ?? [])
1129 ) {
1130 return {
1131 label: "Waiting",
1132 colorClass: "text-sidebar-muted-foreground",
1133 dotClass: "bg-sidebar-muted-foreground",
1134 pulse: false,
1135 };
1136 }
1137
1138 if (hasUnseenFailure(thread)) {
1139 return {
1140 label: "Failed",
1141 colorClass: "text-red-600 dark:text-red-300/90",
1142 dotClass: "bg-red-500 dark:bg-red-300/90",
1143 pulse: false,
1144 };
1145 }
1146
1147 const hasPlanReadyPrompt =
1148 !thread.hasPendingUserInput &&
1149 thread.interactionMode === "plan" &&
1150 isLatestRunSettled(thread.latestRun, thread.runtime) &&
1151 thread.hasActionableProposedPlan;
1152 if (hasPlanReadyPrompt) {
1153 return {
1154 label: "Plan Ready",
1155 colorClass: "text-violet-600 dark:text-violet-300/90",
1156 dotClass: "bg-violet-500 dark:bg-violet-300/90",
1157 pulse: false,
1158 };
1159 }
1160
1161 if (hasUnseenCompletion(thread)) {
1162 return {
1163 label: "Completed",
1164 colorClass: "text-emerald-600 dark:text-emerald-300/90",
1165 dotClass: "bg-emerald-500 dark:bg-emerald-300/90",
1166 pulse: false,
1167 };
1168 }
1169
1170 return null;
1171}
1172
1173export function resolveProjectStatusIndicator(
1174 statuses: ReadonlyArray<ThreadStatusPill | null>,
1175): ThreadStatusPill | null {
1176 let highestPriorityStatus: ThreadStatusPill | null = null;
1177
1178 for (const status of statuses) {
1179 if (status === null) continue;
1180 if (
1181 highestPriorityStatus === null ||
1182 THREAD_STATUS_PRIORITY[status.label] > THREAD_STATUS_PRIORITY[highestPriorityStatus.label]
1183 ) {
1184 highestPriorityStatus = status;
1185 }
1186 }
1187
1188 return highestPriorityStatus;
1189}
1190
1191export function getFallbackThreadIdAfterDelete<
1192 T extends Pick<Thread, "id" | "projectId" | "createdAt" | "updatedAt"> & ThreadSortInput,
1193>(input: {
1194 threads: readonly T[];
1195 deletedThreadId: T["id"];
1196 sortOrder: SidebarThreadSortOrder;
1197 deletedThreadIds?: ReadonlySet<T["id"]>;
1198}): T["id"] | null {
1199 const { deletedThreadId, deletedThreadIds, sortOrder, threads } = input;
1200 const deletedThread = threads.find((thread) => thread.id === deletedThreadId);
1201 if (!deletedThread) {
1202 return null;
1203 }
1204
1205 return (
1206 sortThreads(
1207 threads.filter(
1208 (thread) =>
1209 thread.projectId === deletedThread.projectId &&
1210 thread.id !== deletedThreadId &&
1211 !deletedThreadIds?.has(thread.id),
1212 ),
1213 sortOrder,
1214 )[0]?.id ?? null
1215 );
1216}
1217function getProjectSortTimestamp(
1218 project: SidebarProject,
1219 projectThreads: readonly ThreadSortInput[],
1220 sortOrder: Exclude<SidebarProjectSortOrder, "manual">,
1221): number {
1222 if (projectThreads.length > 0) {
1223 return projectThreads.reduce(
1224 (latest, thread) => Math.max(latest, getThreadSortTimestamp(thread, sortOrder)),
1225 Number.NEGATIVE_INFINITY,
1226 );
1227 }
1228
1229 if (sortOrder === "created_at") {
1230 return toSortableTimestamp(project.createdAt) ?? Number.NEGATIVE_INFINITY;
1231 }
1232 return toSortableTimestamp(project.updatedAt ?? project.createdAt) ?? Number.NEGATIVE_INFINITY;
1233}
1234
1235function sortProjectsByActivity<TProject extends SidebarProject>(
1236 projects: readonly TProject[],
1237 sortOrder: SidebarProjectSortOrder,
1238 getProjectThreads: (project: TProject) => readonly ThreadSortInput[],
1239 compareTies: (left: TProject, right: TProject) => number,
1240): TProject[] {
1241 if (sortOrder === "manual") {
1242 return [...projects];
1243 }
1244
1245 // Project timestamps scan all threads; compute once per project instead of per comparison.
1246 return projects
1247 .map((project) => ({
1248 project,
1249 timestamp: getProjectSortTimestamp(project, getProjectThreads(project), sortOrder),
1250 }))
1251 .sort((left, right) => {
1252 const byTimestamp =
1253 right.timestamp === left.timestamp ? 0 : right.timestamp > left.timestamp ? 1 : -1;
1254 return byTimestamp || compareTies(left.project, right.project);
1255 })
1256 .map(({ project }) => project);
1257}
1258
1259export function sortProjectsForSidebar<
1260 TProject extends SidebarProject,
1261 TThread extends Pick<Thread, "projectId" | "createdAt" | "updatedAt"> & ThreadSortInput,
1262>(
1263 projects: readonly TProject[],
1264 threads: readonly TThread[],
1265 sortOrder: SidebarProjectSortOrder,
1266): TProject[] {
1267 const threadsByProjectId = new Map<string, TThread[]>();
1268 for (const thread of threads) {
1269 const existing = threadsByProjectId.get(thread.projectId) ?? [];
1270 existing.push(thread);
1271 threadsByProjectId.set(thread.projectId, existing);
1272 }
1273
1274 return sortProjectsByActivity(
1275 projects,
1276 sortOrder,
1277 (project) => threadsByProjectId.get(project.id) ?? [],
1278 (left, right) => left.title.localeCompare(right.title) || left.id.localeCompare(right.id),
1279 );
1280}
1281
1282export function sortLogicalProjectsForSidebar<
1283 TProject extends LogicalSidebarProject,
1284 TThread extends ScopedSidebarThread,
1285>(
1286 projects: readonly TProject[],
1287 threads: readonly TThread[],
1288 sortOrder: SidebarProjectSortOrder,
1289): TProject[] {
1290 const groupKeyByProjectRef = new Map(
1291 projects.flatMap((project) =>
1292 project.memberProjectRefs.map(
1293 (projectRef) =>
1294 [`${projectRef.environmentId}\0${projectRef.projectId}`, project.projectKey] as const,
1295 ),
1296 ),
1297 );
1298 const threadsByProjectKey = new Map<string, TThread[]>();
1299 for (const thread of threads) {
1300 if (thread.archivedAt !== null) continue;
1301 const projectKey = groupKeyByProjectRef.get(`${thread.environmentId}\0${thread.projectId}`);
1302 if (!projectKey) continue;
1303 const existing = threadsByProjectKey.get(projectKey);
1304 if (existing) {
1305 existing.push(thread);
1306 } else {
1307 threadsByProjectKey.set(projectKey, [thread]);
1308 }
1309 }
1310
1311 return sortProjectsByActivity(
1312 projects,
1313 sortOrder,
1314 (project) => threadsByProjectKey.get(project.projectKey) ?? [],
1315 (left, right) =>
1316 left.title.localeCompare(right.title) || left.projectKey.localeCompare(right.projectKey),
1317 );
1318}
1319
1320export function sortSidebarV2ProjectGroups<
1321 TProject extends LogicalSidebarProject,
1322 TThread extends ScopedSidebarThread & Pick<SidebarThreadSummary, "lineage">,
1323>(
1324 projects: readonly TProject[],
1325 threads: readonly TThread[],
1326 sortOrder: SidebarProjectSortOrder,
1327): TProject[] {
1328 return sortLogicalProjectsForSidebar(
1329 projects,
1330 filterSidebarV2VisibleThreads(threads, null),
1331 sortOrder,
1332 );
1333}
1334
1335export function sortScopedProjectsForSidebar<
1336 TProject extends ScopedSidebarProject,
1337 TThread extends ScopedSidebarThread,
1338>(
1339 projects: readonly TProject[],
1340 threads: readonly TThread[],
1341 sortOrder: SidebarProjectSortOrder,
1342): TProject[] {
1343 const scopedKey = (environmentId: string, projectId: string) =>
1344 `${environmentId}\u0000${projectId}`;
1345 const threadsByProject = new Map<string, TThread[]>();
1346 for (const thread of threads) {
1347 if (thread.archivedAt !== null) {
1348 continue;
1349 }
1350 const key = scopedKey(thread.environmentId, thread.projectId);
1351 const existing = threadsByProject.get(key) ?? [];
1352 existing.push(thread);
1353 threadsByProject.set(key, existing);
1354 }
1355
1356 return sortProjectsByActivity(
1357 projects,
1358 sortOrder,
1359 (project) => threadsByProject.get(scopedKey(project.environmentId, project.id)) ?? [],
1360 (left, right) =>
1361 left.title.localeCompare(right.title) ||
1362 left.environmentId.localeCompare(right.environmentId) ||
1363 left.id.localeCompare(right.id),
1364 );
1365}