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