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