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

Sidebar.logic.ts

1,359 lines44.6 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 = "approval" | "input" | "working" | "waiting" | "failed" | "ready";
881​
882export function shouldRecedeSidebarThread(input: {
883 status: SidebarThreadStatus;
884 isUnread: boolean;
885 isWoke: boolean;
886 isActive: boolean;
887 isSelected: boolean;
888}): boolean {
889 if (input.isActive || input.isSelected || input.status === "input") return false;
890 if (input.status === "working" || input.status === "waiting") return true;
891 if (input.status === "ready" || input.status === "approval") {
892 return !input.isUnread && !input.isWoke;
893 }
894 return false;
896​
897type SidebarThreadStatusInput = Pick<
898 SidebarThreadSummary,
899 "hasPendingApprovals" | "hasPendingUserInput" | "runtime"
900>;
901​
902export function resolveSidebarThreadStatus(thread: SidebarThreadStatusInput): SidebarThreadStatus {
903 if (thread.hasPendingApprovals) {
904 return "approval";
905 }
906 if (thread.hasPendingUserInput) {
907 return "input";
908 }
909 if (
910 thread.runtime !== null &&
911 ["preparing", "queued", "starting", "running", "waiting"].includes(thread.runtime.status)
912 ) {
913 return "working";
914 }
915 if (thread.runtime?.status === "idle") {
916 return "waiting";
917 }
918 if (thread.runtime?.status === "failed") {
919 return "failed";
920 }
921 return "ready";
923​
924export type SidebarV2TopStatusKind =
925 | "approval"
926 | "done"
927 | "failed"
928 | "input"
929 | "waiting"
930 | "woke"
931 | "working";
932​
933export function resolveSidebarV2TopStatus(input: {
934 readonly status: SidebarThreadStatus;
935 readonly isUnread: boolean;
936 readonly isWoke: boolean;
937}): SidebarV2TopStatusKind | null {
938 if (input.status === "working") {
939 return "working";
940 }
941 if (input.status === "waiting") {
942 return "waiting";
943 }
944 if (input.status === "approval") {
945 return "approval";
946 }
947 if (input.status === "input") {
948 return "input";
949 }
950 if (input.status === "failed") {
951 return "failed";
952 }
953 if (input.isWoke) {
954 return "woke";
955 }
956 return input.isUnread ? "done" : null;
958​
959export function shouldShowSidebarV2Duration(status: SidebarThreadStatus): boolean {
960 return status === "working";
962​
963/** First VALID timestamp wins: `a ?? b` falls through on null, but a present-
964 yet-malformed string must also fall through to the next candidate rather
965 than sink the row to the epoch. */
966export function firstValidTimestampMs(
967 ...candidates: ReadonlyArray<string | null | undefined>
968): number {
969 for (const candidate of candidates) {
970 if (candidate == null) continue;
971 const parsed = Date.parse(candidate);
972 if (!Number.isNaN(parsed)) return parsed;
973 }
974 return 0;
976​
977export { sortActiveThreadsByOrderKey as sortThreadsForSidebar } from "@t3tools/client-runtime/state/thread-sort";
978​
979// Pinned-reorder key math and the keyed sort live in client-runtime
980// (state/thread-sort) so web and mobile compute identical pinned orders.
981export { pinOrderKeyBetween, planPinnedReorder } from "@t3tools/client-runtime/state/thread-sort";
982export { sortPinnedThreadsByOrderKey as sortPinnedThreadsForSidebar } from "@t3tools/client-runtime/state/thread-sort";
983​
984const EMPTY_CONTENT_MATCH_KEYS: ReadonlySet<string> = new Set<string>();
985​
986/**
987 * Search the already-ordered sidebar thread collection by title or linked PR,
988 * plus any thread whose messages the server matched (`contentMatchKeys`, keyed
989 * by `threadSearchMatchKey`). Keeping the input order means lifecycle ordering
990 * (active, snoozed, settled) remains stable while the user narrows the list.
991 */
992export function searchSidebarThreads<
993 T extends {
994 readonly environmentId: EnvironmentId;
995 readonly id: ThreadId;
996 readonly title: string;
997 } & Parameters<typeof threadPullRequestSearchTerms>[0],
998>(
999 threads: readonly T[],
1000 query: string,
1001 contentMatchKeys: ReadonlySet<string> = EMPTY_CONTENT_MATCH_KEYS,
1002): T[] {
1003 const normalizedQuery = query.trim().toLowerCase();
1004 if (normalizedQuery.length === 0) return [];
1005 const titleMatches: T[] = [];
1006 const contentMatches: T[] = [];
1007 for (const thread of threads) {
1008 const matchesTitle = [thread.title, ...threadPullRequestSearchTerms(thread)].some((term) =>
1009 term.toLowerCase().includes(normalizedQuery),
1010 );
1011 if (matchesTitle) {
1012 titleMatches.push(thread);
1013 } else if (
1014 contentMatchKeys.size > 0 &&
1015 contentMatchKeys.has(
1016 threadSearchMatchKey({ environmentId: thread.environmentId, threadId: thread.id }),
1018 ) {
1019 contentMatches.push(thread);
1022 return [...titleMatches, ...contentMatches];
1024​
1025export function filterSidebarProjectScopeItems<TItem extends { readonly value: string }>(input: {
1026 items: readonly TItem[];
1027 query: string;
1028 matches: (item: TItem, query: string) => boolean;
1029}): readonly TItem[] {
1030 const query = input.query.trim();
1031 if (query.length === 0) return input.items;
1032 return input.items.filter((item) => item.value !== "all" && input.matches(item, query));
1034​
1035export interface SidebarProjectScopeMenuState {
1036 readonly open: boolean;
1037 readonly query: string;
1039​
1040export type SidebarProjectScopeMenuAction =
1041 | { readonly type: "query-changed"; readonly query: string }
1042 | { readonly type: "open-changed"; readonly open: boolean }
1043 | { readonly type: "project-settings-opened" };
1044​
1045export function reduceSidebarProjectScopeMenuState(
1046 state: SidebarProjectScopeMenuState,
1047 action: SidebarProjectScopeMenuAction,
1048): SidebarProjectScopeMenuState {
1049 switch (action.type) {
1050 case "query-changed":
1051 return { ...state, query: action.query };
1052 case "open-changed":
1053 return { open: action.open, query: "" };
1054 case "project-settings-opened":
1055 return { open: false, query: "" };
1058​
1059// Settled rows are history, so they order by when the work ENDED, not when
1060// the thread was created or last touched.
1061export function sortSettledThreadsForSidebar<
1062 T extends SettledThreadTimestampInput & { readonly id: string },
1063>(threads: readonly T[]): T[] {
1064 const timestampMs = (thread: T) => {
1065 const timestamp = resolveSettledThreadTimestamp(thread);
1066 return timestamp === null ? 0 : Date.parse(timestamp);
1067 };
1068 return [...threads].toSorted(
1069 (left, right) => timestampMs(right) - timestampMs(left) || left.id.localeCompare(right.id),
1070 );
1072​
1073export function resolveWorkingStartedAt(
1074 thread: Pick<SidebarThreadSummary, "latestRun" | "runtime">,
1075): string | null {
1076 return resolveThreadWorkingStartedAt(thread);
1078​
1079export function formatWorkingDurationLabel(elapsedMs: number): string {
1080 const seconds = Number.isFinite(elapsedMs) ? Math.max(0, Math.floor(elapsedMs / 1000)) : 0;
1081 if (seconds < 60) return `${seconds}s`;
1082 const minutes = Math.floor(seconds / 60);
1083 if (minutes < 60) return `${minutes}m`;
1084 return `${Math.floor(minutes / 60)}h ${minutes % 60}m`;
1086​
1087export function resolveThreadStatusPill(input: {
1088 thread: ThreadStatusInput;
1089}): ThreadStatusPill | null {
1090 const { thread } = input;
1091​
1092 if (thread.hasPendingApprovals) {
1093 return {
1094 label: "Pending Approval",
1095 colorClass: "text-amber-600 dark:text-amber-300/90",
1096 dotClass: "bg-amber-500 dark:bg-amber-300/90",
1097 pulse: false,
1098 };
1100​
1101 if (thread.hasPendingUserInput) {
1102 return {
1103 label: "Awaiting Input",
1104 colorClass: "text-indigo-600 dark:text-indigo-300/90",
1105 dotClass: "bg-indigo-500 dark:bg-indigo-300/90",
1106 pulse: false,
1107 };
1109​
1110 if (thread.runtime?.status === "running" || thread.runtime?.status === "waiting") {
1111 return {
1112 label: "Working",
1113 colorClass: "text-sky-600 dark:text-sky-300/80",
1114 dotClass: "bg-sky-500 dark:bg-sky-300/80",
1115 pulse: true,
1116 };
1118​
1119 if (
1120 thread.runtime?.status === "preparing" ||
1121 thread.runtime?.status === "starting" ||
1122 thread.runtime?.status === "queued"
1123 ) {
1124 return {
1125 label: "Connecting",
1126 colorClass: "text-sky-600 dark:text-sky-300/80",
1127 dotClass: "bg-sky-500 dark:bg-sky-300/80",
1128 pulse: true,
1129 };
1131​
1132 if ((thread.pendingBackgroundTasks?.length ?? 0) > 0) {
1133 return {
1134 label: "Waiting",
1135 colorClass: "text-sidebar-muted-foreground",
1136 dotClass: "bg-sidebar-muted-foreground",
1137 pulse: false,
1138 };
1140​
1141 const hasPlanReadyPrompt =
1142 !thread.hasPendingUserInput &&
1143 thread.interactionMode === "plan" &&
1144 isLatestRunSettled(thread.latestRun, thread.runtime) &&
1145 thread.hasActionableProposedPlan;
1146 if (hasPlanReadyPrompt) {
1147 return {
1148 label: "Plan Ready",
1149 colorClass: "text-violet-600 dark:text-violet-300/90",
1150 dotClass: "bg-violet-500 dark:bg-violet-300/90",
1151 pulse: false,
1152 };
1154​
1155 if (hasUnseenCompletion(thread)) {
1156 return {
1157 label: "Completed",
1158 colorClass: "text-emerald-600 dark:text-emerald-300/90",
1159 dotClass: "bg-emerald-500 dark:bg-emerald-300/90",
1160 pulse: false,
1161 };
1163​
1164 return null;
1166​
1167export function resolveProjectStatusIndicator(
1168 statuses: ReadonlyArray<ThreadStatusPill | null>,
1169): ThreadStatusPill | null {
1170 let highestPriorityStatus: ThreadStatusPill | null = null;
1171​
1172 for (const status of statuses) {
1173 if (status === null) continue;
1174 if (
1175 highestPriorityStatus === null ||
1176 THREAD_STATUS_PRIORITY[status.label] > THREAD_STATUS_PRIORITY[highestPriorityStatus.label]
1177 ) {
1178 highestPriorityStatus = status;
1181​
1182 return highestPriorityStatus;
1184​
1185export function getFallbackThreadIdAfterDelete<
1186 T extends Pick<Thread, "id" | "projectId" | "createdAt" | "updatedAt"> & ThreadSortInput,
1187>(input: {
1188 threads: readonly T[];
1189 deletedThreadId: T["id"];
1190 sortOrder: SidebarThreadSortOrder;
1191 deletedThreadIds?: ReadonlySet<T["id"]>;
1192}): T["id"] | null {
1193 const { deletedThreadId, deletedThreadIds, sortOrder, threads } = input;
1194 const deletedThread = threads.find((thread) => thread.id === deletedThreadId);
1195 if (!deletedThread) {
1196 return null;
1198​
1199 return (
1200 sortThreads(
1201 threads.filter(
1202 (thread) =>
1203 thread.projectId === deletedThread.projectId &&
1204 thread.id !== deletedThreadId &&
1205 !deletedThreadIds?.has(thread.id),
1206 ),
1207 sortOrder,
1208 )[0]?.id ?? null
1209 );
1211export function getProjectSortTimestamp(
1212 project: SidebarProject,
1213 projectThreads: readonly ThreadSortInput[],
1214 sortOrder: Exclude<SidebarProjectSortOrder, "manual">,
1215): number {
1216 if (projectThreads.length > 0) {
1217 return projectThreads.reduce(
1218 (latest, thread) => Math.max(latest, getThreadSortTimestamp(thread, sortOrder)),
1219 Number.NEGATIVE_INFINITY,
1220 );
1222​
1223 if (sortOrder === "created_at") {
1224 return toSortableTimestamp(project.createdAt) ?? Number.NEGATIVE_INFINITY;
1226 return toSortableTimestamp(project.updatedAt ?? project.createdAt) ?? Number.NEGATIVE_INFINITY;
1228​
1229function sortProjectsByActivity<TProject extends SidebarProject>(
1230 projects: readonly TProject[],
1231 sortOrder: SidebarProjectSortOrder,
1232 getProjectThreads: (project: TProject) => readonly ThreadSortInput[],
1233 compareTies: (left: TProject, right: TProject) => number,
1234): TProject[] {
1235 if (sortOrder === "manual") {
1236 return [...projects];
1238​
1239 return [...projects].toSorted((left, right) => {
1240 const rightTimestamp = getProjectSortTimestamp(right, getProjectThreads(right), sortOrder);
1241 const leftTimestamp = getProjectSortTimestamp(left, getProjectThreads(left), sortOrder);
1242 const byTimestamp =
1243 rightTimestamp === leftTimestamp ? 0 : rightTimestamp > leftTimestamp ? 1 : -1;
1244 return byTimestamp || compareTies(left, right);
1245 });
1247​
1248export function sortProjectsForSidebar<
1249 TProject extends SidebarProject,
1250 TThread extends Pick<Thread, "projectId" | "createdAt" | "updatedAt"> & ThreadSortInput,
1252 projects: readonly TProject[],
1253 threads: readonly TThread[],
1254 sortOrder: SidebarProjectSortOrder,
1255): TProject[] {
1256 const threadsByProjectId = new Map<string, TThread[]>();
1257 for (const thread of threads) {
1258 const existing = threadsByProjectId.get(thread.projectId) ?? [];
1259 existing.push(thread);
1260 threadsByProjectId.set(thread.projectId, existing);
1262​
1263 return sortProjectsByActivity(
1264 projects,
1265 sortOrder,
1266 (project) => threadsByProjectId.get(project.id) ?? [],
1267 (left, right) => left.title.localeCompare(right.title) || left.id.localeCompare(right.id),
1268 );
1270​
1271export function sortLogicalProjectsForSidebar<
1272 TProject extends LogicalSidebarProject,
1273 TThread extends ScopedSidebarThread,
1275 projects: readonly TProject[],
1276 threads: readonly TThread[],
1277 sortOrder: SidebarProjectSortOrder,
1278): TProject[] {
1279 const groupKeyByProjectRef = new Map(
1280 projects.flatMap((project) =>
1281 project.memberProjectRefs.map(
1282 (projectRef) =>
1283 [`${projectRef.environmentId}\0${projectRef.projectId}`, project.projectKey] as const,
1284 ),
1285 ),
1286 );
1287 const threadsByProjectKey = new Map<string, TThread[]>();
1288 for (const thread of threads) {
1289 if (thread.archivedAt !== null) continue;
1290 const projectKey = groupKeyByProjectRef.get(`${thread.environmentId}\0${thread.projectId}`);
1291 if (!projectKey) continue;
1292 const existing = threadsByProjectKey.get(projectKey);
1293 if (existing) {
1294 existing.push(thread);
1295 } else {
1296 threadsByProjectKey.set(projectKey, [thread]);
1299​
1300 return sortProjectsByActivity(
1301 projects,
1302 sortOrder,
1303 (project) => threadsByProjectKey.get(project.projectKey) ?? [],
1304 (left, right) =>
1305 left.title.localeCompare(right.title) || left.projectKey.localeCompare(right.projectKey),
1306 );
1308​
1309export function sortSidebarV2ProjectGroups<
1310 TProject extends LogicalSidebarProject,
1311 TThread extends ScopedSidebarThread & Pick<SidebarThreadSummary, "lineage">,
1313 projects: readonly TProject[],
1314 threads: readonly TThread[],
1315 sortOrder: SidebarProjectSortOrder,
1316): TProject[] {
1317 return sortLogicalProjectsForSidebar(
1318 projects,
1319 filterSidebarV2VisibleThreads(threads, null),
1320 sortOrder,
1321 );
1323​
1324/**
1325 * Sorts the cross-environment project collection used by landing surfaces.
1326 * Project ids are only unique within an environment, and archived threads
1327 * must not make a project appear recently active.
1328 */
1329export function sortScopedProjectsForSidebar<
1330 TProject extends ScopedSidebarProject,
1331 TThread extends ScopedSidebarThread,
1333 projects: readonly TProject[],
1334 threads: readonly TThread[],
1335 sortOrder: SidebarProjectSortOrder,
1336): TProject[] {
1337 const scopedKey = (environmentId: string, projectId: string) =>
1338 `${environmentId}\u0000${projectId}`;
1339 const threadsByProject = new Map<string, TThread[]>();
1340 for (const thread of threads) {
1341 if (thread.archivedAt !== null) {
1342 continue;
1344 const key = scopedKey(thread.environmentId, thread.projectId);
1345 const existing = threadsByProject.get(key) ?? [];
1346 existing.push(thread);
1347 threadsByProject.set(key, existing);
1349​
1350 return sortProjectsByActivity(
1351 projects,
1352 sortOrder,
1353 (project) => threadsByProject.get(scopedKey(project.environmentId, project.id)) ?? [],
1354 (left, right) =>
1355 left.title.localeCompare(right.title) ||
1356 left.environmentId.localeCompare(right.environmentId) ||
1357 left.id.localeCompare(right.id),
1358 );