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