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