Open History to see the last commit
1import { resolveThreadWorkingStartedAt } from "@t3tools/client-runtime/state/models";
2import { isShownUnderParent } from "@t3tools/client-runtime/state/threads";
3import { backgroundWorkHoldsCompletion } from "@t3tools/shared/orchestrationV2PendingBackgroundWork";
4import { threadPullRequestSearchTerms } from "@t3tools/shared/threadPullRequests";
5import * as React from "react";
6import {
7 isAtomCommandInterrupted,
8 type AtomCommandResult,
9} from "@t3tools/client-runtime/state/runtime";
10import { defaultAnimateLayoutChanges, type AnimateLayoutChanges } from "@dnd-kit/sortable";
11import {
12 threadSearchMatchKey,
13 threadSearchSubject,
14 type ThreadSearchShell,
15} from "@t3tools/client-runtime/state/thread-search";
16import { foldSearchQuery, rankSearchItems, scoreThreadSearch } from "@t3tools/shared/paletteSearch";
17import type { ContextMenuItem, EnvironmentId, ThreadId } from "@t3tools/contracts";
18import type { SidebarProjectSortOrder, SidebarThreadSortOrder } from "@t3tools/contracts/settings";
19import type { AsyncResult } from "effect/reactivity";
20import {
21 effectiveSnoozed,
22 type ThreadSnoozeShell,
23} from "@t3tools/client-runtime/state/thread-settled";
24import {
25 getThreadSortTimestamp,
26 planPinnedReorder,
27 sortThreads,
28 toSortableTimestamp,
29 type ThreadSortInput,
30} from "@t3tools/client-runtime/state/thread-sort";
31import type { SidebarThreadSummary, Thread } from "../types";
32import { normalizeSearchText } from "../lib/utils";
33import { isLatestRunSettled } from "../session-logic";
34import { observeIntersection } from "../lib/observeIntersection";
35import { deadlineAfter, deadlineStore } from "@t3tools/client-runtime/clock";
36import { useDeadlinePassed } from "../hooks/useDeadline";
37import { legacyProjectCwdPreferenceKey } from "../uiStateStore";
38
39export function shouldNavigateAfterThreadPark(input: {
40 readonly threadKey: string;
41 readonly currentThreadKey: string | null;
42 readonly action: "settle" | "snooze";
43 readonly now: string;
44 readonly thread: (ThreadSnoozeShell & Pick<SidebarThreadSummary, "settledOverride">) | null;
45}): boolean {
46 return (
47 input.threadKey === input.currentThreadKey &&
48 input.thread !== null &&
49 (input.action === "settle"
50 ? input.thread.settledOverride === "settled"
51 : effectiveSnoozed(input.thread, { now: input.now }))
52 );
53}
54
55const THREAD_JUMP_HINT_SHOW_DELAY_MS = 200;
56
57export function resolveSidebarRowAccessibility(input: {
58 readonly title: string;
59 readonly statusLabel: string | null;
60 readonly projectDisplayName: string | null;
61 readonly isActive: boolean;
62}): { readonly label: string; readonly current: "page" | undefined } {
63 return {
64 label: [input.title, input.statusLabel, input.projectDisplayName].filter(Boolean).join(", "),
65 current: input.isActive ? "page" : undefined,
66 };
67}
68
69// Each prewarm retains growing thread detail and a live subscription, multiplying heap and server load.
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
216type 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
252type 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
483type 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 isSidebarSubagentThread(thread: Pick<SidebarThreadSummary, "lineage">): boolean {
545 return thread.lineage.relationshipToParent === "subagent";
546}
547
548// Subagent threads have no sidebar row, so an open subagent is represented by
549// its nearest non-subagent ancestor. A broken chain (missing parent, cycle,
550// other environment) resolves to the thread itself, which then matches no row.
551export function resolveSidebarRowThreadId(
552 threadId: ThreadId,
553 environmentId: EnvironmentId,
554 threads: readonly Pick<SidebarThreadSummary, "id" | "environmentId" | "lineage">[],
555): ThreadId {
556 const findThread = (id: ThreadId) =>
557 threads.find((thread) => thread.id === id && thread.environmentId === environmentId);
558 const visited = new Set<ThreadId>();
559 let thread = findThread(threadId);
560 while (thread !== undefined && isSidebarSubagentThread(thread)) {
561 if (thread.lineage.parentThreadId === null || visited.has(thread.id)) return threadId;
562 visited.add(thread.id);
563 thread = findThread(thread.lineage.parentThreadId);
564 }
565 return thread?.id ?? threadId;
566}
567
568/**
569 * `delegatedUnderParent` holds the tasks linked environments run for a thread
570 * the sidebar lists, by thread key; they show under that thread, as subagents do.
571 */
572export function filterSidebarV2VisibleThreads<
573 T extends Pick<SidebarThreadSummary, "archivedAt" | "environmentId" | "id" | "lineage"> & {
574 projectId: string;
575 },
576>(
577 threads: readonly T[],
578 scopedProjectKeys: ReadonlySet<string> | null,
579 delegatedUnderParent: ReadonlySet<string>,
580): T[] {
581 return threads.filter(
582 (thread) =>
583 thread.archivedAt === null &&
584 !isShownUnderParent(
585 { environmentId: thread.environmentId, threadId: thread.id },
586 thread.lineage,
587 delegatedUnderParent,
588 ) &&
589 (scopedProjectKeys === null ||
590 scopedProjectKeys.has(`${thread.environmentId}:${thread.projectId}`)),
591 );
592}
593
594export function buildBulkTitleRegenerationContextMenuItem(input: {
595 supportedCount: number;
596 actionableCount: number;
597}): ContextMenuItem<"regenerate-title"> | null {
598 if (input.supportedCount === 0) return null;
599 if (input.actionableCount === 0) {
600 return {
601 id: "regenerate-title",
602 label: `Regenerating… (${input.supportedCount})`,
603 disabled: true,
604 };
605 }
606 return {
607 id: "regenerate-title",
608 label: `Regenerate titles (${input.actionableCount})`,
609 };
610}
611
612export function buildBulkUnpinContextMenuItem(input: {
613 pinnedCount: number;
614}): ContextMenuItem<"unpin"> | null {
615 if (input.pinnedCount === 0) return null;
616 return { id: "unpin", label: `Unpin (${input.pinnedCount})` };
617}
618
619export interface ThreadStatusPill {
620 label:
621 | "Working"
622 | "Connecting"
623 | "Completed"
624 | "Failed"
625 | "Pending Approval"
626 | "Awaiting Input"
627 | "Guest Request"
628 | "Waiting"
629 | "Plan Ready";
630 colorClass: string;
631 dotClass: string;
632 pulse: boolean;
633}
634
635const THREAD_STATUS_PRIORITY: Record<ThreadStatusPill["label"], number> = {
636 "Pending Approval": 5,
637 "Awaiting Input": 4,
638 "Guest Request": 3.75,
639 Failed: 3.5,
640 Working: 3,
641 Connecting: 3,
642 Waiting: 2.5,
643 "Plan Ready": 2,
644 Completed: 1,
645};
646
647type ThreadStatusInput = Pick<
648 SidebarThreadSummary,
649 | "hasActionableProposedPlan"
650 | "hasPendingApprovals"
651 | "hasPendingUserInput"
652 | "pendingSubagentRequest"
653 | "pendingGuestMessageCount"
654 | "interactionMode"
655 | "latestRun"
656 | "runtime"
657> & {
658 lastVisitedAt?: string | null | undefined;
659 pendingBackgroundTasks?: SidebarThreadSummary["pendingBackgroundTasks"] | undefined;
660 blockedOnThreadWait?: boolean | undefined;
661};
662
663/**
664 * Thread jump hints appear once the jump modifier has been held for a moment,
665 * so a quick shortcut never flashes them, and hide as soon as it is released.
666 */
667export function useThreadJumpHintsVisible(shouldShow: boolean): boolean {
668 const [showAt, setShowAt] = React.useState<number | null>(null);
669 // The clock is read inside the updater: the compiler caches a bare clock read
670 // in render once per instance, so a second hold would reuse the first deadline.
671 // React discards this render and re-runs with the update.
672 if (shouldShow !== (showAt !== null)) {
673 setShowAt(shouldShow ? () => deadlineAfter(THREAD_JUMP_HINT_SHOW_DELAY_MS) : null);
674 }
675 return useDeadlinePassed(showAt);
676}
677
678export function resolveThreadLastVisitedAt(
679 serverLastVisitedAt: string | null | undefined,
680 localLastVisitedAt: string | undefined,
681): string | undefined {
682 // Server visits override local watermarks, including mark-unread rewinds; use local values only on older
683 // servers.
684 if (serverLastVisitedAt === undefined) return localLastVisitedAt;
685 return serverLastVisitedAt ?? undefined;
686}
687
688export function hasUnseenCompletion(thread: ThreadStatusInput): boolean {
689 if (!thread.latestRun?.completedAt) return false;
690 const completedAt = Date.parse(thread.latestRun.completedAt);
691 if (Number.isNaN(completedAt)) return false;
692 if (!thread.lastVisitedAt) return false;
693
694 const lastVisitedAt = Date.parse(thread.lastVisitedAt);
695 if (Number.isNaN(lastVisitedAt)) return true;
696 return completedAt > lastVisitedAt;
697}
698
699/** Unopened threads' failures still count as unseen, unlike completions. */
700function hasUnseenFailure(thread: ThreadStatusInput): boolean {
701 if (thread.latestRun?.status !== "failed") return false;
702 if (!thread.lastVisitedAt) return true;
703 const completedAt = Date.parse(thread.latestRun.completedAt ?? "");
704 const lastVisitedAt = Date.parse(thread.lastVisitedAt);
705 if (Number.isNaN(completedAt) || Number.isNaN(lastVisitedAt)) return true;
706 return completedAt > lastVisitedAt;
707}
708
709// Suppress trailing double-click navigation; keyboard and synthetic clicks use detail 0.
710export function isTrailingDoubleClick(detail: number): boolean {
711 return detail > 1;
712}
713
714function nodeClosest(node: object | null, selector: string): unknown {
715 if (node === null || !("closest" in node) || typeof node.closest !== "function") return null;
716 return node.closest(selector);
717}
718
719export function isSidebarNestedLinkClick(target: EventTarget | null): boolean {
720 if (target == null || typeof target !== "object") return false;
721 if (nodeClosest(target, "a[href]") !== null) return true;
722 const parent =
723 "parentElement" in target &&
724 target.parentElement !== null &&
725 typeof target.parentElement === "object"
726 ? target.parentElement
727 : null;
728 return nodeClosest(parent, "a[href]") !== null;
729}
730
731export function shouldCreateNewThreadInCurrentProject(
732 shiftKey: boolean,
733 projectGroupCount: number,
734): boolean {
735 return shiftKey || projectGroupCount <= 1;
736}
737
738export function orderItemsByPreferredIds<TItem, TId>(input: {
739 items: readonly TItem[];
740 preferredIds: readonly TId[];
741 getId: (item: TItem) => TId;
742 getPreferenceIds?: (item: TItem) => readonly TId[];
743}): TItem[] {
744 const { getId, getPreferenceIds, items, preferredIds } = input;
745 if (preferredIds.length === 0) {
746 return [...items];
747 }
748
749 const indexesByPreferenceId = new Map<TId, number[]>();
750 for (const [index, item] of items.entries()) {
751 const preferenceIds = getPreferenceIds?.(item) ?? [getId(item)];
752 for (const preferenceId of new Set(preferenceIds)) {
753 const indexes = indexesByPreferenceId.get(preferenceId);
754 if (indexes) {
755 indexes.push(index);
756 } else {
757 indexesByPreferenceId.set(preferenceId, [index]);
758 }
759 }
760 }
761
762 const emittedIndexes = new Set<number>();
763 const ordered = preferredIds.flatMap((id) => {
764 const index = indexesByPreferenceId
765 .get(id)
766 ?.find((candidate) => !emittedIndexes.has(candidate));
767 if (index === undefined) {
768 return [];
769 }
770 emittedIndexes.add(index);
771 return [items[index]!];
772 });
773 const remaining = items.filter((_, index) => !emittedIndexes.has(index));
774 return [...ordered, ...remaining];
775}
776
777export function resolveAdjacentThreadId<T>(input: {
778 threadIds: readonly T[];
779 currentThreadId: T | null;
780 direction: ThreadTraversalDirection;
781}): T | null {
782 const { currentThreadId, direction, threadIds } = input;
783
784 if (threadIds.length === 0) {
785 return null;
786 }
787
788 if (currentThreadId === null) {
789 return direction === "previous" ? (threadIds.at(-1) ?? null) : (threadIds[0] ?? null);
790 }
791
792 const currentIndex = threadIds.indexOf(currentThreadId);
793 if (currentIndex === -1) {
794 return null;
795 }
796
797 if (direction === "previous") {
798 return currentIndex > 0 ? (threadIds[currentIndex - 1] ?? null) : null;
799 }
800
801 return currentIndex < threadIds.length - 1 ? (threadIds[currentIndex + 1] ?? null) : null;
802}
803
804export type SidebarThreadStatus =
805 | "approval"
806 | "input"
807 | "request"
808 | "working"
809 | "waiting"
810 | "failed"
811 | "limited"
812 | "ready";
813
814export function shouldRecedeSidebarThread(input: {
815 status: SidebarThreadStatus;
816 isUnread: boolean;
817 isWoke: boolean;
818 isActive: boolean;
819 isSelected: boolean;
820}): boolean {
821 if (
822 input.isActive ||
823 input.isSelected ||
824 input.status === "input" ||
825 input.status === "request"
826 ) {
827 return false;
828 }
829 if (input.status === "working" || input.status === "waiting") return true;
830 if (input.status === "ready" || input.status === "approval") {
831 return !input.isUnread && !input.isWoke;
832 }
833 return false;
834}
835
836type SidebarThreadStatusInput = Pick<
837 SidebarThreadSummary,
838 | "hasPendingApprovals"
839 | "hasPendingUserInput"
840 | "pendingSubagentRequest"
841 | "pendingGuestMessageCount"
842 | "runtime"
843 | "blockedOnThreadWait"
844>;
845
846export function resolveSidebarThreadStatus(thread: SidebarThreadStatusInput): SidebarThreadStatus {
847 if (thread.hasPendingApprovals || thread.pendingSubagentRequest === "approval") {
848 return "approval";
849 }
850 if (thread.hasPendingUserInput || thread.pendingSubagentRequest === "user_input") {
851 return "input";
852 }
853 // A guest is waiting on the owner; the agent's own requests come first.
854 if ((thread.pendingGuestMessageCount ?? 0) > 0) {
855 return "request";
856 }
857 if (thread.runtime?.status === "running" && thread.blockedOnThreadWait === true) {
858 return "waiting";
859 }
860 if (
861 thread.runtime !== null &&
862 ["preparing", "queued", "starting", "running", "waiting"].includes(thread.runtime.status)
863 ) {
864 return "working";
865 }
866 if (thread.runtime?.status === "idle") {
867 return "waiting";
868 }
869 if (thread.runtime?.status === "failed") {
870 return thread.runtime.lastErrorClass === "usage_limit" ? "limited" : "failed";
871 }
872 return "ready";
873}
874
875/**
876 * The dot on a closed boring-sidebar folder: the most urgent state among its
877 * hidden threads. Waiting threads stay quiet, like their rows.
878 */
879export function resolveSidebarFolderDot(
880 threads: ReadonlyArray<ThreadStatusInput & SidebarThreadStatusInput>,
881): "attention" | "failed" | "unread" | "working" | null {
882 const statuses = new Set(threads.map(resolveSidebarThreadStatus));
883 if (
884 statuses.has("input") ||
885 statuses.has("approval") ||
886 statuses.has("request") ||
887 statuses.has("limited")
888 ) {
889 return "attention";
890 }
891 if (statuses.has("failed")) return "failed";
892 // Rows show Done only for ready threads, so the dot follows the same rule.
893 const hasUnread = threads.some(
894 (thread) => resolveSidebarThreadStatus(thread) === "ready" && hasUnseenCompletion(thread),
895 );
896 if (hasUnread) return "unread";
897 if (statuses.has("working")) return "working";
898 return null;
899}
900
901/**
902 * Keys the old per-project sidebar saved folder open state under, most
903 * specific first, for `resolveProjectExpanded`. Boring folders read and write
904 * the same keys, so a legacy user's closed folders stay closed after regrouping.
905 */
906export function sidebarFolderExpansionKeys(group: {
907 readonly projectKey: string;
908 readonly memberProjects: ReadonlyArray<{
909 readonly physicalProjectKey: string;
910 readonly workspaceRoot: string;
911 }>;
912}): string[] {
913 return [
914 group.projectKey,
915 ...group.memberProjects.map((member) => member.physicalProjectKey),
916 ...group.memberProjects.map((member) => legacyProjectCwdPreferenceKey(member.workspaceRoot)),
917 ];
918}
919
920/**
921 * Boring sidebar folders. Folders follow `groups` order and threads keep their
922 * input order. A project with no threads gets a folder only with `keepEmpty`.
923 * A thread whose project is in no group has no folder and is left out.
924 */
925export function groupSidebarThreadsByProject<
926 TGroup extends {
927 readonly memberProjectRefs: ReadonlyArray<{
928 readonly environmentId: EnvironmentId;
929 readonly projectId: string;
930 }>;
931 },
932 TThread extends Pick<SidebarThreadSummary, "environmentId" | "projectId">,
933>(
934 groups: readonly TGroup[],
935 threads: readonly TThread[],
936 keepEmpty: boolean,
937): Array<{ group: TGroup; threads: TThread[] }> {
938 const folders = groups.map((group) => ({ group, threads: [] as TThread[] }));
939 const folderByProject = new Map<string, (typeof folders)[number]>();
940 for (const folder of folders) {
941 for (const ref of folder.group.memberProjectRefs) {
942 folderByProject.set(`${ref.environmentId}:${ref.projectId}`, folder);
943 }
944 }
945 for (const thread of threads) {
946 folderByProject.get(`${thread.environmentId}:${thread.projectId}`)?.threads.push(thread);
947 }
948 return keepEmpty ? folders : folders.filter((folder) => folder.threads.length > 0);
949}
950
951export type SidebarV2TopStatusKind =
952 | "approval"
953 | "done"
954 | "failed"
955 | "limited"
956 | "input"
957 | "request"
958 | "waiting"
959 | "woke"
960 | "working";
961
962export function firstValidTimestampMs(
963 ...candidates: ReadonlyArray<string | null | undefined>
964): number {
965 for (const candidate of candidates) {
966 if (candidate == null) continue;
967 const parsed = Date.parse(candidate);
968 if (!Number.isNaN(parsed)) return parsed;
969 }
970 return 0;
971}
972
973export { sortActiveThreadsByOrderKey as sortThreadsForSidebar } from "@t3tools/client-runtime/state/thread-sort";
974export {
975 sortInboxThreadsByReturn,
976 sortWorkingThreadsBySend,
977} from "@t3tools/client-runtime/state/thread-inbox";
978
979export { pinOrderKeyBetween } from "@t3tools/client-runtime/state/thread-sort";
980export { sortPinnedThreadsByOrderKey as sortPinnedThreadsForSidebar } from "@t3tools/client-runtime/state/thread-sort";
981
982const EMPTY_CONTENT_MATCH_KEYS: ReadonlySet<string> = new Set<string>();
983
984/**
985 * Sidebar search results: title, branch, and pull request matches ranked as
986 * the command palette ranks them, then threads listed only because their
987 * messages match, in `contentMatchKeys` order.
988 */
989export function searchSidebarThreads<
990 T extends ThreadSearchShell & {
991 readonly environmentId: EnvironmentId;
992 readonly id: ThreadId;
993 },
994>(
995 threads: readonly T[],
996 query: string,
997 contentMatchKeys: ReadonlySet<string> = EMPTY_CONTENT_MATCH_KEYS,
998 now = Date.now(),
999): { readonly titleMatches: T[]; readonly contentMatches: T[] } {
1000 const normalizedQuery = foldSearchQuery(query);
1001 if (normalizedQuery.length === 0) return { titleMatches: [], contentMatches: [] };
1002 const titleMatches = rankSearchItems(threads, (thread, options) =>
1003 scoreThreadSearch(normalizedQuery, threadSearchSubject(thread, null), now, {
1004 ...options,
1005 picks: false,
1006 }),
1007 ).map(({ item }) => item);
1008 const listed = new Set(titleMatches);
1009 // In the order the server ranked their messages, as the palette lists them.
1010 const threadByKey = new Map(
1011 threads.map((thread) => [
1012 threadSearchMatchKey({ environmentId: thread.environmentId, threadId: thread.id }),
1013 thread,
1014 ]),
1015 );
1016 const contentMatches = [...contentMatchKeys].flatMap((key) => {
1017 const thread = threadByKey.get(key);
1018 return thread && !listed.has(thread) ? [thread] : [];
1019 });
1020 return { titleMatches, contentMatches };
1021}
1022
1023export function pullRequestMatchesSearchQuery(
1024 pullRequest: Parameters<typeof threadPullRequestSearchTerms>[0],
1025 query: string,
1026): boolean {
1027 const normalizedQuery = normalizeSearchText(query);
1028 if (normalizedQuery.length === 0) return false;
1029 const haystack = normalizeSearchText(threadPullRequestSearchTerms(pullRequest).join(" "));
1030 return normalizedQuery.split(" ").every((token) => haystack.includes(token));
1031}
1032
1033export function filterSidebarProjectScopeItems<TItem extends { readonly value: string }>(input: {
1034 items: readonly TItem[];
1035 query: string;
1036 matches: (item: TItem, query: string) => boolean;
1037}): readonly TItem[] {
1038 const query = input.query.trim();
1039 if (query.length === 0) return input.items;
1040 return input.items.filter((item) => item.value !== "all" && input.matches(item, query));
1041}
1042
1043interface SidebarProjectScopeMenuState {
1044 readonly open: boolean;
1045 readonly query: string;
1046}
1047
1048type SidebarProjectScopeMenuAction =
1049 | { readonly type: "query-changed"; readonly query: string }
1050 | { readonly type: "open-changed"; readonly open: boolean }
1051 | { readonly type: "project-settings-opened" };
1052
1053export function reduceSidebarProjectScopeMenuState(
1054 state: SidebarProjectScopeMenuState,
1055 action: SidebarProjectScopeMenuAction,
1056): SidebarProjectScopeMenuState {
1057 switch (action.type) {
1058 case "query-changed":
1059 return { ...state, query: action.query };
1060 case "open-changed":
1061 return { open: action.open, query: "" };
1062 case "project-settings-opened":
1063 return { open: false, query: "" };
1064 }
1065}
1066
1067export function resolveWorkingStartedAt(
1068 thread: Pick<SidebarThreadSummary, "latestRun" | "runtime">,
1069): string | null {
1070 return resolveThreadWorkingStartedAt(thread);
1071}
1072
1073export function resolveThreadStatusPill(input: {
1074 thread: ThreadStatusInput;
1075}): ThreadStatusPill | null {
1076 const { thread } = input;
1077
1078 if (thread.hasPendingApprovals || thread.pendingSubagentRequest === "approval") {
1079 return {
1080 label: "Pending Approval",
1081 colorClass: "text-amber-600 dark:text-amber-300/90",
1082 dotClass: "bg-amber-500 dark:bg-amber-300/90",
1083 pulse: false,
1084 };
1085 }
1086
1087 if (thread.hasPendingUserInput || thread.pendingSubagentRequest === "user_input") {
1088 return {
1089 label: "Awaiting Input",
1090 colorClass: "text-indigo-600 dark:text-indigo-300/90",
1091 dotClass: "bg-indigo-500 dark:bg-indigo-300/90",
1092 pulse: false,
1093 };
1094 }
1095
1096 if ((thread.pendingGuestMessageCount ?? 0) > 0) {
1097 return {
1098 label: "Guest Request",
1099 colorClass: "text-guest-foreground",
1100 dotClass: "bg-guest",
1101 pulse: false,
1102 };
1103 }
1104
1105 if (
1106 (thread.runtime?.status === "running" && thread.blockedOnThreadWait !== true) ||
1107 thread.runtime?.status === "waiting"
1108 ) {
1109 return {
1110 label: "Working",
1111 colorClass: "text-sky-600 dark:text-sky-300/80",
1112 dotClass: "bg-sky-500 dark:bg-sky-300/80",
1113 pulse: true,
1114 };
1115 }
1116
1117 if (
1118 thread.runtime?.status === "preparing" ||
1119 thread.runtime?.status === "starting" ||
1120 thread.runtime?.status === "queued"
1121 ) {
1122 return {
1123 label: "Connecting",
1124 colorClass: "text-sky-600 dark:text-sky-300/80",
1125 dotClass: "bg-sky-500 dark:bg-sky-300/80",
1126 pulse: true,
1127 };
1128 }
1129
1130 if (
1131 (thread.runtime?.status === "running" && thread.blockedOnThreadWait === true) ||
1132 backgroundWorkHoldsCompletion(thread.pendingBackgroundTasks ?? [])
1133 ) {
1134 return {
1135 label: "Waiting",
1136 colorClass: "text-sidebar-muted-foreground",
1137 dotClass: "bg-sidebar-muted-foreground",
1138 pulse: false,
1139 };
1140 }
1141
1142 if (hasUnseenFailure(thread)) {
1143 return {
1144 label: "Failed",
1145 colorClass: "text-red-600 dark:text-red-300/90",
1146 dotClass: "bg-red-500 dark:bg-red-300/90",
1147 pulse: false,
1148 };
1149 }
1150
1151 const hasPlanReadyPrompt =
1152 !thread.hasPendingUserInput &&
1153 thread.interactionMode === "plan" &&
1154 isLatestRunSettled(thread.latestRun, thread.runtime) &&
1155 thread.hasActionableProposedPlan;
1156 if (hasPlanReadyPrompt) {
1157 return {
1158 label: "Plan Ready",
1159 colorClass: "text-violet-600 dark:text-violet-300/90",
1160 dotClass: "bg-violet-500 dark:bg-violet-300/90",
1161 pulse: false,
1162 };
1163 }
1164
1165 if (hasUnseenCompletion(thread)) {
1166 return {
1167 label: "Completed",
1168 colorClass: "text-emerald-600 dark:text-emerald-300/90",
1169 dotClass: "bg-emerald-500 dark:bg-emerald-300/90",
1170 pulse: false,
1171 };
1172 }
1173
1174 return null;
1175}
1176
1177export function resolveProjectStatusIndicator(
1178 statuses: ReadonlyArray<ThreadStatusPill | null>,
1179): ThreadStatusPill | null {
1180 let highestPriorityStatus: ThreadStatusPill | null = null;
1181
1182 for (const status of statuses) {
1183 if (status === null) continue;
1184 if (
1185 highestPriorityStatus === null ||
1186 THREAD_STATUS_PRIORITY[status.label] > THREAD_STATUS_PRIORITY[highestPriorityStatus.label]
1187 ) {
1188 highestPriorityStatus = status;
1189 }
1190 }
1191
1192 return highestPriorityStatus;
1193}
1194
1195export function getFallbackThreadIdAfterDelete<
1196 T extends Pick<Thread, "id" | "projectId" | "createdAt" | "updatedAt"> & ThreadSortInput,
1197>(input: {
1198 threads: readonly T[];
1199 deletedThreadId: T["id"];
1200 sortOrder: SidebarThreadSortOrder;
1201 deletedThreadIds?: ReadonlySet<T["id"]>;
1202}): T["id"] | null {
1203 const { deletedThreadId, deletedThreadIds, sortOrder, threads } = input;
1204 const deletedThread = threads.find((thread) => thread.id === deletedThreadId);
1205 if (!deletedThread) {
1206 return null;
1207 }
1208
1209 return (
1210 sortThreads(
1211 threads.filter(
1212 (thread) =>
1213 thread.projectId === deletedThread.projectId &&
1214 thread.id !== deletedThreadId &&
1215 !deletedThreadIds?.has(thread.id),
1216 ),
1217 sortOrder,
1218 )[0]?.id ?? null
1219 );
1220}
1221function getProjectSortTimestamp(
1222 project: SidebarProject,
1223 projectThreads: readonly ThreadSortInput[],
1224 sortOrder: Exclude<SidebarProjectSortOrder, "manual">,
1225): number {
1226 if (projectThreads.length > 0) {
1227 return projectThreads.reduce(
1228 (latest, thread) => Math.max(latest, getThreadSortTimestamp(thread, sortOrder)),
1229 Number.NEGATIVE_INFINITY,
1230 );
1231 }
1232
1233 if (sortOrder === "created_at") {
1234 return toSortableTimestamp(project.createdAt) ?? Number.NEGATIVE_INFINITY;
1235 }
1236 return toSortableTimestamp(project.updatedAt ?? project.createdAt) ?? Number.NEGATIVE_INFINITY;
1237}
1238
1239function sortProjectsByActivity<TProject extends SidebarProject>(
1240 projects: readonly TProject[],
1241 sortOrder: SidebarProjectSortOrder,
1242 getProjectThreads: (project: TProject) => readonly ThreadSortInput[],
1243 compareTies: (left: TProject, right: TProject) => number,
1244): TProject[] {
1245 if (sortOrder === "manual") {
1246 return [...projects];
1247 }
1248
1249 // Project timestamps scan all threads; compute once per project instead of per comparison.
1250 return projects
1251 .map((project) => ({
1252 project,
1253 timestamp: getProjectSortTimestamp(project, getProjectThreads(project), sortOrder),
1254 }))
1255 .sort((left, right) => {
1256 const byTimestamp =
1257 right.timestamp === left.timestamp ? 0 : right.timestamp > left.timestamp ? 1 : -1;
1258 return byTimestamp || compareTies(left.project, right.project);
1259 })
1260 .map(({ project }) => project);
1261}
1262
1263export function sortProjectsForSidebar<
1264 TProject extends SidebarProject,
1265 TThread extends Pick<Thread, "projectId" | "createdAt" | "updatedAt"> & ThreadSortInput,
1266>(
1267 projects: readonly TProject[],
1268 threads: readonly TThread[],
1269 sortOrder: SidebarProjectSortOrder,
1270): TProject[] {
1271 const threadsByProjectId = new Map<string, TThread[]>();
1272 for (const thread of threads) {
1273 const existing = threadsByProjectId.get(thread.projectId) ?? [];
1274 existing.push(thread);
1275 threadsByProjectId.set(thread.projectId, existing);
1276 }
1277
1278 return sortProjectsByActivity(
1279 projects,
1280 sortOrder,
1281 (project) => threadsByProjectId.get(project.id) ?? [],
1282 (left, right) => left.title.localeCompare(right.title) || left.id.localeCompare(right.id),
1283 );
1284}
1285
1286export function sortLogicalProjectsForSidebar<
1287 TProject extends LogicalSidebarProject,
1288 TThread extends ScopedSidebarThread,
1289>(
1290 projects: readonly TProject[],
1291 threads: readonly TThread[],
1292 sortOrder: SidebarProjectSortOrder,
1293): TProject[] {
1294 const groupKeyByProjectRef = new Map(
1295 projects.flatMap((project) =>
1296 project.memberProjectRefs.map(
1297 (projectRef) =>
1298 [`${projectRef.environmentId}\0${projectRef.projectId}`, project.projectKey] as const,
1299 ),
1300 ),
1301 );
1302 const threadsByProjectKey = new Map<string, TThread[]>();
1303 for (const thread of threads) {
1304 if (thread.archivedAt !== null) continue;
1305 const projectKey = groupKeyByProjectRef.get(`${thread.environmentId}\0${thread.projectId}`);
1306 if (!projectKey) continue;
1307 const existing = threadsByProjectKey.get(projectKey);
1308 if (existing) {
1309 existing.push(thread);
1310 } else {
1311 threadsByProjectKey.set(projectKey, [thread]);
1312 }
1313 }
1314
1315 return sortProjectsByActivity(
1316 projects,
1317 sortOrder,
1318 (project) => threadsByProjectKey.get(project.projectKey) ?? [],
1319 (left, right) =>
1320 left.title.localeCompare(right.title) || left.projectKey.localeCompare(right.projectKey),
1321 );
1322}
1323
1324export function sortSidebarV2ProjectGroups<
1325 TProject extends LogicalSidebarProject,
1326 TThread extends ScopedSidebarThread &
1327 Pick<SidebarThreadSummary, "environmentId" | "id" | "lineage">,
1328>(
1329 projects: readonly TProject[],
1330 threads: readonly TThread[],
1331 sortOrder: SidebarProjectSortOrder,
1332 delegatedUnderParent: ReadonlySet<string>,
1333): TProject[] {
1334 return sortLogicalProjectsForSidebar(
1335 projects,
1336 filterSidebarV2VisibleThreads(threads, null, delegatedUnderParent),
1337 sortOrder,
1338 );
1339}
1340
1341export function sortScopedProjectsForSidebar<
1342 TProject extends ScopedSidebarProject,
1343 TThread extends ScopedSidebarThread,
1344>(
1345 projects: readonly TProject[],
1346 threads: readonly TThread[],
1347 sortOrder: SidebarProjectSortOrder,
1348): TProject[] {
1349 const scopedKey = (environmentId: string, projectId: string) =>
1350 `${environmentId}\u0000${projectId}`;
1351 const threadsByProject = new Map<string, TThread[]>();
1352 for (const thread of threads) {
1353 if (thread.archivedAt !== null) {
1354 continue;
1355 }
1356 const key = scopedKey(thread.environmentId, thread.projectId);
1357 const existing = threadsByProject.get(key) ?? [];
1358 existing.push(thread);
1359 threadsByProject.set(key, existing);
1360 }
1361
1362 return sortProjectsByActivity(
1363 projects,
1364 sortOrder,
1365 (project) => threadsByProject.get(scopedKey(project.environmentId, project.id)) ?? [],
1366 (left, right) =>
1367 left.title.localeCompare(right.title) ||
1368 left.environmentId.localeCompare(right.environmentId) ||
1369 left.id.localeCompare(right.id),
1370 );
1371}