Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

Sidebar.logic.ts

1,400 lines44.5 KB

1import { resolveThreadWorkingStartedAt } from "@t3tools/client-runtime/state/models";
2import { backgroundWorkHoldsCompletion } from "@t3tools/shared/orchestrationV2PendingBackgroundWork";
3import { threadPullRequestSearchTerms } from "@t3tools/shared/threadPullRequests";
4import * as React from "react";
5import {
6 isAtomCommandInterrupted,
7 type AtomCommandResult,
8} from "@t3tools/client-runtime/state/runtime";
9import { defaultAnimateLayoutChanges, type AnimateLayoutChanges } from "@dnd-kit/sortable";
10import { threadSearchMatchKey } from "@t3tools/client-runtime/state/thread-search";
11import type { ContextMenuItem, EnvironmentId, ThreadId } from "@t3tools/contracts";
12import type { SidebarProjectSortOrder, SidebarThreadSortOrder } from "@t3tools/contracts/settings";
13import type { AsyncResult } from "effect/reactivity";
14import { planPinnedReorder } from "@t3tools/client-runtime/state/thread-sort";
15import {
16 effectiveSnoozed,
17 type ThreadSnoozeShell,
18} from "@t3tools/client-runtime/state/thread-settled";
19import {
20 getThreadSortTimestamp,
21 sortThreads,
22 toSortableTimestamp,
23 type ThreadSortInput,
24} from "../lib/threadSort";
25import type { SidebarThreadSummary, Thread } from "../types";
26import { cn, normalizeSearchText } from "../lib/utils";
27import { isLatestRunSettled } from "../session-logic";
28import { resolveServerBackedAppStageLabel } from "../branding.logic";
29​
30export function shouldNavigateAfterThreadPark(input: {
31 readonly threadKey: string;
32 readonly currentThreadKey: string | null;
33 readonly action: "settle" | "snooze";
34 readonly now: string;
35 readonly thread: (ThreadSnoozeShell & Pick<SidebarThreadSummary, "settledOverride">) | null;
36}): boolean {
37 return (
38 input.threadKey === input.currentThreadKey &&
39 input.thread !== null &&
40 (input.action === "settle"
41 ? input.thread.settledOverride === "settled"
42 : effectiveSnoozed(input.thread, { now: input.now }))
43 );
45​
46const THREAD_SELECTION_SAFE_SELECTOR = "[data-thread-item], [data-thread-selection-safe]";
47export const THREAD_JUMP_HINT_SHOW_DELAY_MS = 200;
48​
49export function resolveSidebarRowAccessibility(input: {
50 readonly title: string;
51 readonly statusLabel: string | null;
52 readonly projectDisplayName: string | null;
53 readonly isActive: boolean;
54}): { readonly label: string; readonly current: "page" | undefined } {
55 return {
56 label: [input.title, input.statusLabel, input.projectDisplayName].filter(Boolean).join(", "),
57 current: input.isActive ? "page" : undefined,
58 };
60​
61// Each prewarmed thread holds a live, fully hydrated detail subscription (all
62// messages and activities, growing as agents work) for as long as the row stays
63// visible, so this limit is a direct renderer-heap and server-load multiplier —
64// keep it small; cold opens still render instantly from the cached snapshot.
65const SIDEBAR_THREAD_PREWARM_LIMIT = 3;
66const SIDEBAR_ROW_SUBSCRIPTION_OVERSCAN_PX = 160;
67​
68export function useSidebarRowSubscriptionLease(isActive: boolean): {
69 readonly leaseLiveStatus: boolean;
70 readonly rowRef: React.Dispatch<React.SetStateAction<HTMLElement | null>>;
71} {
72 const [row, setRow] = React.useState<HTMLElement | null>(null);
73 const [isNearViewport, setIsNearViewport] = React.useState(isActive);
74 // The active row stays leased after it deactivates until the observer reports.
75 if (isActive && !isNearViewport) setIsNearViewport(true);
76 const canObserve = typeof IntersectionObserver !== "undefined";
77​
78 React.useEffect(() => {
79 if (isActive || row === null || !canObserve) return;
80​
81 const scrollRoot = row.closest<HTMLElement>('[data-slot="scroll-area-viewport"]');
82 const observer = new IntersectionObserver(
83 ([entry]) => setIsNearViewport(entry?.isIntersecting === true),
84 {
85 root: scrollRoot,
86 rootMargin: `${SIDEBAR_ROW_SUBSCRIPTION_OVERSCAN_PX}px 0px`,
87 },
88 );
89 observer.observe(row);
90 return () => observer.disconnect();
91 }, [canObserve, isActive, row]);
92​
93 return {
94 leaseLiveStatus: isActive || isNearViewport || !canObserve,
95 rowRef: setRow,
96 };
98​
99export function useRetainedValue<T>(key: string | null, value: T | null): T | null {
100 const [retained, setRetained] = React.useState<{
101 readonly key: string;
102 readonly value: T;
103 } | null>(null);
104 if (key !== null && value !== null && (retained?.key !== key || retained.value !== value)) {
105 setRetained({ key, value });
106 }
107 if (value !== null) return value;
108 return key !== null && retained?.key === key ? retained.value : null;
110​
111// Sidebar.motion handles ordinary section changes. Sortable transforms own
112// dragging; replaying their committed DOM order would animate the drop twice.
113export const animateSidebarLayoutChanges: AnimateLayoutChanges = (args) =>
114 args.isSorting ? defaultAnimateLayoutChanges(args) : false;
115​
116// Snoozed rows can leave the shelf, but dropping into it is not supported
117// because snoozing requires a wake time. The Working shelf (beta) follows live
118// status, so its rows only drag out as chat context, never between sidebar
119// sections.
120​
121export type SidebarSection = "pinned" | "active" | "working" | "snoozed" | "settled";
122​
123export function resolveSidebarThreadSection(input: {
124 readonly snoozed: boolean;
125 readonly settled: boolean;
126 readonly pinned: boolean;
127}): SidebarSection {
128 if (input.snoozed) return "snoozed";
129 if (input.settled) return "settled";
130 if (input.pinned) return "pinned";
131 return "active";
133​
134const SIDEBAR_MARKER_PREFIX = "sidebar-marker-";
135​
136export type SidebarListMarker =
137 | "pinned-header"
138 | "active-placeholder"
139 | "settled-placeholder"
140 | "pinned-divider"
141 | "working-header"
142 | "snoozed-header"
143 | "settled-header";
144​
145export function sidebarMarkerId(marker: SidebarListMarker): string {
146 return `${SIDEBAR_MARKER_PREFIX}${marker}`;
148​
149export type SidebarListItem =
150 | { readonly kind: "thread"; readonly key: string; readonly section: SidebarSection }
151 | { readonly kind: "marker"; readonly marker: SidebarListMarker };
152​
153export function sidebarListItemId(item: SidebarListItem): string {
154 return item.kind === "thread" ? item.key : sidebarMarkerId(item.marker);
156​
157function sectionAtSidebarSlot(items: readonly SidebarListItem[], index: number): SidebarSection {
158 let section: SidebarSection = "pinned";
159 for (let i = 0; i < index && i < items.length; i += 1) {
160 const item = items[i]!;
161 if (item.kind !== "marker") continue;
162 if (item.marker === "pinned-divider") section = "active";
163 else if (item.marker === "working-header") section = "working";
164 else if (item.marker === "snoozed-header") section = "snoozed";
165 else if (item.marker === "settled-header") section = "settled";
166 }
167 return section;
169​
170export type SidebarDropTarget = {
171 readonly section: "pinned" | "active" | "settled";
172 readonly pinnedOrder: readonly string[];
173 readonly activeOrder: readonly string[];
174};
175​
176export function resolveSidebarDropTarget(
177 items: readonly SidebarListItem[],
178 activeKey: string,
179 overId: string,
180): SidebarDropTarget | null {
181 const activeIndex = items.findIndex((item) => sidebarListItemId(item) === activeKey);
182 const overIndex = items.findIndex((item) => sidebarListItemId(item) === overId);
183 if (activeIndex === -1 || overIndex === -1 || items[activeIndex]?.kind !== "thread") return null;
184 const moved = items.filter((_, index) => index !== activeIndex);
185 moved.splice(overIndex, 0, items[activeIndex]!);
186 const section = sectionAtSidebarSlot(moved, overIndex);
187 if (section === "working" || section === "snoozed") return null;
188 const pinnedOrder: string[] = [];
189 const activeOrder: string[] = [];
190 let currentSection: SidebarSection = "pinned";
191 for (const item of moved) {
192 if (item.kind === "marker") {
193 if (item.marker === "pinned-divider") currentSection = "active";
194 else if (
195 item.marker === "working-header" ||
196 item.marker === "snoozed-header" ||
197 item.marker === "settled-header"
198 )
199 break;
200 } else if (currentSection === "pinned") pinnedOrder.push(item.key);
201 else activeOrder.push(item.key);
202 }
203 return { section, pinnedOrder, activeOrder };
205​
206export type SidebarThreadDropPlan =
207 | { readonly kind: "none" }
208 | {
209 readonly kind: "reorder-pinned";
210 readonly order: readonly string[];
211 readonly assignments: ReadonlyArray<{ readonly id: string; readonly orderKey: string }>;
212 }
213 | {
214 readonly kind: "pin";
215 readonly order: readonly string[];
216 readonly orderKey: string | undefined;
217 readonly extraAssignments: ReadonlyArray<{ readonly id: string; readonly orderKey: string }>;
218 }
219 | {
220 readonly kind: "move-active";
221 readonly order: readonly string[] | null;
222 readonly assignments: ReadonlyArray<{ readonly id: string; readonly orderKey: string }>;
223 readonly unpin: boolean;
224 readonly unsettle: boolean;
225 readonly unsnooze: boolean;
226 }
227 | { readonly kind: "settle" };
228​
229export type SidebarDropVerb = "pin" | "unpin" | "settle" | "unsettle" | "wake";
230​
231export function resolveSidebarDropVerb(
232 from: SidebarSection,
233 to: SidebarSection | null,
234): SidebarDropVerb | null {
235 if (to === null || to === from || to === "working" || to === "snoozed") return null;
236 if (to === "pinned") return "pin";
237 if (to === "settled") return "settle";
238 if (from === "pinned") return "unpin";
239 if (from === "settled") return "unsettle";
240 return "wake";
242​
243export function resolveSidebarSweepKeys(
244 orderedKeys: readonly string[],
245 originKey: string,
246 targetKey: string,
247 canApply: (key: string) => boolean,
248): string[] {
249 const origin = orderedKeys.indexOf(originKey);
250 const target = orderedKeys.indexOf(targetKey);
251 if (origin === -1 || target === -1) return [];
252 return orderedKeys.slice(Math.min(origin, target), Math.max(origin, target) + 1).filter(canApply);
254​
255export function sidebarThreadKeyAtY(list: HTMLElement, y: number): string | null {
256 const viewport = list.closest('[data-slot="scroll-area-viewport"]')?.getBoundingClientRect();
257 const visibleY = viewport ? Math.min(Math.max(y, viewport.top), viewport.bottom - 1) : y;
258 let key: string | null = null;
259 for (const row of list.querySelectorAll<HTMLElement>("li[data-thread-item]")) {
260 if (key !== null && row.getBoundingClientRect().top > visibleY) break;
261 key = row.dataset.threadItem ?? null;
262 }
263 return key;
265​
266export function planSidebarThreadDrop(input: {
267 readonly activeKey: string;
268 readonly activeSection: SidebarSection;
269 readonly activePinned?: boolean;
270 readonly activeSettled?: boolean;
271 readonly supportsSettlement?: boolean;
272 readonly target: SidebarDropTarget;
273 readonly pinnedOrder: readonly string[];
274 readonly pinnedKeysById: ReadonlyMap<string, string | null | undefined>;
275 readonly reorderableKeys?: ReadonlySet<string>;
276 readonly activeOrder: readonly string[];
277 readonly activeKeysById: ReadonlyMap<string, string | null | undefined>;
278 readonly activeReorderableKeys?: ReadonlySet<string>;
279 readonly activeTimeOrdered?: boolean;
280}): SidebarThreadDropPlan {
281 const {
282 activeKey,
283 activeSection,
284 activePinned = activeSection === "pinned",
285 activeSettled = activeSection === "settled",
286 target,
287 pinnedOrder,
288 pinnedKeysById,
289 reorderableKeys,
290 activeOrder,
291 activeKeysById,
292 activeReorderableKeys,
293 } = input;
294 if (activeSection === "working") return { kind: "none" };
295 if (input.supportsSettlement === false && (target.section === "settled" || activeSettled)) {
296 return { kind: "none" };
297 }
298 const arrange = (
299 order: readonly string[],
300 keysById: ReadonlyMap<string, string | null | undefined>,
301 writable: ReadonlySet<string> | undefined,
302 ) => {
303 if (!writable) return planPinnedReorder({ orderedIds: order, keysById, movedId: activeKey });
304 if (!writable.has(activeKey)) return null;
305 const assignments = planPinnedReorder({
306 orderedIds: order.filter((key) => writable.has(key) || keysById.get(key) != null),
307 keysById,
308 movedId: activeKey,
309 });
310 return assignments.every(({ id }) => writable.has(id)) ? assignments : null;
311 };
312 switch (target.section) {
313 case "active": {
314 if (input.activeTimeOrdered) {
315 return activeSection === "active"
316 ? { kind: "none" }
317 : {
318 kind: "move-active",
319 order: null,
320 assignments: [],
321 unpin: activePinned,
322 unsettle: activeSettled,
323 unsnooze: activeSection === "snoozed",
324 };
325 }
326 const order = target.activeOrder;
327 if (
328 activeSection === "active" &&
329 order.length === activeOrder.length &&
330 order.every((key, index) => key === activeOrder[index])
331 ) {
332 return { kind: "none" };
333 }
334 const assignments = arrange(order, activeKeysById, activeReorderableKeys);
335 if (assignments === null) return { kind: "none" };
336 return {
337 kind: "move-active",
338 order,
339 assignments,
340 unpin: activePinned,
341 unsettle: activeSettled,
342 unsnooze: activeSection === "snoozed",
343 };
344 }
345 case "settled":
346 return activeSection === "settled" ? { kind: "none" } : { kind: "settle" };
347 case "pinned": {
348 const order = target.pinnedOrder;
349 if (
350 activeSection === "pinned" &&
351 order.length === pinnedOrder.length &&
352 order.every((key, index) => key === pinnedOrder[index])
353 ) {
354 return { kind: "none" };
355 }
356 const assignments = arrange(order, pinnedKeysById, reorderableKeys);
357 if (assignments === null) return { kind: "none" };
358 if (activeSection === "pinned") {
359 return assignments.length === 0
360 ? { kind: "none" }
361 : { kind: "reorder-pinned", order, assignments };
362 }
363 return {
364 kind: "pin",
365 order,
366 orderKey: assignments.find((assignment) => assignment.id === activeKey)?.orderKey,
367 extraAssignments: activePinned
368 ? assignments
369 : assignments.filter((assignment) => assignment.id !== activeKey),
370 };
371 }
372 }
374​
375export function applySidebarThreadDrop<
376 T extends Pick<
377 SidebarThreadSummary,
378 | "pinnedAt"
379 | "pinOrderKey"
380 | "activeOrderKey"
381 | "snoozedAt"
382 | "snoozedUntil"
383 | "settledAt"
384 | "settledOverride"
385 | "unsettledAt"
386 >,
387>(thread: T, section: "pinned" | "active" | "settled", now: string, orderKey?: string): T {
388 const wasSettled = thread.settledOverride === "settled";
389 const awake = { ...thread, snoozedAt: null, snoozedUntil: null };
390 if (section === "settled") {
391 return {
392 ...awake,
393 pinnedAt: null,
394 pinOrderKey: null,
395 activeOrderKey: null,
396 settledOverride: "settled",
397 settledAt: wasSettled ? (thread.settledAt ?? now) : now,
398 unsettledAt: null,
399 };
400 }
401 const resumed = wasSettled
402 ? { ...awake, settledOverride: "active" as const, settledAt: null, unsettledAt: now }
403 : awake;
404 return {
405 ...resumed,
406 pinnedAt: section === "pinned" ? (thread.pinnedAt ?? now) : null,
407 pinOrderKey: section === "pinned" ? (orderKey ?? thread.pinOrderKey) : null,
408 ...(section === "active" && orderKey !== undefined ? { activeOrderKey: orderKey } : {}),
409 };
411​
412type SidebarProject = {
413 id: string;
414 title: string;
415 createdAt?: string | undefined;
416 updatedAt?: string | undefined;
417};
418​
419type ScopedSidebarProject = SidebarProject & {
420 environmentId: string;
421};
422​
423type ScopedSidebarThread = ThreadSortInput & {
424 environmentId: string;
425 projectId: string;
426 archivedAt: string | null;
427};
428​
429type LogicalSidebarProject = SidebarProject & {
430 projectKey: string;
431 memberProjectRefs: readonly {
432 environmentId: string;
433 projectId: string;
434 }[];
435};
436​
437export type ThreadTraversalDirection = "previous" | "next";
438​
439/**
440 * Shared-worktree checks must exclude only successful deletions, never the
441 * whole batch.
442 */
443export async function deleteSelectedThreadEntries<
444 TEntry extends { readonly threadKey: string },
445>(input: {
446 entries: readonly TEntry[];
447 delete: (
448 entry: TEntry,
449 deletedThreadKeys: ReadonlySet<string>,
450 ) => Promise<AtomCommandResult<unknown, unknown> | null>;
451}) {
452 const deletedThreadKeys = new Set<string>();
453 let firstFailure: AsyncResult.Failure<unknown, unknown> | null = null;
454​
455 for (const entry of input.entries) {
456 const result = await input.delete(entry, deletedThreadKeys);
457 if (result === null) continue;
458 if (result._tag === "Failure") {
459 if (isAtomCommandInterrupted(result)) break;
460 firstFailure ??= result;
461 continue;
462 }
463 deletedThreadKeys.add(entry.threadKey);
464 }
465​
466 return { deletedThreadKeys, firstFailure };
468​
469export async function archiveSelectedThreadEntries<
470 TEntry extends { readonly threadKey: string },
471 TResult extends { readonly _tag: "Success" | "Failure" },
472>(input: {
473 entries: readonly TEntry[];
474 archive: (entry: TEntry, onArchived: () => void) => Promise<TResult>;
475}): Promise<{
476 archivedThreadKeys: readonly string[];
477 mutationFailure: Extract<TResult, { readonly _tag: "Failure" }> | null;
478 followupFailures: readonly Extract<TResult, { readonly _tag: "Failure" }>[];
479}> {
480 const archivedThreadKeys: string[] = [];
481 const followupFailures: Extract<TResult, { readonly _tag: "Failure" }>[] = [];
482​
483 for (const entry of input.entries) {
484 let didArchive = false;
485 const result = await input.archive(entry, () => {
486 didArchive = true;
487 });
488 if (didArchive || result._tag === "Success") archivedThreadKeys.push(entry.threadKey);
489 if (result._tag === "Success") continue;
490 const failure = result as Extract<TResult, { readonly _tag: "Failure" }>;
491 if (didArchive) {
492 followupFailures.push(failure);
493 continue;
494 }
495 return { archivedThreadKeys, mutationFailure: failure, followupFailures };
496 }
497​
498 return { archivedThreadKeys, mutationFailure: null, followupFailures };
500​
501export function buildMultiSelectThreadContextMenuItems(input: {
502 count: number;
503 hasRunningThread: boolean;
504}): readonly ContextMenuItem<"mark-unread" | "archive" | "delete">[] {
505 return [
506 { id: "mark-unread", label: `Mark unread (${input.count})` },
507 {
508 id: "archive",
509 label: `Archive (${input.count})`,
510 disabled: input.hasRunningThread,
511 },
512 { id: "delete", label: `Delete (${input.count})`, destructive: true },
513 ];
515​
516export function isSidebarSubagentThread(thread: Pick<SidebarThreadSummary, "lineage">): boolean {
517 return thread.lineage.relationshipToParent === "subagent";
519​
520// Subagent threads have no sidebar row, so an open subagent is represented by
521// its nearest non-subagent ancestor. A broken chain (missing parent, cycle,
522// other environment) resolves to the thread itself, which then matches no row.
523export function resolveSidebarRowThreadId(
524 threadId: ThreadId,
525 environmentId: EnvironmentId,
526 threads: readonly Pick<SidebarThreadSummary, "id" | "environmentId" | "lineage">[],
527): ThreadId {
528 const findThread = (id: ThreadId) =>
529 threads.find((thread) => thread.id === id && thread.environmentId === environmentId);
530 const visited = new Set<ThreadId>();
531 let thread = findThread(threadId);
532 while (thread !== undefined && isSidebarSubagentThread(thread)) {
533 if (thread.lineage.parentThreadId === null || visited.has(thread.id)) return threadId;
534 visited.add(thread.id);
535 thread = findThread(thread.lineage.parentThreadId);
536 }
537 return thread?.id ?? threadId;
539​
540export function filterSidebarV2VisibleThreads<
541 T extends Pick<SidebarThreadSummary, "archivedAt" | "lineage"> & {
542 environmentId: string;
543 projectId: string;
544 },
545>(threads: readonly T[], scopedProjectKeys: ReadonlySet<string> | null): T[] {
546 return threads.filter(
547 (thread) =>
548 thread.archivedAt === null &&
549 !isSidebarSubagentThread(thread) &&
550 (scopedProjectKeys === null ||
551 scopedProjectKeys.has(`${thread.environmentId}:${thread.projectId}`)),
552 );
554​
555export function getSidebarForkParentThreadId(
556 thread: Pick<SidebarThreadSummary, "forkedFrom" | "lineage">,
557) {
558 if (thread.lineage.relationshipToParent !== "fork") {
559 return null;
560 }
561 return thread.forkedFrom?.type === "run"
562 ? thread.forkedFrom.threadId
563 : thread.lineage.parentThreadId;
565​
566export function buildBulkTitleRegenerationContextMenuItem(input: {
567 supportedCount: number;
568 actionableCount: number;
569}): ContextMenuItem<"regenerate-title"> | null {
570 if (input.supportedCount === 0) return null;
571 if (input.actionableCount === 0) {
572 return {
573 id: "regenerate-title",
574 label: `Regenerating… (${input.supportedCount})`,
575 disabled: true,
576 };
577 }
578 return {
579 id: "regenerate-title",
580 label: `Regenerate titles (${input.actionableCount})`,
581 };
583​
584export function buildBulkUnpinContextMenuItem(input: {
585 pinnedCount: number;
586}): ContextMenuItem<"unpin"> | null {
587 if (input.pinnedCount === 0) return null;
588 return { id: "unpin", label: `Unpin (${input.pinnedCount})` };
590​
591export interface ThreadStatusPill {
592 label:
593 | "Working"
594 | "Connecting"
595 | "Completed"
596 | "Failed"
597 | "Pending Approval"
598 | "Awaiting Input"
599 | "Waiting"
600 | "Plan Ready";
601 colorClass: string;
602 dotClass: string;
603 pulse: boolean;
605​
606const THREAD_STATUS_PRIORITY: Record<ThreadStatusPill["label"], number> = {
607 "Pending Approval": 5,
608 "Awaiting Input": 4,
609 Failed: 3.5,
610 Working: 3,
611 Connecting: 3,
612 Waiting: 2.5,
613 "Plan Ready": 2,
614 Completed: 1,
615};
616​
617type ThreadStatusInput = Pick<
618 SidebarThreadSummary,
619 | "hasActionableProposedPlan"
620 | "hasPendingApprovals"
621 | "hasPendingUserInput"
622 | "pendingSubagentRequest"
623 | "interactionMode"
624 | "latestRun"
625 | "runtime"
626> & {
627 lastVisitedAt?: string | null | undefined;
628 pendingBackgroundTasks?: SidebarThreadSummary["pendingBackgroundTasks"] | undefined;
629};
630​
631export interface ThreadJumpHintVisibilityController {
632 sync: (shouldShow: boolean) => void;
633 dispose: () => void;
635​
636export function resolveSidebarStageBadgeLabel(input: {
637 primaryServerVersion: string | null | undefined;
638 fallbackStageLabel: string;
639}): string {
640 return resolveServerBackedAppStageLabel(input);
642​
643export function createThreadJumpHintVisibilityController(input: {
644 delayMs: number;
645 onVisibilityChange: (visible: boolean) => void;
646 setTimeoutFn?: typeof globalThis.setTimeout;
647 clearTimeoutFn?: typeof globalThis.clearTimeout;
648}): ThreadJumpHintVisibilityController {
649 const setTimeoutFn = input.setTimeoutFn ?? globalThis.setTimeout;
650 const clearTimeoutFn = input.clearTimeoutFn ?? globalThis.clearTimeout;
651 let isVisible = false;
652 let timeoutId: NodeJS.Timeout | null = null;
653​
654 const clearPendingShow = () => {
655 if (timeoutId === null) {
656 return;
657 }
658 clearTimeoutFn(timeoutId);
659 timeoutId = null;
660 };
661​
662 return {
663 sync: (shouldShow) => {
664 if (!shouldShow) {
665 clearPendingShow();
666 if (isVisible) {
667 isVisible = false;
668 input.onVisibilityChange(false);
669 }
670 return;
671 }
672​
673 if (isVisible || timeoutId !== null) {
674 return;
675 }
676​
677 timeoutId = setTimeoutFn(() => {
678 timeoutId = null;
679 isVisible = true;
680 input.onVisibilityChange(true);
681 }, input.delayMs);
682 },
683 dispose: () => {
684 clearPendingShow();
685 },
686 };
688​
689export function useThreadJumpHintVisibility(): {
690 showThreadJumpHints: boolean;
691 updateThreadJumpHintsVisibility: (shouldShow: boolean) => void;
692} {
693 const [showThreadJumpHints, setShowThreadJumpHints] = React.useState(false);
694 const controllerRef = React.useRef<ThreadJumpHintVisibilityController | null>(null);
695​
696 React.useEffect(() => {
697 const controller = createThreadJumpHintVisibilityController({
698 delayMs: THREAD_JUMP_HINT_SHOW_DELAY_MS,
699 onVisibilityChange: (visible) => {
700 setShowThreadJumpHints(visible);
701 },
702 setTimeoutFn: window.setTimeout.bind(window),
703 clearTimeoutFn: window.clearTimeout.bind(window),
704 });
705 controllerRef.current = controller;
706​
707 return () => {
708 controller.dispose();
709 controllerRef.current = null;
710 };
711 }, []);
712​
713 const updateThreadJumpHintsVisibility = (shouldShow: boolean) => {
714 controllerRef.current?.sync(shouldShow);
715 };
716​
717 return {
718 showThreadJumpHints,
719 updateThreadJumpHintsVisibility,
720 };
722​
723export function resolveThreadLastVisitedAt(
724 serverLastVisitedAt: string | null | undefined,
725 localLastVisitedAt: string | undefined,
726): string | undefined {
727 // When the server tracks visits it is authoritative — including explicit
728 // rewinds from mark-unread, which a newer browser-local watermark must not
729 // mask. The local value only carries servers without visited tracking.
730 if (serverLastVisitedAt === undefined) return localLastVisitedAt;
731 return serverLastVisitedAt ?? undefined;
733​
734export function hasUnseenCompletion(thread: ThreadStatusInput): boolean {
735 if (!thread.latestRun?.completedAt) return false;
736 const completedAt = Date.parse(thread.latestRun.completedAt);
737 if (Number.isNaN(completedAt)) return false;
738 if (!thread.lastVisitedAt) return false;
739​
740 const lastVisitedAt = Date.parse(thread.lastVisitedAt);
741 if (Number.isNaN(lastVisitedAt)) return true;
742 return completedAt > lastVisitedAt;
744​
745/**
746 * A failed latest run the person hasn't looked at since it ended. Unlike a
747 * completion, a thread nobody has opened yet (an automation's, say) counts:
748 * its failure still needs someone.
749 */
750function hasUnseenFailure(thread: ThreadStatusInput): boolean {
751 if (thread.latestRun?.status !== "failed") return false;
752 if (!thread.lastVisitedAt) return true;
753 const completedAt = Date.parse(thread.latestRun.completedAt ?? "");
754 const lastVisitedAt = Date.parse(thread.lastVisitedAt);
755 if (Number.isNaN(completedAt) || Number.isNaN(lastVisitedAt)) return true;
756 return completedAt > lastVisitedAt;
758​
759export function shouldClearThreadSelectionOnMouseDown(target: HTMLElement | null): boolean {
760 if (target === null) return true;
761 return !target.closest(THREAD_SELECTION_SAFE_SELECTOR);
763​
764// A double-click dispatches two `click` events before `dblclick`: the first has
765// `detail === 1`, the second `detail === 2`. The second click must not run the
766// row's single-click navigation, otherwise double-click-to-rename would also
767// navigate. `MouseEvent.detail` is 0 for synthetic/keyboard activations, which
768// still count as a normal single activation.
769export function isTrailingDoubleClick(detail: number): boolean {
770 return detail > 1;
772​
773function nodeClosest(node: object | null, selector: string): unknown {
774 if (node === null || !("closest" in node) || typeof node.closest !== "function") return null;
775 return node.closest(selector);
777​
778export function isSidebarNestedLinkClick(target: EventTarget | null): boolean {
779 if (target == null || typeof target !== "object") return false;
780 if (nodeClosest(target, "a[href]") !== null) return true;
781 const parent =
782 "parentElement" in target &&
783 target.parentElement !== null &&
784 typeof target.parentElement === "object"
785 ? target.parentElement
786 : null;
787 return nodeClosest(parent, "a[href]") !== null;
789​
790export function shouldCreateNewThreadInCurrentProject(
791 shiftKey: boolean,
792 projectGroupCount: number,
793): boolean {
794 return shiftKey || projectGroupCount <= 1;
796​
797export function orderItemsByPreferredIds<TItem, TId>(input: {
798 items: readonly TItem[];
799 preferredIds: readonly TId[];
800 getId: (item: TItem) => TId;
801 getPreferenceIds?: (item: TItem) => readonly TId[];
802}): TItem[] {
803 const { getId, getPreferenceIds, items, preferredIds } = input;
804 if (preferredIds.length === 0) {
805 return [...items];
806 }
807​
808 const indexesByPreferenceId = new Map<TId, number[]>();
809 for (const [index, item] of items.entries()) {
810 const preferenceIds = getPreferenceIds?.(item) ?? [getId(item)];
811 for (const preferenceId of new Set(preferenceIds)) {
812 const indexes = indexesByPreferenceId.get(preferenceId);
813 if (indexes) {
814 indexes.push(index);
815 } else {
816 indexesByPreferenceId.set(preferenceId, [index]);
817 }
818 }
819 }
820​
821 const emittedIndexes = new Set<number>();
822 const ordered = preferredIds.flatMap((id) => {
823 const index = indexesByPreferenceId
824 .get(id)
825 ?.find((candidate) => !emittedIndexes.has(candidate));
826 if (index === undefined) {
827 return [];
828 }
829 emittedIndexes.add(index);
830 return [items[index]!];
831 });
832 const remaining = items.filter((_, index) => !emittedIndexes.has(index));
833 return [...ordered, ...remaining];
835​
836export function getSidebarThreadIdsToPrewarm<TThreadId>(
837 visibleThreadIds: readonly TThreadId[],
838 limit = SIDEBAR_THREAD_PREWARM_LIMIT,
839): TThreadId[] {
840 return visibleThreadIds.slice(0, Math.max(0, limit));
842​
843export function resolveAdjacentThreadId<T>(input: {
844 threadIds: readonly T[];
845 currentThreadId: T | null;
846 direction: ThreadTraversalDirection;
847}): T | null {
848 const { currentThreadId, direction, threadIds } = input;
849​
850 if (threadIds.length === 0) {
851 return null;
852 }
853​
854 if (currentThreadId === null) {
855 return direction === "previous" ? (threadIds.at(-1) ?? null) : (threadIds[0] ?? null);
856 }
857​
858 const currentIndex = threadIds.indexOf(currentThreadId);
859 if (currentIndex === -1) {
860 return null;
861 }
862​
863 if (direction === "previous") {
864 return currentIndex > 0 ? (threadIds[currentIndex - 1] ?? null) : null;
865 }
866​
867 return currentIndex < threadIds.length - 1 ? (threadIds[currentIndex + 1] ?? null) : null;
869​
870export function isContextMenuPointerDown(input: {
871 button: number;
872 ctrlKey: boolean;
873 isMac: boolean;
874}): boolean {
875 if (input.button === 2) return true;
876 return input.isMac && input.button === 0 && input.ctrlKey;
878​
879export function resolveThreadRowClassName(input: {
880 isActive: boolean;
881 isSelected: boolean;
882}): string {
883 const baseClassName =
884 "h-8 w-full translate-x-0 cursor-pointer justify-start rounded-md px-2 text-left text-sm select-none focus-visible:ring-1 focus-visible:ring-inset focus-visible:ring-ring";
885​
886 if (input.isSelected && input.isActive) {
887 return cn(
888 baseClassName,
889 "bg-sidebar-row-active text-sidebar-foreground font-medium hover:bg-sidebar-row-active hover:text-sidebar-foreground",
890 );
891 }
892​
893 if (input.isSelected) {
894 return cn(
895 baseClassName,
896 "bg-sidebar-row-selected text-sidebar-foreground hover:bg-sidebar-row-active hover:text-sidebar-foreground",
897 );
898 }
899​
900 if (input.isActive) {
901 return cn(
902 baseClassName,
903 "bg-sidebar-row-active text-sidebar-foreground font-medium hover:bg-sidebar-row-active hover:text-sidebar-foreground",
904 );
905 }
906​
907 return cn(
908 baseClassName,
909 "text-sidebar-muted-foreground/80 hover:bg-sidebar-row-hover hover:text-sidebar-foreground",
910 );
912​
913export type SidebarThreadStatus =
914 | "approval"
915 | "input"
916 | "working"
917 | "waiting"
918 | "failed"
919 | "limited"
920 | "ready";
921​
922export function shouldRecedeSidebarThread(input: {
923 status: SidebarThreadStatus;
924 isUnread: boolean;
925 isWoke: boolean;
926 isActive: boolean;
927 isSelected: boolean;
928}): boolean {
929 if (input.isActive || input.isSelected || input.status === "input") return false;
930 if (input.status === "working" || input.status === "waiting") return true;
931 if (input.status === "ready" || input.status === "approval") {
932 return !input.isUnread && !input.isWoke;
933 }
934 return false;
936​
937type SidebarThreadStatusInput = Pick<
938 SidebarThreadSummary,
939 "hasPendingApprovals" | "hasPendingUserInput" | "pendingSubagentRequest" | "runtime"
940>;
941​
942export function resolveSidebarThreadStatus(thread: SidebarThreadStatusInput): SidebarThreadStatus {
943 if (thread.hasPendingApprovals || thread.pendingSubagentRequest === "approval") {
944 return "approval";
945 }
946 if (thread.hasPendingUserInput || thread.pendingSubagentRequest === "user_input") {
947 return "input";
948 }
949 if (
950 thread.runtime !== null &&
951 ["preparing", "queued", "starting", "running", "waiting"].includes(thread.runtime.status)
952 ) {
953 return "working";
954 }
955 if (thread.runtime?.status === "idle") {
956 return "waiting";
957 }
958 if (thread.runtime?.status === "failed") {
959 return thread.runtime.lastErrorClass === "usage_limit" ? "limited" : "failed";
960 }
961 return "ready";
963​
964export type SidebarV2TopStatusKind =
965 | "approval"
966 | "done"
967 | "failed"
968 | "limited"
969 | "input"
970 | "waiting"
971 | "woke"
972 | "working";
973​
974export function resolveSidebarV2TopStatus(input: {
975 readonly status: SidebarThreadStatus;
976 readonly isUnread: boolean;
977 readonly isWoke: boolean;
978}): SidebarV2TopStatusKind | null {
979 if (input.status === "working") {
980 return "working";
981 }
982 if (input.status === "waiting") {
983 return "waiting";
984 }
985 if (input.status === "approval") {
986 return "approval";
987 }
988 if (input.status === "input") {
989 return "input";
990 }
991 if (input.status === "failed" || input.status === "limited") {
992 return input.status;
993 }
994 if (input.isWoke) {
995 return "woke";
996 }
997 return input.isUnread ? "done" : null;
999​
1000export function shouldShowSidebarV2Duration(status: SidebarThreadStatus): boolean {
1001 return status === "working";
1003​
1004export function firstValidTimestampMs(
1005 ...candidates: ReadonlyArray<string | null | undefined>
1006): number {
1007 for (const candidate of candidates) {
1008 if (candidate == null) continue;
1009 const parsed = Date.parse(candidate);
1010 if (!Number.isNaN(parsed)) return parsed;
1012 return 0;
1014​
1015export { sortActiveThreadsByOrderKey as sortThreadsForSidebar } from "@t3tools/client-runtime/state/thread-sort";
1016export {
1017 isThreadWorking as isSidebarThreadWorking,
1018 sortInboxThreadsByReturn,
1019 sortWorkingThreadsBySend,
1020} from "@t3tools/client-runtime/state/thread-inbox";
1021​
1022export { pinOrderKeyBetween } from "@t3tools/client-runtime/state/thread-sort";
1023export { sortPinnedThreadsByOrderKey as sortPinnedThreadsForSidebar } from "@t3tools/client-runtime/state/thread-sort";
1024​
1025const EMPTY_CONTENT_MATCH_KEYS: ReadonlySet<string> = new Set<string>();
1026​
1027export function searchSidebarThreads<
1028 T extends {
1029 readonly environmentId: EnvironmentId;
1030 readonly id: ThreadId;
1031 readonly title: string;
1032 } & Parameters<typeof threadPullRequestSearchTerms>[0],
1034 threads: readonly T[],
1035 query: string,
1036 contentMatchKeys: ReadonlySet<string> = EMPTY_CONTENT_MATCH_KEYS,
1037): T[] {
1038 const normalizedQuery = query.trim().toLowerCase();
1039 if (normalizedQuery.length === 0) return [];
1040 const titleMatches: T[] = [];
1041 const contentMatches: T[] = [];
1042 for (const thread of threads) {
1043 const matchesTitle = [thread.title, ...threadPullRequestSearchTerms(thread)].some((term) =>
1044 term.toLowerCase().includes(normalizedQuery),
1045 );
1046 if (matchesTitle) {
1047 titleMatches.push(thread);
1048 } else if (
1049 contentMatchKeys.size > 0 &&
1050 contentMatchKeys.has(
1051 threadSearchMatchKey({ environmentId: thread.environmentId, threadId: thread.id }),
1053 ) {
1054 contentMatches.push(thread);
1057 return [...titleMatches, ...contentMatches];
1059​
1060export function pullRequestMatchesSearchQuery(
1061 pullRequest: Parameters<typeof threadPullRequestSearchTerms>[0],
1062 query: string,
1063): boolean {
1064 const normalizedQuery = normalizeSearchText(query);
1065 if (normalizedQuery.length === 0) return false;
1066 const haystack = normalizeSearchText(threadPullRequestSearchTerms(pullRequest).join(" "));
1067 return normalizedQuery.split(" ").every((token) => haystack.includes(token));
1069​
1070export function filterSidebarProjectScopeItems<TItem extends { readonly value: string }>(input: {
1071 items: readonly TItem[];
1072 query: string;
1073 matches: (item: TItem, query: string) => boolean;
1074}): readonly TItem[] {
1075 const query = input.query.trim();
1076 if (query.length === 0) return input.items;
1077 return input.items.filter((item) => item.value !== "all" && input.matches(item, query));
1079​
1080export interface SidebarProjectScopeMenuState {
1081 readonly open: boolean;
1082 readonly query: string;
1084​
1085export type SidebarProjectScopeMenuAction =
1086 | { readonly type: "query-changed"; readonly query: string }
1087 | { readonly type: "open-changed"; readonly open: boolean }
1088 | { readonly type: "project-settings-opened" };
1089​
1090export function reduceSidebarProjectScopeMenuState(
1091 state: SidebarProjectScopeMenuState,
1092 action: SidebarProjectScopeMenuAction,
1093): SidebarProjectScopeMenuState {
1094 switch (action.type) {
1095 case "query-changed":
1096 return { ...state, query: action.query };
1097 case "open-changed":
1098 return { open: action.open, query: "" };
1099 case "project-settings-opened":
1100 return { open: false, query: "" };
1103​
1104export function resolveWorkingStartedAt(
1105 thread: Pick<SidebarThreadSummary, "latestRun" | "runtime">,
1106): string | null {
1107 return resolveThreadWorkingStartedAt(thread);
1109​
1110export function formatWorkingDurationLabel(elapsedMs: number): string {
1111 const seconds = Number.isFinite(elapsedMs) ? Math.max(0, Math.floor(elapsedMs / 1000)) : 0;
1112 if (seconds < 60) return `${seconds}s`;
1113 const minutes = Math.floor(seconds / 60);
1114 if (minutes < 60) return `${minutes}m`;
1115 return `${Math.floor(minutes / 60)}h ${minutes % 60}m`;
1117​
1118export function resolveThreadStatusPill(input: {
1119 thread: ThreadStatusInput;
1120}): ThreadStatusPill | null {
1121 const { thread } = input;
1122​
1123 if (thread.hasPendingApprovals || thread.pendingSubagentRequest === "approval") {
1124 return {
1125 label: "Pending Approval",
1126 colorClass: "text-amber-600 dark:text-amber-300/90",
1127 dotClass: "bg-amber-500 dark:bg-amber-300/90",
1128 pulse: false,
1129 };
1131​
1132 if (thread.hasPendingUserInput || thread.pendingSubagentRequest === "user_input") {
1133 return {
1134 label: "Awaiting Input",
1135 colorClass: "text-indigo-600 dark:text-indigo-300/90",
1136 dotClass: "bg-indigo-500 dark:bg-indigo-300/90",
1137 pulse: false,
1138 };
1140​
1141 if (thread.runtime?.status === "running" || thread.runtime?.status === "waiting") {
1142 return {
1143 label: "Working",
1144 colorClass: "text-sky-600 dark:text-sky-300/80",
1145 dotClass: "bg-sky-500 dark:bg-sky-300/80",
1146 pulse: true,
1147 };
1149​
1150 if (
1151 thread.runtime?.status === "preparing" ||
1152 thread.runtime?.status === "starting" ||
1153 thread.runtime?.status === "queued"
1154 ) {
1155 return {
1156 label: "Connecting",
1157 colorClass: "text-sky-600 dark:text-sky-300/80",
1158 dotClass: "bg-sky-500 dark:bg-sky-300/80",
1159 pulse: true,
1160 };
1162​
1163 if (backgroundWorkHoldsCompletion(thread.pendingBackgroundTasks ?? [])) {
1164 return {
1165 label: "Waiting",
1166 colorClass: "text-sidebar-muted-foreground",
1167 dotClass: "bg-sidebar-muted-foreground",
1168 pulse: false,
1169 };
1171​
1172 if (hasUnseenFailure(thread)) {
1173 return {
1174 label: "Failed",
1175 colorClass: "text-red-600 dark:text-red-300/90",
1176 dotClass: "bg-red-500 dark:bg-red-300/90",
1177 pulse: false,
1178 };
1180​
1181 const hasPlanReadyPrompt =
1182 !thread.hasPendingUserInput &&
1183 thread.interactionMode === "plan" &&
1184 isLatestRunSettled(thread.latestRun, thread.runtime) &&
1185 thread.hasActionableProposedPlan;
1186 if (hasPlanReadyPrompt) {
1187 return {
1188 label: "Plan Ready",
1189 colorClass: "text-violet-600 dark:text-violet-300/90",
1190 dotClass: "bg-violet-500 dark:bg-violet-300/90",
1191 pulse: false,
1192 };
1194​
1195 if (hasUnseenCompletion(thread)) {
1196 return {
1197 label: "Completed",
1198 colorClass: "text-emerald-600 dark:text-emerald-300/90",
1199 dotClass: "bg-emerald-500 dark:bg-emerald-300/90",
1200 pulse: false,
1201 };
1203​
1204 return null;
1206​
1207export function resolveProjectStatusIndicator(
1208 statuses: ReadonlyArray<ThreadStatusPill | null>,
1209): ThreadStatusPill | null {
1210 let highestPriorityStatus: ThreadStatusPill | null = null;
1211​
1212 for (const status of statuses) {
1213 if (status === null) continue;
1214 if (
1215 highestPriorityStatus === null ||
1216 THREAD_STATUS_PRIORITY[status.label] > THREAD_STATUS_PRIORITY[highestPriorityStatus.label]
1217 ) {
1218 highestPriorityStatus = status;
1221​
1222 return highestPriorityStatus;
1224​
1225export function getFallbackThreadIdAfterDelete<
1226 T extends Pick<Thread, "id" | "projectId" | "createdAt" | "updatedAt"> & ThreadSortInput,
1227>(input: {
1228 threads: readonly T[];
1229 deletedThreadId: T["id"];
1230 sortOrder: SidebarThreadSortOrder;
1231 deletedThreadIds?: ReadonlySet<T["id"]>;
1232}): T["id"] | null {
1233 const { deletedThreadId, deletedThreadIds, sortOrder, threads } = input;
1234 const deletedThread = threads.find((thread) => thread.id === deletedThreadId);
1235 if (!deletedThread) {
1236 return null;
1238​
1239 return (
1240 sortThreads(
1241 threads.filter(
1242 (thread) =>
1243 thread.projectId === deletedThread.projectId &&
1244 thread.id !== deletedThreadId &&
1245 !deletedThreadIds?.has(thread.id),
1246 ),
1247 sortOrder,
1248 )[0]?.id ?? null
1249 );
1251export function getProjectSortTimestamp(
1252 project: SidebarProject,
1253 projectThreads: readonly ThreadSortInput[],
1254 sortOrder: Exclude<SidebarProjectSortOrder, "manual">,
1255): number {
1256 if (projectThreads.length > 0) {
1257 return projectThreads.reduce(
1258 (latest, thread) => Math.max(latest, getThreadSortTimestamp(thread, sortOrder)),
1259 Number.NEGATIVE_INFINITY,
1260 );
1262​
1263 if (sortOrder === "created_at") {
1264 return toSortableTimestamp(project.createdAt) ?? Number.NEGATIVE_INFINITY;
1266 return toSortableTimestamp(project.updatedAt ?? project.createdAt) ?? Number.NEGATIVE_INFINITY;
1268​
1269function sortProjectsByActivity<TProject extends SidebarProject>(
1270 projects: readonly TProject[],
1271 sortOrder: SidebarProjectSortOrder,
1272 getProjectThreads: (project: TProject) => readonly ThreadSortInput[],
1273 compareTies: (left: TProject, right: TProject) => number,
1274): TProject[] {
1275 if (sortOrder === "manual") {
1276 return [...projects];
1278​
1279 // Each project's timestamp walks all of its threads, so compute it once
1280 // per project instead of once per comparison.
1281 return projects
1282 .map((project) => ({
1283 project,
1284 timestamp: getProjectSortTimestamp(project, getProjectThreads(project), sortOrder),
1285 }))
1286 .sort((left, right) => {
1287 const byTimestamp =
1288 right.timestamp === left.timestamp ? 0 : right.timestamp > left.timestamp ? 1 : -1;
1289 return byTimestamp || compareTies(left.project, right.project);
1290 })
1291 .map(({ project }) => project);
1293​
1294export function sortProjectsForSidebar<
1295 TProject extends SidebarProject,
1296 TThread extends Pick<Thread, "projectId" | "createdAt" | "updatedAt"> & ThreadSortInput,
1298 projects: readonly TProject[],
1299 threads: readonly TThread[],
1300 sortOrder: SidebarProjectSortOrder,
1301): TProject[] {
1302 const threadsByProjectId = new Map<string, TThread[]>();
1303 for (const thread of threads) {
1304 const existing = threadsByProjectId.get(thread.projectId) ?? [];
1305 existing.push(thread);
1306 threadsByProjectId.set(thread.projectId, existing);
1308​
1309 return sortProjectsByActivity(
1310 projects,
1311 sortOrder,
1312 (project) => threadsByProjectId.get(project.id) ?? [],
1313 (left, right) => left.title.localeCompare(right.title) || left.id.localeCompare(right.id),
1314 );
1316​
1317export function sortLogicalProjectsForSidebar<
1318 TProject extends LogicalSidebarProject,
1319 TThread extends ScopedSidebarThread,
1321 projects: readonly TProject[],
1322 threads: readonly TThread[],
1323 sortOrder: SidebarProjectSortOrder,
1324): TProject[] {
1325 const groupKeyByProjectRef = new Map(
1326 projects.flatMap((project) =>
1327 project.memberProjectRefs.map(
1328 (projectRef) =>
1329 [`${projectRef.environmentId}\0${projectRef.projectId}`, project.projectKey] as const,
1330 ),
1331 ),
1332 );
1333 const threadsByProjectKey = new Map<string, TThread[]>();
1334 for (const thread of threads) {
1335 if (thread.archivedAt !== null) continue;
1336 const projectKey = groupKeyByProjectRef.get(`${thread.environmentId}\0${thread.projectId}`);
1337 if (!projectKey) continue;
1338 const existing = threadsByProjectKey.get(projectKey);
1339 if (existing) {
1340 existing.push(thread);
1341 } else {
1342 threadsByProjectKey.set(projectKey, [thread]);
1345​
1346 return sortProjectsByActivity(
1347 projects,
1348 sortOrder,
1349 (project) => threadsByProjectKey.get(project.projectKey) ?? [],
1350 (left, right) =>
1351 left.title.localeCompare(right.title) || left.projectKey.localeCompare(right.projectKey),
1352 );
1354​
1355export function sortSidebarV2ProjectGroups<
1356 TProject extends LogicalSidebarProject,
1357 TThread extends ScopedSidebarThread & Pick<SidebarThreadSummary, "lineage">,
1359 projects: readonly TProject[],
1360 threads: readonly TThread[],
1361 sortOrder: SidebarProjectSortOrder,
1362): TProject[] {
1363 return sortLogicalProjectsForSidebar(
1364 projects,
1365 filterSidebarV2VisibleThreads(threads, null),
1366 sortOrder,
1367 );
1369​
1370export function sortScopedProjectsForSidebar<
1371 TProject extends ScopedSidebarProject,
1372 TThread extends ScopedSidebarThread,
1374 projects: readonly TProject[],
1375 threads: readonly TThread[],
1376 sortOrder: SidebarProjectSortOrder,
1377): TProject[] {
1378 const scopedKey = (environmentId: string, projectId: string) =>
1379 `${environmentId}\u0000${projectId}`;
1380 const threadsByProject = new Map<string, TThread[]>();
1381 for (const thread of threads) {
1382 if (thread.archivedAt !== null) {
1383 continue;
1385 const key = scopedKey(thread.environmentId, thread.projectId);
1386 const existing = threadsByProject.get(key) ?? [];
1387 existing.push(thread);
1388 threadsByProject.set(key, existing);
1390​
1391 return sortProjectsByActivity(
1392 projects,
1393 sortOrder,
1394 (project) => threadsByProject.get(scopedKey(project.environmentId, project.id)) ?? [],
1395 (left, right) =>
1396 left.title.localeCompare(right.title) ||
1397 left.environmentId.localeCompare(right.environmentId) ||
1398 left.id.localeCompare(right.id),
1399 );