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

Sidebar.logic.ts

1,360 lines43.3 KB

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