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

Sidebar.logic.ts

1,446 lines47.9 KB

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 );
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 };
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 };
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;
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";
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}`;
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);
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;
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 };
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";
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 }
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 };
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 };
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 };
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 ];
530​
531export function isSidebarSubagentThread(thread: Pick<SidebarThreadSummary, "lineage">): boolean {
532 return thread.lineage.relationshipToParent === "subagent";
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 );
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;
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 };
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})` };
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;
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;
632​
633export function resolveSidebarStageBadgeLabel(input: {
634 primaryServerVersion: string | null | undefined;
635 fallbackStageLabel: string;
636}): string {
637 return resolveServerBackedAppStageLabel(input);
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 };
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 };
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;
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;
748​
749export function shouldClearThreadSelectionOnMouseDown(target: HTMLElement | null): boolean {
750 if (target === null) return true;
751 return !target.closest(THREAD_SELECTION_SAFE_SELECTOR);
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;
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);
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;
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;
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];
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));
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;
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;
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 );
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;
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";
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";
1002 return input.isUnread ? "done" : null;
1004​
1005export function shouldShowSidebarV2Duration(status: SidebarThreadStatus): boolean {
1006 return status === "working";
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 );
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;
1035 return 0;
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],
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 }),
1079 ) {
1080 contentMatches.push(thread);
1083 return [...titleMatches, ...contentMatches];
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));
1095​
1096export interface SidebarProjectScopeMenuState {
1097 readonly open: boolean;
1098 readonly query: string;
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: "" };
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 );
1149​
1150/** The timestamp a working thread's elapsed label counts from: the running
1151 turn's start (request time until adoption), falling back to the session's
1152 last transition when the turn projection lags behind. Malformed
1153 timestamps fall through to the next candidate, not just missing ones. */
1154export function resolveWorkingStartedAt(
1155 thread: Pick<SidebarThreadSummary, "latestRun" | "runtime">,
1156): string | null {
1157 return resolveThreadWorkingStartedAt(thread);
1159​
1160export function formatWorkingDurationLabel(elapsedMs: number): string {
1161 const seconds = Number.isFinite(elapsedMs) ? Math.max(0, Math.floor(elapsedMs / 1000)) : 0;
1162 if (seconds < 60) return `${seconds}s`;
1163 const minutes = Math.floor(seconds / 60);
1164 if (minutes < 60) return `${minutes}m`;
1165 return `${Math.floor(minutes / 60)}h ${minutes % 60}m`;
1167​
1168export function resolveThreadStatusPill(input: {
1169 thread: ThreadStatusInput;
1170}): ThreadStatusPill | null {
1171 const { thread } = input;
1172​
1173 if (thread.hasPendingApprovals) {
1174 return {
1175 label: "Pending Approval",
1176 colorClass: "text-amber-600 dark:text-amber-300/90",
1177 dotClass: "bg-amber-500 dark:bg-amber-300/90",
1178 pulse: false,
1179 };
1181​
1182 if (thread.hasPendingUserInput) {
1183 return {
1184 label: "Awaiting Input",
1185 colorClass: "text-indigo-600 dark:text-indigo-300/90",
1186 dotClass: "bg-indigo-500 dark:bg-indigo-300/90",
1187 pulse: false,
1188 };
1190​
1191 if (thread.runtime?.status === "running" || thread.runtime?.status === "waiting") {
1192 return {
1193 label: "Working",
1194 colorClass: "text-sky-600 dark:text-sky-300/80",
1195 dotClass: "bg-sky-500 dark:bg-sky-300/80",
1196 pulse: true,
1197 };
1199​
1200 if (
1201 thread.runtime?.status === "preparing" ||
1202 thread.runtime?.status === "starting" ||
1203 thread.runtime?.status === "queued"
1204 ) {
1205 return {
1206 label: "Connecting",
1207 colorClass: "text-sky-600 dark:text-sky-300/80",
1208 dotClass: "bg-sky-500 dark:bg-sky-300/80",
1209 pulse: true,
1210 };
1212​
1213 if ((thread.pendingBackgroundTasks?.length ?? 0) > 0) {
1214 return {
1215 label: "Waiting",
1216 colorClass: "text-sidebar-muted-foreground",
1217 dotClass: "bg-sidebar-muted-foreground",
1218 pulse: false,
1219 };
1221​
1222 const hasPlanReadyPrompt =
1223 !thread.hasPendingUserInput &&
1224 thread.interactionMode === "plan" &&
1225 isLatestRunSettled(thread.latestRun, thread.runtime) &&
1226 thread.hasActionableProposedPlan;
1227 if (hasPlanReadyPrompt) {
1228 return {
1229 label: "Plan Ready",
1230 colorClass: "text-violet-600 dark:text-violet-300/90",
1231 dotClass: "bg-violet-500 dark:bg-violet-300/90",
1232 pulse: false,
1233 };
1235​
1236 if (hasUnseenCompletion(thread)) {
1237 return {
1238 label: "Completed",
1239 colorClass: "text-emerald-600 dark:text-emerald-300/90",
1240 dotClass: "bg-emerald-500 dark:bg-emerald-300/90",
1241 pulse: false,
1242 };
1244​
1245 return null;
1247​
1248export function resolveProjectStatusIndicator(
1249 statuses: ReadonlyArray<ThreadStatusPill | null>,
1250): ThreadStatusPill | null {
1251 let highestPriorityStatus: ThreadStatusPill | null = null;
1252​
1253 for (const status of statuses) {
1254 if (status === null) continue;
1255 if (
1256 highestPriorityStatus === null ||
1257 THREAD_STATUS_PRIORITY[status.label] > THREAD_STATUS_PRIORITY[highestPriorityStatus.label]
1258 ) {
1259 highestPriorityStatus = status;
1262​
1263 return highestPriorityStatus;
1265​
1266export function getFallbackThreadIdAfterDelete<
1267 T extends Pick<Thread, "id" | "projectId" | "createdAt" | "updatedAt"> & ThreadSortInput,
1268>(input: {
1269 threads: readonly T[];
1270 deletedThreadId: T["id"];
1271 sortOrder: SidebarThreadSortOrder;
1272 deletedThreadIds?: ReadonlySet<T["id"]>;
1273}): T["id"] | null {
1274 const { deletedThreadId, deletedThreadIds, sortOrder, threads } = input;
1275 const deletedThread = threads.find((thread) => thread.id === deletedThreadId);
1276 if (!deletedThread) {
1277 return null;
1279​
1280 return (
1281 sortThreads(
1282 threads.filter(
1283 (thread) =>
1284 thread.projectId === deletedThread.projectId &&
1285 thread.id !== deletedThreadId &&
1286 !deletedThreadIds?.has(thread.id),
1287 ),
1288 sortOrder,
1289 )[0]?.id ?? null
1290 );
1292export function getProjectSortTimestamp(
1293 project: SidebarProject,
1294 projectThreads: readonly ThreadSortInput[],
1295 sortOrder: Exclude<SidebarProjectSortOrder, "manual">,
1296): number {
1297 if (projectThreads.length > 0) {
1298 return projectThreads.reduce(
1299 (latest, thread) => Math.max(latest, getThreadSortTimestamp(thread, sortOrder)),
1300 Number.NEGATIVE_INFINITY,
1301 );
1303​
1304 if (sortOrder === "created_at") {
1305 return toSortableTimestamp(project.createdAt) ?? Number.NEGATIVE_INFINITY;
1307 return toSortableTimestamp(project.updatedAt ?? project.createdAt) ?? Number.NEGATIVE_INFINITY;
1309​
1310function sortProjectsByActivity<TProject extends SidebarProject>(
1311 projects: readonly TProject[],
1312 sortOrder: SidebarProjectSortOrder,
1313 getProjectThreads: (project: TProject) => readonly ThreadSortInput[],
1314 compareTies: (left: TProject, right: TProject) => number,
1315): TProject[] {
1316 if (sortOrder === "manual") {
1317 return [...projects];
1319​
1320 // Each project's timestamp walks all of its threads, so compute it once
1321 // per project instead of once per comparison.
1322 return projects
1323 .map((project) => ({
1324 project,
1325 timestamp: getProjectSortTimestamp(project, getProjectThreads(project), sortOrder),
1326 }))
1327 .sort((left, right) => {
1328 const byTimestamp =
1329 right.timestamp === left.timestamp ? 0 : right.timestamp > left.timestamp ? 1 : -1;
1330 return byTimestamp || compareTies(left.project, right.project);
1331 })
1332 .map(({ project }) => project);
1334​
1335export function sortProjectsForSidebar<
1336 TProject extends SidebarProject,
1337 TThread extends Pick<Thread, "projectId" | "createdAt" | "updatedAt"> & ThreadSortInput,
1339 projects: readonly TProject[],
1340 threads: readonly TThread[],
1341 sortOrder: SidebarProjectSortOrder,
1342): TProject[] {
1343 const threadsByProjectId = new Map<string, TThread[]>();
1344 for (const thread of threads) {
1345 const existing = threadsByProjectId.get(thread.projectId) ?? [];
1346 existing.push(thread);
1347 threadsByProjectId.set(thread.projectId, existing);
1349​
1350 return sortProjectsByActivity(
1351 projects,
1352 sortOrder,
1353 (project) => threadsByProjectId.get(project.id) ?? [],
1354 (left, right) => left.title.localeCompare(right.title) || left.id.localeCompare(right.id),
1355 );
1357​
1358export function sortLogicalProjectsForSidebar<
1359 TProject extends LogicalSidebarProject,
1360 TThread extends ScopedSidebarThread,
1362 projects: readonly TProject[],
1363 threads: readonly TThread[],
1364 sortOrder: SidebarProjectSortOrder,
1365): TProject[] {
1366 const groupKeyByProjectRef = new Map(
1367 projects.flatMap((project) =>
1368 project.memberProjectRefs.map(
1369 (projectRef) =>
1370 [`${projectRef.environmentId}\0${projectRef.projectId}`, project.projectKey] as const,
1371 ),
1372 ),
1373 );
1374 const threadsByProjectKey = new Map<string, TThread[]>();
1375 for (const thread of threads) {
1376 if (thread.archivedAt !== null) continue;
1377 const projectKey = groupKeyByProjectRef.get(`${thread.environmentId}\0${thread.projectId}`);
1378 if (!projectKey) continue;
1379 const existing = threadsByProjectKey.get(projectKey);
1380 if (existing) {
1381 existing.push(thread);
1382 } else {
1383 threadsByProjectKey.set(projectKey, [thread]);
1386​
1387 return sortProjectsByActivity(
1388 projects,
1389 sortOrder,
1390 (project) => threadsByProjectKey.get(project.projectKey) ?? [],
1391 (left, right) =>
1392 left.title.localeCompare(right.title) || left.projectKey.localeCompare(right.projectKey),
1393 );
1395​
1396export function sortSidebarV2ProjectGroups<
1397 TProject extends LogicalSidebarProject,
1398 TThread extends ScopedSidebarThread & Pick<SidebarThreadSummary, "lineage">,
1400 projects: readonly TProject[],
1401 threads: readonly TThread[],
1402 sortOrder: SidebarProjectSortOrder,
1403): TProject[] {
1404 return sortLogicalProjectsForSidebar(
1405 projects,
1406 filterSidebarV2VisibleThreads(threads, null),
1407 sortOrder,
1408 );
1410​
1411/**
1412 * Sorts the cross-environment project collection used by landing surfaces.
1413 * Project ids are only unique within an environment, and archived threads
1414 * must not make a project appear recently active.
1415 */
1416export function sortScopedProjectsForSidebar<
1417 TProject extends ScopedSidebarProject,
1418 TThread extends ScopedSidebarThread,
1420 projects: readonly TProject[],
1421 threads: readonly TThread[],
1422 sortOrder: SidebarProjectSortOrder,
1423): TProject[] {
1424 const scopedKey = (environmentId: string, projectId: string) =>
1425 `${environmentId}\u0000${projectId}`;
1426 const threadsByProject = new Map<string, TThread[]>();
1427 for (const thread of threads) {
1428 if (thread.archivedAt !== null) {
1429 continue;
1431 const key = scopedKey(thread.environmentId, thread.projectId);
1432 const existing = threadsByProject.get(key) ?? [];
1433 existing.push(thread);
1434 threadsByProject.set(key, existing);
1436​
1437 return sortProjectsByActivity(
1438 projects,
1439 sortOrder,
1440 (project) => threadsByProject.get(scopedKey(project.environmentId, project.id)) ?? [],
1441 (left, right) =>
1442 left.title.localeCompare(right.title) ||
1443 left.environmentId.localeCompare(right.environmentId) ||
1444 left.id.localeCompare(right.id),
1445 );