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