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";
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 );
51}
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 };
66}
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 };
92}
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);
99}
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);
116}
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;
147}
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;
159}
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";
178}
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}`;
193}
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);
201}
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;
214}
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 };
250}
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";
287}
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);
299}
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;
310}
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 }
419}
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 };
456}
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 };
510}
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 };
542}
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 ];
557}
558
559export function isSidebarSubagentThread(thread: Pick<SidebarThreadSummary, "lineage">): boolean {
560 return thread.lineage.relationshipToParent === "subagent";
561}
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;
581}
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 );
596}
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 };
614}
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})` };
621}
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;
637}
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 // The clock is read inside the updater: the compiler caches a bare clock read
674 // in render once per instance, so a second hold would reuse the first deadline.
675 // React discards this render and re-runs with the update.
676 if (shouldShow !== (showAt !== null)) {
677 setShowAt(shouldShow ? () => deadlineAfter(THREAD_JUMP_HINT_SHOW_DELAY_MS) : null);
678 }
679 return useDeadlinePassed(showAt);
680}
681
682export function resolveThreadLastVisitedAt(
683 serverLastVisitedAt: string | null | undefined,
684 localLastVisitedAt: string | undefined,
685): string | undefined {
686 // Server visits override local watermarks, including mark-unread rewinds; use local values only on older
687 // servers.
688 if (serverLastVisitedAt === undefined) return localLastVisitedAt;
689 return serverLastVisitedAt ?? undefined;
690}
691
692export function hasUnseenCompletion(thread: ThreadStatusInput): boolean {
693 if (!thread.latestRun?.completedAt) return false;
694 const completedAt = Date.parse(thread.latestRun.completedAt);
695 if (Number.isNaN(completedAt)) return false;
696 if (!thread.lastVisitedAt) return false;
697
698 const lastVisitedAt = Date.parse(thread.lastVisitedAt);
699 if (Number.isNaN(lastVisitedAt)) return true;
700 return completedAt > lastVisitedAt;
701}
702
703/** Unopened threads' failures still count as unseen, unlike completions. */
704function hasUnseenFailure(thread: ThreadStatusInput): boolean {
705 if (thread.latestRun?.status !== "failed") return false;
706 if (!thread.lastVisitedAt) return true;
707 const completedAt = Date.parse(thread.latestRun.completedAt ?? "");
708 const lastVisitedAt = Date.parse(thread.lastVisitedAt);
709 if (Number.isNaN(completedAt) || Number.isNaN(lastVisitedAt)) return true;
710 return completedAt > lastVisitedAt;
711}
712
713export function shouldClearThreadSelectionOnMouseDown(target: HTMLElement | null): boolean {
714 if (target === null) return true;
715 return !target.closest(THREAD_SELECTION_SAFE_SELECTOR);
716}
717
718// Suppress trailing double-click navigation; keyboard and synthetic clicks use detail 0.
719export function isTrailingDoubleClick(detail: number): boolean {
720 return detail > 1;
721}
722
723function nodeClosest(node: object | null, selector: string): unknown {
724 if (node === null || !("closest" in node) || typeof node.closest !== "function") return null;
725 return node.closest(selector);
726}
727
728export function isSidebarNestedLinkClick(target: EventTarget | null): boolean {
729 if (target == null || typeof target !== "object") return false;
730 if (nodeClosest(target, "a[href]") !== null) return true;
731 const parent =
732 "parentElement" in target &&
733 target.parentElement !== null &&
734 typeof target.parentElement === "object"
735 ? target.parentElement
736 : null;
737 return nodeClosest(parent, "a[href]") !== null;
738}
739
740export function shouldCreateNewThreadInCurrentProject(
741 shiftKey: boolean,
742 projectGroupCount: number,
743): boolean {
744 return shiftKey || projectGroupCount <= 1;
745}
746
747export function orderItemsByPreferredIds<TItem, TId>(input: {
748 items: readonly TItem[];
749 preferredIds: readonly TId[];
750 getId: (item: TItem) => TId;
751 getPreferenceIds?: (item: TItem) => readonly TId[];
752}): TItem[] {
753 const { getId, getPreferenceIds, items, preferredIds } = input;
754 if (preferredIds.length === 0) {
755 return [...items];
756 }
757
758 const indexesByPreferenceId = new Map<TId, number[]>();
759 for (const [index, item] of items.entries()) {
760 const preferenceIds = getPreferenceIds?.(item) ?? [getId(item)];
761 for (const preferenceId of new Set(preferenceIds)) {
762 const indexes = indexesByPreferenceId.get(preferenceId);
763 if (indexes) {
764 indexes.push(index);
765 } else {
766 indexesByPreferenceId.set(preferenceId, [index]);
767 }
768 }
769 }
770
771 const emittedIndexes = new Set<number>();
772 const ordered = preferredIds.flatMap((id) => {
773 const index = indexesByPreferenceId
774 .get(id)
775 ?.find((candidate) => !emittedIndexes.has(candidate));
776 if (index === undefined) {
777 return [];
778 }
779 emittedIndexes.add(index);
780 return [items[index]!];
781 });
782 const remaining = items.filter((_, index) => !emittedIndexes.has(index));
783 return [...ordered, ...remaining];
784}
785
786export function getSidebarThreadIdsToPrewarm<TThreadId>(
787 visibleThreadIds: readonly TThreadId[],
788 limit = SIDEBAR_THREAD_PREWARM_LIMIT,
789): TThreadId[] {
790 return visibleThreadIds.slice(0, Math.max(0, limit));
791}
792
793export function resolveAdjacentThreadId<T>(input: {
794 threadIds: readonly T[];
795 currentThreadId: T | null;
796 direction: ThreadTraversalDirection;
797}): T | null {
798 const { currentThreadId, direction, threadIds } = input;
799
800 if (threadIds.length === 0) {
801 return null;
802 }
803
804 if (currentThreadId === null) {
805 return direction === "previous" ? (threadIds.at(-1) ?? null) : (threadIds[0] ?? null);
806 }
807
808 const currentIndex = threadIds.indexOf(currentThreadId);
809 if (currentIndex === -1) {
810 return null;
811 }
812
813 if (direction === "previous") {
814 return currentIndex > 0 ? (threadIds[currentIndex - 1] ?? null) : null;
815 }
816
817 return currentIndex < threadIds.length - 1 ? (threadIds[currentIndex + 1] ?? null) : null;
818}
819
820export function isContextMenuPointerDown(input: {
821 button: number;
822 ctrlKey: boolean;
823 isMac: boolean;
824}): boolean {
825 if (input.button === 2) return true;
826 return input.isMac && input.button === 0 && input.ctrlKey;
827}
828
829export type SidebarThreadStatus =
830 | "approval"
831 | "input"
832 | "request"
833 | "working"
834 | "waiting"
835 | "failed"
836 | "limited"
837 | "ready";
838
839export function shouldRecedeSidebarThread(input: {
840 status: SidebarThreadStatus;
841 isUnread: boolean;
842 isWoke: boolean;
843 isActive: boolean;
844 isSelected: boolean;
845}): boolean {
846 if (
847 input.isActive ||
848 input.isSelected ||
849 input.status === "input" ||
850 input.status === "request"
851 ) {
852 return false;
853 }
854 if (input.status === "working" || input.status === "waiting") return true;
855 if (input.status === "ready" || input.status === "approval") {
856 return !input.isUnread && !input.isWoke;
857 }
858 return false;
859}
860
861type SidebarThreadStatusInput = Pick<
862 SidebarThreadSummary,
863 | "hasPendingApprovals"
864 | "hasPendingUserInput"
865 | "pendingSubagentRequest"
866 | "pendingGuestMessageCount"
867 | "runtime"
868 | "blockedOnThreadWait"
869>;
870
871export function resolveSidebarThreadStatus(thread: SidebarThreadStatusInput): SidebarThreadStatus {
872 if (thread.hasPendingApprovals || thread.pendingSubagentRequest === "approval") {
873 return "approval";
874 }
875 if (thread.hasPendingUserInput || thread.pendingSubagentRequest === "user_input") {
876 return "input";
877 }
878 // A guest is waiting on the owner; the agent's own requests come first.
879 if ((thread.pendingGuestMessageCount ?? 0) > 0) {
880 return "request";
881 }
882 if (thread.runtime?.status === "running" && thread.blockedOnThreadWait === true) {
883 return "waiting";
884 }
885 if (
886 thread.runtime !== null &&
887 ["preparing", "queued", "starting", "running", "waiting"].includes(thread.runtime.status)
888 ) {
889 return "working";
890 }
891 if (thread.runtime?.status === "idle") {
892 return "waiting";
893 }
894 if (thread.runtime?.status === "failed") {
895 return thread.runtime.lastErrorClass === "usage_limit" ? "limited" : "failed";
896 }
897 return "ready";
898}
899
900export type SidebarV2TopStatusKind =
901 | "approval"
902 | "done"
903 | "failed"
904 | "limited"
905 | "input"
906 | "request"
907 | "waiting"
908 | "woke"
909 | "working";
910
911export function resolveSidebarV2TopStatus(input: {
912 readonly status: SidebarThreadStatus;
913 readonly isUnread: boolean;
914 readonly isWoke: boolean;
915}): SidebarV2TopStatusKind | null {
916 if (input.status === "working") {
917 return "working";
918 }
919 if (input.status === "waiting") {
920 return "waiting";
921 }
922 if (input.status === "approval") {
923 return "approval";
924 }
925 if (input.status === "input" || input.status === "request") {
926 return input.status;
927 }
928 if (input.status === "failed" || input.status === "limited") {
929 return input.status;
930 }
931 if (input.isWoke) {
932 return "woke";
933 }
934 return input.isUnread ? "done" : null;
935}
936
937export function firstValidTimestampMs(
938 ...candidates: ReadonlyArray<string | null | undefined>
939): number {
940 for (const candidate of candidates) {
941 if (candidate == null) continue;
942 const parsed = Date.parse(candidate);
943 if (!Number.isNaN(parsed)) return parsed;
944 }
945 return 0;
946}
947
948export { sortActiveThreadsByOrderKey as sortThreadsForSidebar } from "@t3tools/client-runtime/state/thread-sort";
949export {
950 isThreadWorking as isSidebarThreadWorking,
951 sortInboxThreadsByReturn,
952 sortWorkingThreadsBySend,
953} from "@t3tools/client-runtime/state/thread-inbox";
954
955export { pinOrderKeyBetween } from "@t3tools/client-runtime/state/thread-sort";
956export { sortPinnedThreadsByOrderKey as sortPinnedThreadsForSidebar } from "@t3tools/client-runtime/state/thread-sort";
957
958const EMPTY_CONTENT_MATCH_KEYS: ReadonlySet<string> = new Set<string>();
959
960/**
961 * Sidebar search results: title, branch, and pull request matches ranked as
962 * the command palette ranks them, then threads listed only because their
963 * messages match, in `contentMatchKeys` order.
964 */
965export function searchSidebarThreads<
966 T extends ThreadSearchShell & {
967 readonly environmentId: EnvironmentId;
968 readonly id: ThreadId;
969 },
970>(
971 threads: readonly T[],
972 query: string,
973 contentMatchKeys: ReadonlySet<string> = EMPTY_CONTENT_MATCH_KEYS,
974 now = Date.now(),
975): { readonly titleMatches: T[]; readonly contentMatches: T[] } {
976 const normalizedQuery = foldSearchQuery(query);
977 if (normalizedQuery.length === 0) return { titleMatches: [], contentMatches: [] };
978 const titleMatches = rankSearchItems(threads, (thread, options) =>
979 scoreThreadSearch(normalizedQuery, threadSearchSubject(thread, null), now, {
980 ...options,
981 picks: false,
982 }),
983 ).map(({ item }) => item);
984 const listed = new Set(titleMatches);
985 // In the order the server ranked their messages, as the palette lists them.
986 const threadByKey = new Map(
987 threads.map((thread) => [
988 threadSearchMatchKey({ environmentId: thread.environmentId, threadId: thread.id }),
989 thread,
990 ]),
991 );
992 const contentMatches = [...contentMatchKeys].flatMap((key) => {
993 const thread = threadByKey.get(key);
994 return thread && !listed.has(thread) ? [thread] : [];
995 });
996 return { titleMatches, contentMatches };
997}
998
999export function pullRequestMatchesSearchQuery(
1000 pullRequest: Parameters<typeof threadPullRequestSearchTerms>[0],
1001 query: string,
1002): boolean {
1003 const normalizedQuery = normalizeSearchText(query);
1004 if (normalizedQuery.length === 0) return false;
1005 const haystack = normalizeSearchText(threadPullRequestSearchTerms(pullRequest).join(" "));
1006 return normalizedQuery.split(" ").every((token) => haystack.includes(token));
1007}
1008
1009export function filterSidebarProjectScopeItems<TItem extends { readonly value: string }>(input: {
1010 items: readonly TItem[];
1011 query: string;
1012 matches: (item: TItem, query: string) => boolean;
1013}): readonly TItem[] {
1014 const query = input.query.trim();
1015 if (query.length === 0) return input.items;
1016 return input.items.filter((item) => item.value !== "all" && input.matches(item, query));
1017}
1018
1019export interface SidebarProjectScopeMenuState {
1020 readonly open: boolean;
1021 readonly query: string;
1022}
1023
1024export type SidebarProjectScopeMenuAction =
1025 | { readonly type: "query-changed"; readonly query: string }
1026 | { readonly type: "open-changed"; readonly open: boolean }
1027 | { readonly type: "project-settings-opened" };
1028
1029export function reduceSidebarProjectScopeMenuState(
1030 state: SidebarProjectScopeMenuState,
1031 action: SidebarProjectScopeMenuAction,
1032): SidebarProjectScopeMenuState {
1033 switch (action.type) {
1034 case "query-changed":
1035 return { ...state, query: action.query };
1036 case "open-changed":
1037 return { open: action.open, query: "" };
1038 case "project-settings-opened":
1039 return { open: false, query: "" };
1040 }
1041}
1042
1043export function resolveWorkingStartedAt(
1044 thread: Pick<SidebarThreadSummary, "latestRun" | "runtime">,
1045): string | null {
1046 return resolveThreadWorkingStartedAt(thread);
1047}
1048
1049export function resolveThreadStatusPill(input: {
1050 thread: ThreadStatusInput;
1051}): ThreadStatusPill | null {
1052 const { thread } = input;
1053
1054 if (thread.hasPendingApprovals || thread.pendingSubagentRequest === "approval") {
1055 return {
1056 label: "Pending Approval",
1057 colorClass: "text-amber-600 dark:text-amber-300/90",
1058 dotClass: "bg-amber-500 dark:bg-amber-300/90",
1059 pulse: false,
1060 };
1061 }
1062
1063 if (thread.hasPendingUserInput || thread.pendingSubagentRequest === "user_input") {
1064 return {
1065 label: "Awaiting Input",
1066 colorClass: "text-indigo-600 dark:text-indigo-300/90",
1067 dotClass: "bg-indigo-500 dark:bg-indigo-300/90",
1068 pulse: false,
1069 };
1070 }
1071
1072 if ((thread.pendingGuestMessageCount ?? 0) > 0) {
1073 return {
1074 label: "Guest Request",
1075 colorClass: "text-guest-foreground",
1076 dotClass: "bg-guest",
1077 pulse: false,
1078 };
1079 }
1080
1081 if (
1082 (thread.runtime?.status === "running" && thread.blockedOnThreadWait !== true) ||
1083 thread.runtime?.status === "waiting"
1084 ) {
1085 return {
1086 label: "Working",
1087 colorClass: "text-sky-600 dark:text-sky-300/80",
1088 dotClass: "bg-sky-500 dark:bg-sky-300/80",
1089 pulse: true,
1090 };
1091 }
1092
1093 if (
1094 thread.runtime?.status === "preparing" ||
1095 thread.runtime?.status === "starting" ||
1096 thread.runtime?.status === "queued"
1097 ) {
1098 return {
1099 label: "Connecting",
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 === "running" && thread.blockedOnThreadWait === true) ||
1108 backgroundWorkHoldsCompletion(thread.pendingBackgroundTasks ?? [])
1109 ) {
1110 return {
1111 label: "Waiting",
1112 colorClass: "text-sidebar-muted-foreground",
1113 dotClass: "bg-sidebar-muted-foreground",
1114 pulse: false,
1115 };
1116 }
1117
1118 if (hasUnseenFailure(thread)) {
1119 return {
1120 label: "Failed",
1121 colorClass: "text-red-600 dark:text-red-300/90",
1122 dotClass: "bg-red-500 dark:bg-red-300/90",
1123 pulse: false,
1124 };
1125 }
1126
1127 const hasPlanReadyPrompt =
1128 !thread.hasPendingUserInput &&
1129 thread.interactionMode === "plan" &&
1130 isLatestRunSettled(thread.latestRun, thread.runtime) &&
1131 thread.hasActionableProposedPlan;
1132 if (hasPlanReadyPrompt) {
1133 return {
1134 label: "Plan Ready",
1135 colorClass: "text-violet-600 dark:text-violet-300/90",
1136 dotClass: "bg-violet-500 dark:bg-violet-300/90",
1137 pulse: false,
1138 };
1139 }
1140
1141 if (hasUnseenCompletion(thread)) {
1142 return {
1143 label: "Completed",
1144 colorClass: "text-emerald-600 dark:text-emerald-300/90",
1145 dotClass: "bg-emerald-500 dark:bg-emerald-300/90",
1146 pulse: false,
1147 };
1148 }
1149
1150 return null;
1151}
1152
1153export function resolveProjectStatusIndicator(
1154 statuses: ReadonlyArray<ThreadStatusPill | null>,
1155): ThreadStatusPill | null {
1156 let highestPriorityStatus: ThreadStatusPill | null = null;
1157
1158 for (const status of statuses) {
1159 if (status === null) continue;
1160 if (
1161 highestPriorityStatus === null ||
1162 THREAD_STATUS_PRIORITY[status.label] > THREAD_STATUS_PRIORITY[highestPriorityStatus.label]
1163 ) {
1164 highestPriorityStatus = status;
1165 }
1166 }
1167
1168 return highestPriorityStatus;
1169}
1170
1171export function getFallbackThreadIdAfterDelete<
1172 T extends Pick<Thread, "id" | "projectId" | "createdAt" | "updatedAt"> & ThreadSortInput,
1173>(input: {
1174 threads: readonly T[];
1175 deletedThreadId: T["id"];
1176 sortOrder: SidebarThreadSortOrder;
1177 deletedThreadIds?: ReadonlySet<T["id"]>;
1178}): T["id"] | null {
1179 const { deletedThreadId, deletedThreadIds, sortOrder, threads } = input;
1180 const deletedThread = threads.find((thread) => thread.id === deletedThreadId);
1181 if (!deletedThread) {
1182 return null;
1183 }
1184
1185 return (
1186 sortThreads(
1187 threads.filter(
1188 (thread) =>
1189 thread.projectId === deletedThread.projectId &&
1190 thread.id !== deletedThreadId &&
1191 !deletedThreadIds?.has(thread.id),
1192 ),
1193 sortOrder,
1194 )[0]?.id ?? null
1195 );
1196}
1197function getProjectSortTimestamp(
1198 project: SidebarProject,
1199 projectThreads: readonly ThreadSortInput[],
1200 sortOrder: Exclude<SidebarProjectSortOrder, "manual">,
1201): number {
1202 if (projectThreads.length > 0) {
1203 return projectThreads.reduce(
1204 (latest, thread) => Math.max(latest, getThreadSortTimestamp(thread, sortOrder)),
1205 Number.NEGATIVE_INFINITY,
1206 );
1207 }
1208
1209 if (sortOrder === "created_at") {
1210 return toSortableTimestamp(project.createdAt) ?? Number.NEGATIVE_INFINITY;
1211 }
1212 return toSortableTimestamp(project.updatedAt ?? project.createdAt) ?? Number.NEGATIVE_INFINITY;
1213}
1214
1215function sortProjectsByActivity<TProject extends SidebarProject>(
1216 projects: readonly TProject[],
1217 sortOrder: SidebarProjectSortOrder,
1218 getProjectThreads: (project: TProject) => readonly ThreadSortInput[],
1219 compareTies: (left: TProject, right: TProject) => number,
1220): TProject[] {
1221 if (sortOrder === "manual") {
1222 return [...projects];
1223 }
1224
1225 // Project timestamps scan all threads; compute once per project instead of per comparison.
1226 return projects
1227 .map((project) => ({
1228 project,
1229 timestamp: getProjectSortTimestamp(project, getProjectThreads(project), sortOrder),
1230 }))
1231 .sort((left, right) => {
1232 const byTimestamp =
1233 right.timestamp === left.timestamp ? 0 : right.timestamp > left.timestamp ? 1 : -1;
1234 return byTimestamp || compareTies(left.project, right.project);
1235 })
1236 .map(({ project }) => project);
1237}
1238
1239export function sortProjectsForSidebar<
1240 TProject extends SidebarProject,
1241 TThread extends Pick<Thread, "projectId" | "createdAt" | "updatedAt"> & ThreadSortInput,
1242>(
1243 projects: readonly TProject[],
1244 threads: readonly TThread[],
1245 sortOrder: SidebarProjectSortOrder,
1246): TProject[] {
1247 const threadsByProjectId = new Map<string, TThread[]>();
1248 for (const thread of threads) {
1249 const existing = threadsByProjectId.get(thread.projectId) ?? [];
1250 existing.push(thread);
1251 threadsByProjectId.set(thread.projectId, existing);
1252 }
1253
1254 return sortProjectsByActivity(
1255 projects,
1256 sortOrder,
1257 (project) => threadsByProjectId.get(project.id) ?? [],
1258 (left, right) => left.title.localeCompare(right.title) || left.id.localeCompare(right.id),
1259 );
1260}
1261
1262export function sortLogicalProjectsForSidebar<
1263 TProject extends LogicalSidebarProject,
1264 TThread extends ScopedSidebarThread,
1265>(
1266 projects: readonly TProject[],
1267 threads: readonly TThread[],
1268 sortOrder: SidebarProjectSortOrder,
1269): TProject[] {
1270 const groupKeyByProjectRef = new Map(
1271 projects.flatMap((project) =>
1272 project.memberProjectRefs.map(
1273 (projectRef) =>
1274 [`${projectRef.environmentId}\0${projectRef.projectId}`, project.projectKey] as const,
1275 ),
1276 ),
1277 );
1278 const threadsByProjectKey = new Map<string, TThread[]>();
1279 for (const thread of threads) {
1280 if (thread.archivedAt !== null) continue;
1281 const projectKey = groupKeyByProjectRef.get(`${thread.environmentId}\0${thread.projectId}`);
1282 if (!projectKey) continue;
1283 const existing = threadsByProjectKey.get(projectKey);
1284 if (existing) {
1285 existing.push(thread);
1286 } else {
1287 threadsByProjectKey.set(projectKey, [thread]);
1288 }
1289 }
1290
1291 return sortProjectsByActivity(
1292 projects,
1293 sortOrder,
1294 (project) => threadsByProjectKey.get(project.projectKey) ?? [],
1295 (left, right) =>
1296 left.title.localeCompare(right.title) || left.projectKey.localeCompare(right.projectKey),
1297 );
1298}
1299
1300export function sortSidebarV2ProjectGroups<
1301 TProject extends LogicalSidebarProject,
1302 TThread extends ScopedSidebarThread & Pick<SidebarThreadSummary, "lineage">,
1303>(
1304 projects: readonly TProject[],
1305 threads: readonly TThread[],
1306 sortOrder: SidebarProjectSortOrder,
1307): TProject[] {
1308 return sortLogicalProjectsForSidebar(
1309 projects,
1310 filterSidebarV2VisibleThreads(threads, null),
1311 sortOrder,
1312 );
1313}
1314
1315export function sortScopedProjectsForSidebar<
1316 TProject extends ScopedSidebarProject,
1317 TThread extends ScopedSidebarThread,
1318>(
1319 projects: readonly TProject[],
1320 threads: readonly TThread[],
1321 sortOrder: SidebarProjectSortOrder,
1322): TProject[] {
1323 const scopedKey = (environmentId: string, projectId: string) =>
1324 `${environmentId}\u0000${projectId}`;
1325 const threadsByProject = new Map<string, TThread[]>();
1326 for (const thread of threads) {
1327 if (thread.archivedAt !== null) {
1328 continue;
1329 }
1330 const key = scopedKey(thread.environmentId, thread.projectId);
1331 const existing = threadsByProject.get(key) ?? [];
1332 existing.push(thread);
1333 threadsByProject.set(key, existing);
1334 }
1335
1336 return sortProjectsByActivity(
1337 projects,
1338 sortOrder,
1339 (project) => threadsByProject.get(scopedKey(project.environmentId, project.id)) ?? [],
1340 (left, right) =>
1341 left.title.localeCompare(right.title) ||
1342 left.environmentId.localeCompare(right.environmentId) ||
1343 left.id.localeCompare(right.id),
1344 );
1345}