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

Sidebar.logic.ts

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