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

Sidebar.logic.ts

1,380 lines43.6 KB

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