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

Sidebar.logic.ts

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