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