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