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