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