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

Sidebar.logic.ts

1,359 lines43.9 KB

1import { resolveThreadWorkingStartedAt } from "@t3tools/client-runtime/state/models";
2import { isShownUnderParent } from "@t3tools/client-runtime/state/threads";
3import { backgroundWorkHoldsCompletion } from "@t3tools/shared/orchestrationV2PendingBackgroundWork";
4import { threadPullRequestSearchTerms } from "@t3tools/shared/threadPullRequests";
5import * as React from "react";
6import {
7 isAtomCommandInterrupted,
8 type AtomCommandResult,
9} from "@t3tools/client-runtime/state/runtime";
10import { defaultAnimateLayoutChanges, type AnimateLayoutChanges } from "@dnd-kit/sortable";
11import {
12 threadSearchMatchKey,
13 threadSearchSubject,
14 type ThreadSearchShell,
15} from "@t3tools/client-runtime/state/thread-search";
16import { foldSearchQuery, rankSearchItems, scoreThreadSearch } from "@t3tools/shared/paletteSearch";
17import type { ContextMenuItem, EnvironmentId, ThreadId } from "@t3tools/contracts";
18import type { SidebarProjectSortOrder, SidebarThreadSortOrder } from "@t3tools/contracts/settings";
19import type { AsyncResult } from "effect/reactivity";
20import { planPinnedReorder } from "@t3tools/client-runtime/state/thread-sort";
21import {
22 effectiveSnoozed,
23 type ThreadSnoozeShell,
24} from "@t3tools/client-runtime/state/thread-settled";
25import {
26 getThreadSortTimestamp,
27 sortThreads,
28 toSortableTimestamp,
29 type ThreadSortInput,
30} from "../lib/threadSort";
31import type { SidebarThreadSummary, Thread } from "../types";
32import { normalizeSearchText } from "../lib/utils";
33import { isLatestRunSettled } from "../session-logic";
34import { observeIntersection } from "../lib/observeIntersection";
35import { deadlineAfter, deadlineStore } from "@t3tools/client-runtime/clock";
36import { useDeadlinePassed } from "../hooks/useDeadline";
37​
38export function shouldNavigateAfterThreadPark(input: {
39 readonly threadKey: string;
40 readonly currentThreadKey: string | null;
41 readonly action: "settle" | "snooze";
42 readonly now: string;
43 readonly thread: (ThreadSnoozeShell & Pick<SidebarThreadSummary, "settledOverride">) | null;
44}): boolean {
45 return (
46 input.threadKey === input.currentThreadKey &&
47 input.thread !== null &&
48 (input.action === "settle"
49 ? input.thread.settledOverride === "settled"
50 : effectiveSnoozed(input.thread, { now: input.now }))
51 );
53​
54const THREAD_SELECTION_SAFE_SELECTOR = "[data-thread-item], [data-thread-selection-safe]";
55const THREAD_JUMP_HINT_SHOW_DELAY_MS = 200;
56​
57export function resolveSidebarRowAccessibility(input: {
58 readonly title: string;
59 readonly statusLabel: string | null;
60 readonly projectDisplayName: string | null;
61 readonly isActive: boolean;
62}): { readonly label: string; readonly current: "page" | undefined } {
63 return {
64 label: [input.title, input.statusLabel, input.projectDisplayName].filter(Boolean).join(", "),
65 current: input.isActive ? "page" : undefined,
66 };
68​
69// Each prewarm retains growing thread detail and a live subscription, multiplying heap and server load.
70const SIDEBAR_THREAD_PREWARM_LIMIT = 3;
71const SIDEBAR_ROW_SUBSCRIPTION_OVERSCAN_PX = 160;
72​
73export function useSidebarRowSubscriptionLease(isActive: boolean): {
74 readonly leaseLiveStatus: boolean;
75 readonly rowRef: (row: HTMLElement | null) => (() => void) | undefined;
76} {
77 const [isNearViewport, setIsNearViewport] = React.useState(isActive);
78 if (isActive && !isNearViewport) setIsNearViewport(true);
79 const canObserve = typeof IntersectionObserver !== "undefined";
80​
81 return {
82 leaseLiveStatus: isActive || isNearViewport || !canObserve,
83 rowRef: (row) => {
84 if (row === null || isActive || !canObserve) return undefined;
85 // The overscan has to apply to the sidebar's own scroller; a viewport-rooted
86 // margin is still clipped by it.
87 return observeIntersection(row, (entry) => setIsNearViewport(entry.isIntersecting), {
88 root: row.closest('[data-slot="scroll-area-viewport"]'),
89 rootMargin: `${SIDEBAR_ROW_SUBSCRIPTION_OVERSCAN_PX}px 0px`,
90 });
91 },
92 };
94​
95const fileDragClears = new Set<(active: false) => void>();
96function clearFileDrags() {
97 const clears = [...fileDragClears];
98 fileDragClears.clear();
99 for (const clear of clears) clear(false);
101​
102/**
103 * A file drag that ends outside every drop target (Escape, or a drop elsewhere)
104 * sends no dragleave to the row it last entered, so the window's dragend clears it.
105 */
106export function setFileDragActive(setActive: (active: boolean) => void, active: boolean) {
107 setActive(active);
108 if (typeof window === "undefined") return;
109 if (!active) {
110 if (fileDragClears.delete(setActive) && fileDragClears.size === 0) {
111 window.removeEventListener("dragend", clearFileDrags);
112 }
113 return;
114 }
115 if (fileDragClears.size === 0) window.addEventListener("dragend", clearFileDrags, { once: true });
116 fileDragClears.add(setActive);
118​
119/**
120 * A clock that advances exactly when a snooze wake time passes, so a woken
121 * thread leaves the shelf on time without a per-second clock.
122 */
123export function useSnoozeWakeClock(
124 threads: ReadonlyArray<{ readonly snoozedUntil?: string | null | undefined }>,
125): number {
126 const [clockMs, setClockMs] = React.useState(() => Date.now());
127 const wakeTimes: number[] = [];
128 let nextWakeAt: number | null = null;
129 for (const thread of threads) {
130 const wakeAt = thread.snoozedUntil == null ? Number.NaN : Date.parse(thread.snoozedUntil);
131 if (!(wakeAt > clockMs)) continue;
132 wakeTimes.push(wakeAt);
133 if (nextWakeAt === null || wakeAt < nextWakeAt) nextWakeAt = wakeAt;
134 }
135 const woke = useDeadlinePassed(nextWakeAt);
136 // Advancing to the latest wake that has passed skips every wake that elapsed
137 // meanwhile, e.g. across a laptop sleep. Stepping one wake at a time would
138 // re-render once per elapsed wake and hit React's limit.
139 if (woke && nextWakeAt !== null) {
140 let nextClockMs = nextWakeAt;
141 for (const wakeAt of wakeTimes) {
142 if (wakeAt > nextClockMs && deadlineStore(wakeAt).getSnapshot()) nextClockMs = wakeAt;
143 }
144 setClockMs(nextClockMs);
145 return nextClockMs;
146 }
147 return clockMs;
149​
150export function useRetainedValue<T>(key: string | null, value: T | null): T | null {
151 const [retained, setRetained] = React.useState<{
152 readonly key: string;
153 readonly value: T;
154 } | null>(null);
155 if (key !== null && value !== null && (retained?.key !== key || retained.value !== value)) {
156 setRetained({ key, value });
157 }
158 if (value !== null) return value;
159 return key !== null && retained?.key === key ? retained.value : null;
161​
162// Sortable owns drag transforms; replaying committed order would animate drops twice.
163export const animateSidebarLayoutChanges: AnimateLayoutChanges = (args) =>
164 args.isSorting ? defaultAnimateLayoutChanges(args) : false;
165​
166// Snoozed rows cannot accept drops without a wake time. Working rows only drag out as chat context.
167​
168export type SidebarSection = "pinned" | "active" | "working" | "snoozed" | "settled";
169​
170export function resolveSidebarThreadSection(input: {
171 readonly snoozed: boolean;
172 readonly settled: boolean;
173 readonly pinned: boolean;
174}): SidebarSection {
175 if (input.snoozed) return "snoozed";
176 if (input.settled) return "settled";
177 if (input.pinned) return "pinned";
178 return "active";
180​
181const SIDEBAR_MARKER_PREFIX = "sidebar-marker-";
182​
183export type SidebarListMarker =
184 | "pinned-header"
185 | "active-placeholder"
186 | "settled-placeholder"
187 | "pinned-divider"
188 | "working-header"
189 | "snoozed-header"
190 | "settled-header";
191​
192export function sidebarMarkerId(marker: SidebarListMarker): string {
193 return `${SIDEBAR_MARKER_PREFIX}${marker}`;
195​
196export type SidebarListItem =
197 | { readonly kind: "thread"; readonly key: string; readonly section: SidebarSection }
198 | { readonly kind: "marker"; readonly marker: SidebarListMarker };
199​
200export function sidebarListItemId(item: SidebarListItem): string {
201 return item.kind === "thread" ? item.key : sidebarMarkerId(item.marker);
203​
204function sectionAtSidebarSlot(items: readonly SidebarListItem[], index: number): SidebarSection {
205 let section: SidebarSection = "pinned";
206 for (let i = 0; i < index && i < items.length; i += 1) {
207 const item = items[i]!;
208 if (item.kind !== "marker") continue;
209 if (item.marker === "pinned-divider") section = "active";
210 else if (item.marker === "working-header") section = "working";
211 else if (item.marker === "snoozed-header") section = "snoozed";
212 else if (item.marker === "settled-header") section = "settled";
213 }
214 return section;
216​
217export type SidebarDropTarget = {
218 readonly section: "pinned" | "active" | "settled";
219 readonly pinnedOrder: readonly string[];
220 readonly activeOrder: readonly string[];
221};
222​
223export function resolveSidebarDropTarget(
224 items: readonly SidebarListItem[],
225 activeKey: string,
226 overId: string,
227): SidebarDropTarget | null {
228 const activeIndex = items.findIndex((item) => sidebarListItemId(item) === activeKey);
229 const overIndex = items.findIndex((item) => sidebarListItemId(item) === overId);
230 if (activeIndex === -1 || overIndex === -1 || items[activeIndex]?.kind !== "thread") return null;
231 const moved = items.filter((_, index) => index !== activeIndex);
232 moved.splice(overIndex, 0, items[activeIndex]!);
233 const section = sectionAtSidebarSlot(moved, overIndex);
234 if (section === "working" || section === "snoozed") return null;
235 const pinnedOrder: string[] = [];
236 const activeOrder: string[] = [];
237 let currentSection: SidebarSection = "pinned";
238 for (const item of moved) {
239 if (item.kind === "marker") {
240 if (item.marker === "pinned-divider") currentSection = "active";
241 else if (
242 item.marker === "working-header" ||
243 item.marker === "snoozed-header" ||
244 item.marker === "settled-header"
245 )
246 break;
247 } else if (currentSection === "pinned") pinnedOrder.push(item.key);
248 else activeOrder.push(item.key);
249 }
250 return { section, pinnedOrder, activeOrder };
252​
253export type SidebarThreadDropPlan =
254 | { readonly kind: "none" }
255 | {
256 readonly kind: "reorder-pinned";
257 readonly order: readonly string[];
258 readonly assignments: ReadonlyArray<{ readonly id: string; readonly orderKey: string }>;
259 }
260 | {
261 readonly kind: "pin";
262 readonly order: readonly string[];
263 readonly orderKey: string | undefined;
264 readonly extraAssignments: ReadonlyArray<{ readonly id: string; readonly orderKey: string }>;
265 }
266 | {
267 readonly kind: "move-active";
268 readonly order: readonly string[] | null;
269 readonly assignments: ReadonlyArray<{ readonly id: string; readonly orderKey: string }>;
270 readonly unpin: boolean;
271 readonly unsettle: boolean;
272 readonly unsnooze: boolean;
273 }
274 | { readonly kind: "settle" };
275​
276export type SidebarDropVerb = "pin" | "unpin" | "settle" | "unsettle" | "wake";
277​
278export function resolveSidebarDropVerb(
279 from: SidebarSection,
280 to: SidebarSection | null,
281): SidebarDropVerb | null {
282 if (to === null || to === from || to === "working" || to === "snoozed") return null;
283 if (to === "pinned") return "pin";
284 if (to === "settled") return "settle";
285 if (from === "pinned") return "unpin";
286 if (from === "settled") return "unsettle";
287 return "wake";
289​
290export function resolveSidebarSweepKeys(
291 orderedKeys: readonly string[],
292 originKey: string,
293 targetKey: string,
294 canApply: (key: string) => boolean,
295): string[] {
296 const origin = orderedKeys.indexOf(originKey);
297 const target = orderedKeys.indexOf(targetKey);
298 if (origin === -1 || target === -1) return [];
299 return orderedKeys.slice(Math.min(origin, target), Math.max(origin, target) + 1).filter(canApply);
301​
302export function sidebarThreadKeyAtY(list: HTMLElement, y: number): string | null {
303 const viewport = list.closest('[data-slot="scroll-area-viewport"]')?.getBoundingClientRect();
304 const visibleY = viewport ? Math.min(Math.max(y, viewport.top), viewport.bottom - 1) : y;
305 let key: string | null = null;
306 for (const row of list.querySelectorAll<HTMLElement>("li[data-thread-item]")) {
307 if (key !== null && row.getBoundingClientRect().top > visibleY) break;
308 key = row.dataset.threadItem ?? null;
309 }
310 return key;
312​
313export function planSidebarThreadDrop(input: {
314 readonly activeKey: string;
315 readonly activeSection: SidebarSection;
316 readonly activePinned?: boolean;
317 readonly activeSettled?: boolean;
318 readonly supportsSettlement?: boolean;
319 readonly target: SidebarDropTarget;
320 readonly pinnedOrder: readonly string[];
321 readonly pinnedKeysById: ReadonlyMap<string, string | null | undefined>;
322 readonly reorderableKeys?: ReadonlySet<string>;
323 readonly activeOrder: readonly string[];
324 readonly activeKeysById: ReadonlyMap<string, string | null | undefined>;
325 readonly activeReorderableKeys?: ReadonlySet<string>;
326 readonly activeTimeOrdered?: boolean;
327}): SidebarThreadDropPlan {
328 const {
329 activeKey,
330 activeSection,
331 activePinned = activeSection === "pinned",
332 activeSettled = activeSection === "settled",
333 target,
334 pinnedOrder,
335 pinnedKeysById,
336 reorderableKeys,
337 activeOrder,
338 activeKeysById,
339 activeReorderableKeys,
340 } = input;
341 if (activeSection === "working") return { kind: "none" };
342 if (input.supportsSettlement === false && (target.section === "settled" || activeSettled)) {
343 return { kind: "none" };
344 }
345 const arrange = (
346 order: readonly string[],
347 keysById: ReadonlyMap<string, string | null | undefined>,
348 writable: ReadonlySet<string> | undefined,
349 ) => {
350 if (!writable) return planPinnedReorder({ orderedIds: order, keysById, movedId: activeKey });
351 if (!writable.has(activeKey)) return null;
352 const assignments = planPinnedReorder({
353 orderedIds: order.filter((key) => writable.has(key) || keysById.get(key) != null),
354 keysById,
355 movedId: activeKey,
356 });
357 return assignments.every(({ id }) => writable.has(id)) ? assignments : null;
358 };
359 switch (target.section) {
360 case "active": {
361 if (input.activeTimeOrdered) {
362 return activeSection === "active"
363 ? { kind: "none" }
364 : {
365 kind: "move-active",
366 order: null,
367 assignments: [],
368 unpin: activePinned,
369 unsettle: activeSettled,
370 unsnooze: activeSection === "snoozed",
371 };
372 }
373 const order = target.activeOrder;
374 if (
375 activeSection === "active" &&
376 order.length === activeOrder.length &&
377 order.every((key, index) => key === activeOrder[index])
378 ) {
379 return { kind: "none" };
380 }
381 const assignments = arrange(order, activeKeysById, activeReorderableKeys);
382 if (assignments === null) return { kind: "none" };
383 return {
384 kind: "move-active",
385 order,
386 assignments,
387 unpin: activePinned,
388 unsettle: activeSettled,
389 unsnooze: activeSection === "snoozed",
390 };
391 }
392 case "settled":
393 return activeSection === "settled" ? { kind: "none" } : { kind: "settle" };
394 case "pinned": {
395 const order = target.pinnedOrder;
396 if (
397 activeSection === "pinned" &&
398 order.length === pinnedOrder.length &&
399 order.every((key, index) => key === pinnedOrder[index])
400 ) {
401 return { kind: "none" };
402 }
403 const assignments = arrange(order, pinnedKeysById, reorderableKeys);
404 if (assignments === null) return { kind: "none" };
405 if (activeSection === "pinned") {
406 return assignments.length === 0
407 ? { kind: "none" }
408 : { kind: "reorder-pinned", order, assignments };
409 }
410 return {
411 kind: "pin",
412 order,
413 orderKey: assignments.find((assignment) => assignment.id === activeKey)?.orderKey,
414 extraAssignments: activePinned
415 ? assignments
416 : assignments.filter((assignment) => assignment.id !== activeKey),
417 };
418 }
419 }
421​
422export function applySidebarThreadDrop<
423 T extends Pick<
424 SidebarThreadSummary,
425 | "pinnedAt"
426 | "pinOrderKey"
427 | "activeOrderKey"
428 | "snoozedAt"
429 | "snoozedUntil"
430 | "settledAt"
431 | "settledOverride"
432 | "unsettledAt"
433 >,
434>(thread: T, section: "pinned" | "active" | "settled", now: string, orderKey?: string): T {
435 const wasSettled = thread.settledOverride === "settled";
436 const awake = { ...thread, snoozedAt: null, snoozedUntil: null };
437 if (section === "settled") {
438 return {
439 ...awake,
440 pinnedAt: null,
441 pinOrderKey: null,
442 activeOrderKey: null,
443 settledOverride: "settled",
444 settledAt: wasSettled ? (thread.settledAt ?? now) : now,
445 unsettledAt: null,
446 };
447 }
448 const resumed = wasSettled
449 ? { ...awake, settledOverride: "active" as const, settledAt: null, unsettledAt: now }
450 : awake;
451 return {
452 ...resumed,
453 pinnedAt: section === "pinned" ? (thread.pinnedAt ?? now) : null,
454 pinOrderKey: section === "pinned" ? (orderKey ?? thread.pinOrderKey) : null,
455 ...(section === "active" && orderKey !== undefined ? { activeOrderKey: orderKey } : {}),
456 };
458​
459type SidebarProject = {
460 id: string;
461 title: string;
462 createdAt?: string | undefined;
463 updatedAt?: string | undefined;
464};
465​
466type ScopedSidebarProject = SidebarProject & {
467 environmentId: string;
468};
469​
470type ScopedSidebarThread = ThreadSortInput & {
471 environmentId: string;
472 projectId: string;
473 archivedAt: string | null;
474};
475​
476type LogicalSidebarProject = SidebarProject & {
477 projectKey: string;
478 memberProjectRefs: readonly {
479 environmentId: string;
480 projectId: string;
481 }[];
482};
483​
484export type ThreadTraversalDirection = "previous" | "next";
485​
486/** Exclude only successful deletions from shared-worktree checks. */
487export async function deleteSelectedThreadEntries<
488 TEntry extends { readonly threadKey: string },
489>(input: {
490 entries: readonly TEntry[];
491 delete: (
492 entry: TEntry,
493 deletedThreadKeys: ReadonlySet<string>,
494 ) => Promise<AtomCommandResult<unknown, unknown> | null>;
495}) {
496 const deletedThreadKeys = new Set<string>();
497 let firstFailure: AsyncResult.Failure<unknown, unknown> | null = null;
498​
499 for (const entry of input.entries) {
500 const result = await input.delete(entry, deletedThreadKeys);
501 if (result === null) continue;
502 if (result._tag === "Failure") {
503 if (isAtomCommandInterrupted(result)) break;
504 firstFailure ??= result;
505 continue;
506 }
507 deletedThreadKeys.add(entry.threadKey);
508 }
509​
510 return { deletedThreadKeys, firstFailure };
512​
513export async function archiveSelectedThreadEntries<
514 TEntry extends { readonly threadKey: string },
515 TResult extends { readonly _tag: "Success" | "Failure" },
516>(input: {
517 entries: readonly TEntry[];
518 archive: (entry: TEntry, onArchived: () => void) => Promise<TResult>;
519}): Promise<{
520 archivedThreadKeys: readonly string[];
521 mutationFailure: Extract<TResult, { readonly _tag: "Failure" }> | null;
522 followupFailures: readonly Extract<TResult, { readonly _tag: "Failure" }>[];
523}> {
524 const archivedThreadKeys: string[] = [];
525 const followupFailures: Extract<TResult, { readonly _tag: "Failure" }>[] = [];
526​
527 for (const entry of input.entries) {
528 let didArchive = false;
529 const result = await input.archive(entry, () => {
530 didArchive = true;
531 });
532 if (didArchive || result._tag === "Success") archivedThreadKeys.push(entry.threadKey);
533 if (result._tag === "Success") continue;
534 const failure = result as Extract<TResult, { readonly _tag: "Failure" }>;
535 if (didArchive) {
536 followupFailures.push(failure);
537 continue;
538 }
539 return { archivedThreadKeys, mutationFailure: failure, followupFailures };
540 }
541​
542 return { archivedThreadKeys, mutationFailure: null, followupFailures };
544​
545export function buildMultiSelectThreadContextMenuItems(input: {
546 count: number;
547 hasRunningThread: boolean;
548}): readonly ContextMenuItem<"mark-unread" | "archive" | "delete">[] {
549 return [
550 { id: "mark-unread", label: `Mark unread (${input.count})` },
551 {
552 id: "archive",
553 label: `Archive (${input.count})`,
554 disabled: input.hasRunningThread,
555 },
556 { id: "delete", label: `Delete (${input.count})`, destructive: true },
557 ];
559​
560export function isSidebarSubagentThread(thread: Pick<SidebarThreadSummary, "lineage">): boolean {
561 return thread.lineage.relationshipToParent === "subagent";
563​
564// Subagent threads have no sidebar row, so an open subagent is represented by
565// its nearest non-subagent ancestor. A broken chain (missing parent, cycle,
566// other environment) resolves to the thread itself, which then matches no row.
567export function resolveSidebarRowThreadId(
568 threadId: ThreadId,
569 environmentId: EnvironmentId,
570 threads: readonly Pick<SidebarThreadSummary, "id" | "environmentId" | "lineage">[],
571): ThreadId {
572 const findThread = (id: ThreadId) =>
573 threads.find((thread) => thread.id === id && thread.environmentId === environmentId);
574 const visited = new Set<ThreadId>();
575 let thread = findThread(threadId);
576 while (thread !== undefined && isSidebarSubagentThread(thread)) {
577 if (thread.lineage.parentThreadId === null || visited.has(thread.id)) return threadId;
578 visited.add(thread.id);
579 thread = findThread(thread.lineage.parentThreadId);
580 }
581 return thread?.id ?? threadId;
583​
584/**
585 * `delegatedUnderParent` holds the tasks linked environments run for a thread
586 * the sidebar lists, by thread key; they show under that thread, as subagents do.
587 */
588export function filterSidebarV2VisibleThreads<
589 T extends Pick<SidebarThreadSummary, "archivedAt" | "environmentId" | "id" | "lineage"> & {
590 projectId: string;
591 },
592>(
593 threads: readonly T[],
594 scopedProjectKeys: ReadonlySet<string> | null,
595 delegatedUnderParent: ReadonlySet<string>,
596): T[] {
597 return threads.filter(
598 (thread) =>
599 thread.archivedAt === null &&
600 !isShownUnderParent(
601 { environmentId: thread.environmentId, threadId: thread.id },
602 thread.lineage,
603 delegatedUnderParent,
604 ) &&
605 (scopedProjectKeys === null ||
606 scopedProjectKeys.has(`${thread.environmentId}:${thread.projectId}`)),
607 );
609​
610export function buildBulkTitleRegenerationContextMenuItem(input: {
611 supportedCount: number;
612 actionableCount: number;
613}): ContextMenuItem<"regenerate-title"> | null {
614 if (input.supportedCount === 0) return null;
615 if (input.actionableCount === 0) {
616 return {
617 id: "regenerate-title",
618 label: `Regenerating… (${input.supportedCount})`,
619 disabled: true,
620 };
621 }
622 return {
623 id: "regenerate-title",
624 label: `Regenerate titles (${input.actionableCount})`,
625 };
627​
628export function buildBulkUnpinContextMenuItem(input: {
629 pinnedCount: number;
630}): ContextMenuItem<"unpin"> | null {
631 if (input.pinnedCount === 0) return null;
632 return { id: "unpin", label: `Unpin (${input.pinnedCount})` };
634​
635export interface ThreadStatusPill {
636 label:
637 | "Working"
638 | "Connecting"
639 | "Completed"
640 | "Failed"
641 | "Pending Approval"
642 | "Awaiting Input"
643 | "Guest Request"
644 | "Waiting"
645 | "Plan Ready";
646 colorClass: string;
647 dotClass: string;
648 pulse: boolean;
650​
651const THREAD_STATUS_PRIORITY: Record<ThreadStatusPill["label"], number> = {
652 "Pending Approval": 5,
653 "Awaiting Input": 4,
654 "Guest Request": 3.75,
655 Failed: 3.5,
656 Working: 3,
657 Connecting: 3,
658 Waiting: 2.5,
659 "Plan Ready": 2,
660 Completed: 1,
661};
662​
663type ThreadStatusInput = Pick<
664 SidebarThreadSummary,
665 | "hasActionableProposedPlan"
666 | "hasPendingApprovals"
667 | "hasPendingUserInput"
668 | "pendingSubagentRequest"
669 | "pendingGuestMessageCount"
670 | "interactionMode"
671 | "latestRun"
672 | "runtime"
673> & {
674 lastVisitedAt?: string | null | undefined;
675 pendingBackgroundTasks?: SidebarThreadSummary["pendingBackgroundTasks"] | undefined;
676 blockedOnThreadWait?: boolean | undefined;
677};
678​
679/**
680 * Thread jump hints appear once the jump modifier has been held for a moment,
681 * so a quick shortcut never flashes them, and hide as soon as it is released.
682 */
683export function useThreadJumpHintsVisible(shouldShow: boolean): boolean {
684 const [showAt, setShowAt] = React.useState<number | null>(null);
685 // The clock is read inside the updater: the compiler caches a bare clock read
686 // in render once per instance, so a second hold would reuse the first deadline.
687 // React discards this render and re-runs with the update.
688 if (shouldShow !== (showAt !== null)) {
689 setShowAt(shouldShow ? () => deadlineAfter(THREAD_JUMP_HINT_SHOW_DELAY_MS) : null);
690 }
691 return useDeadlinePassed(showAt);
693​
694export function resolveThreadLastVisitedAt(
695 serverLastVisitedAt: string | null | undefined,
696 localLastVisitedAt: string | undefined,
697): string | undefined {
698 // Server visits override local watermarks, including mark-unread rewinds; use local values only on older
699 // servers.
700 if (serverLastVisitedAt === undefined) return localLastVisitedAt;
701 return serverLastVisitedAt ?? undefined;
703​
704export function hasUnseenCompletion(thread: ThreadStatusInput): boolean {
705 if (!thread.latestRun?.completedAt) return false;
706 const completedAt = Date.parse(thread.latestRun.completedAt);
707 if (Number.isNaN(completedAt)) return false;
708 if (!thread.lastVisitedAt) return false;
709​
710 const lastVisitedAt = Date.parse(thread.lastVisitedAt);
711 if (Number.isNaN(lastVisitedAt)) return true;
712 return completedAt > lastVisitedAt;
714​
715/** Unopened threads' failures still count as unseen, unlike completions. */
716function hasUnseenFailure(thread: ThreadStatusInput): boolean {
717 if (thread.latestRun?.status !== "failed") return false;
718 if (!thread.lastVisitedAt) return true;
719 const completedAt = Date.parse(thread.latestRun.completedAt ?? "");
720 const lastVisitedAt = Date.parse(thread.lastVisitedAt);
721 if (Number.isNaN(completedAt) || Number.isNaN(lastVisitedAt)) return true;
722 return completedAt > lastVisitedAt;
724​
725export function shouldClearThreadSelectionOnMouseDown(target: HTMLElement | null): boolean {
726 if (target === null) return true;
727 return !target.closest(THREAD_SELECTION_SAFE_SELECTOR);
729​
730// Suppress trailing double-click navigation; keyboard and synthetic clicks use detail 0.
731export function isTrailingDoubleClick(detail: number): boolean {
732 return detail > 1;
734​
735function nodeClosest(node: object | null, selector: string): unknown {
736 if (node === null || !("closest" in node) || typeof node.closest !== "function") return null;
737 return node.closest(selector);
739​
740export function isSidebarNestedLinkClick(target: EventTarget | null): boolean {
741 if (target == null || typeof target !== "object") return false;
742 if (nodeClosest(target, "a[href]") !== null) return true;
743 const parent =
744 "parentElement" in target &&
745 target.parentElement !== null &&
746 typeof target.parentElement === "object"
747 ? target.parentElement
748 : null;
749 return nodeClosest(parent, "a[href]") !== null;
751​
752export function shouldCreateNewThreadInCurrentProject(
753 shiftKey: boolean,
754 projectGroupCount: number,
755): boolean {
756 return shiftKey || projectGroupCount <= 1;
758​
759export function orderItemsByPreferredIds<TItem, TId>(input: {
760 items: readonly TItem[];
761 preferredIds: readonly TId[];
762 getId: (item: TItem) => TId;
763 getPreferenceIds?: (item: TItem) => readonly TId[];
764}): TItem[] {
765 const { getId, getPreferenceIds, items, preferredIds } = input;
766 if (preferredIds.length === 0) {
767 return [...items];
768 }
769​
770 const indexesByPreferenceId = new Map<TId, number[]>();
771 for (const [index, item] of items.entries()) {
772 const preferenceIds = getPreferenceIds?.(item) ?? [getId(item)];
773 for (const preferenceId of new Set(preferenceIds)) {
774 const indexes = indexesByPreferenceId.get(preferenceId);
775 if (indexes) {
776 indexes.push(index);
777 } else {
778 indexesByPreferenceId.set(preferenceId, [index]);
779 }
780 }
781 }
782​
783 const emittedIndexes = new Set<number>();
784 const ordered = preferredIds.flatMap((id) => {
785 const index = indexesByPreferenceId
786 .get(id)
787 ?.find((candidate) => !emittedIndexes.has(candidate));
788 if (index === undefined) {
789 return [];
790 }
791 emittedIndexes.add(index);
792 return [items[index]!];
793 });
794 const remaining = items.filter((_, index) => !emittedIndexes.has(index));
795 return [...ordered, ...remaining];
797​
798export function getSidebarThreadIdsToPrewarm<TThreadId>(
799 visibleThreadIds: readonly TThreadId[],
800 limit = SIDEBAR_THREAD_PREWARM_LIMIT,
801): TThreadId[] {
802 return visibleThreadIds.slice(0, Math.max(0, limit));
804​
805export function resolveAdjacentThreadId<T>(input: {
806 threadIds: readonly T[];
807 currentThreadId: T | null;
808 direction: ThreadTraversalDirection;
809}): T | null {
810 const { currentThreadId, direction, threadIds } = input;
811​
812 if (threadIds.length === 0) {
813 return null;
814 }
815​
816 if (currentThreadId === null) {
817 return direction === "previous" ? (threadIds.at(-1) ?? null) : (threadIds[0] ?? null);
818 }
819​
820 const currentIndex = threadIds.indexOf(currentThreadId);
821 if (currentIndex === -1) {
822 return null;
823 }
824​
825 if (direction === "previous") {
826 return currentIndex > 0 ? (threadIds[currentIndex - 1] ?? null) : null;
827 }
828​
829 return currentIndex < threadIds.length - 1 ? (threadIds[currentIndex + 1] ?? null) : null;
831​
832export function isContextMenuPointerDown(input: {
833 button: number;
834 ctrlKey: boolean;
835 isMac: boolean;
836}): boolean {
837 if (input.button === 2) return true;
838 return input.isMac && input.button === 0 && input.ctrlKey;
840​
841export type SidebarThreadStatus =
842 | "approval"
843 | "input"
844 | "request"
845 | "working"
846 | "waiting"
847 | "failed"
848 | "limited"
849 | "ready";
850​
851export function shouldRecedeSidebarThread(input: {
852 status: SidebarThreadStatus;
853 isUnread: boolean;
854 isWoke: boolean;
855 isActive: boolean;
856 isSelected: boolean;
857}): boolean {
858 if (
859 input.isActive ||
860 input.isSelected ||
861 input.status === "input" ||
862 input.status === "request"
863 ) {
864 return false;
865 }
866 if (input.status === "working" || input.status === "waiting") return true;
867 if (input.status === "ready" || input.status === "approval") {
868 return !input.isUnread && !input.isWoke;
869 }
870 return false;
872​
873type SidebarThreadStatusInput = Pick<
874 SidebarThreadSummary,
875 | "hasPendingApprovals"
876 | "hasPendingUserInput"
877 | "pendingSubagentRequest"
878 | "pendingGuestMessageCount"
879 | "runtime"
880 | "blockedOnThreadWait"
881>;
882​
883export function resolveSidebarThreadStatus(thread: SidebarThreadStatusInput): SidebarThreadStatus {
884 if (thread.hasPendingApprovals || thread.pendingSubagentRequest === "approval") {
885 return "approval";
886 }
887 if (thread.hasPendingUserInput || thread.pendingSubagentRequest === "user_input") {
888 return "input";
889 }
890 // A guest is waiting on the owner; the agent's own requests come first.
891 if ((thread.pendingGuestMessageCount ?? 0) > 0) {
892 return "request";
893 }
894 if (thread.runtime?.status === "running" && thread.blockedOnThreadWait === true) {
895 return "waiting";
896 }
897 if (
898 thread.runtime !== null &&
899 ["preparing", "queued", "starting", "running", "waiting"].includes(thread.runtime.status)
900 ) {
901 return "working";
902 }
903 if (thread.runtime?.status === "idle") {
904 return "waiting";
905 }
906 if (thread.runtime?.status === "failed") {
907 return thread.runtime.lastErrorClass === "usage_limit" ? "limited" : "failed";
908 }
909 return "ready";
911​
912export type SidebarV2TopStatusKind =
913 | "approval"
914 | "done"
915 | "failed"
916 | "limited"
917 | "input"
918 | "request"
919 | "waiting"
920 | "woke"
921 | "working";
922​
923export function resolveSidebarV2TopStatus(input: {
924 readonly status: SidebarThreadStatus;
925 readonly isUnread: boolean;
926 readonly isWoke: boolean;
927}): SidebarV2TopStatusKind | null {
928 if (input.status === "working") {
929 return "working";
930 }
931 if (input.status === "waiting") {
932 return "waiting";
933 }
934 if (input.status === "approval") {
935 return "approval";
936 }
937 if (input.status === "input" || input.status === "request") {
938 return input.status;
939 }
940 if (input.status === "failed" || input.status === "limited") {
941 return input.status;
942 }
943 if (input.isWoke) {
944 return "woke";
945 }
946 return input.isUnread ? "done" : null;
948​
949export function firstValidTimestampMs(
950 ...candidates: ReadonlyArray<string | null | undefined>
951): number {
952 for (const candidate of candidates) {
953 if (candidate == null) continue;
954 const parsed = Date.parse(candidate);
955 if (!Number.isNaN(parsed)) return parsed;
956 }
957 return 0;
959​
960export { sortActiveThreadsByOrderKey as sortThreadsForSidebar } from "@t3tools/client-runtime/state/thread-sort";
961export {
962 isThreadWorking as isSidebarThreadWorking,
963 sortInboxThreadsByReturn,
964 sortWorkingThreadsBySend,
965} from "@t3tools/client-runtime/state/thread-inbox";
966​
967export { pinOrderKeyBetween } from "@t3tools/client-runtime/state/thread-sort";
968export { sortPinnedThreadsByOrderKey as sortPinnedThreadsForSidebar } from "@t3tools/client-runtime/state/thread-sort";
969​
970const EMPTY_CONTENT_MATCH_KEYS: ReadonlySet<string> = new Set<string>();
971​
972/**
973 * Sidebar search results: title, branch, and pull request matches ranked as
974 * the command palette ranks them, then threads listed only because their
975 * messages match, in `contentMatchKeys` order.
976 */
977export function searchSidebarThreads<
978 T extends ThreadSearchShell & {
979 readonly environmentId: EnvironmentId;
980 readonly id: ThreadId;
981 },
982>(
983 threads: readonly T[],
984 query: string,
985 contentMatchKeys: ReadonlySet<string> = EMPTY_CONTENT_MATCH_KEYS,
986 now = Date.now(),
987): { readonly titleMatches: T[]; readonly contentMatches: T[] } {
988 const normalizedQuery = foldSearchQuery(query);
989 if (normalizedQuery.length === 0) return { titleMatches: [], contentMatches: [] };
990 const titleMatches = rankSearchItems(threads, (thread, options) =>
991 scoreThreadSearch(normalizedQuery, threadSearchSubject(thread, null), now, {
992 ...options,
993 picks: false,
994 }),
995 ).map(({ item }) => item);
996 const listed = new Set(titleMatches);
997 // In the order the server ranked their messages, as the palette lists them.
998 const threadByKey = new Map(
999 threads.map((thread) => [
1000 threadSearchMatchKey({ environmentId: thread.environmentId, threadId: thread.id }),
1001 thread,
1002 ]),
1003 );
1004 const contentMatches = [...contentMatchKeys].flatMap((key) => {
1005 const thread = threadByKey.get(key);
1006 return thread && !listed.has(thread) ? [thread] : [];
1007 });
1008 return { titleMatches, contentMatches };
1010​
1011export function pullRequestMatchesSearchQuery(
1012 pullRequest: Parameters<typeof threadPullRequestSearchTerms>[0],
1013 query: string,
1014): boolean {
1015 const normalizedQuery = normalizeSearchText(query);
1016 if (normalizedQuery.length === 0) return false;
1017 const haystack = normalizeSearchText(threadPullRequestSearchTerms(pullRequest).join(" "));
1018 return normalizedQuery.split(" ").every((token) => haystack.includes(token));
1020​
1021export function filterSidebarProjectScopeItems<TItem extends { readonly value: string }>(input: {
1022 items: readonly TItem[];
1023 query: string;
1024 matches: (item: TItem, query: string) => boolean;
1025}): readonly TItem[] {
1026 const query = input.query.trim();
1027 if (query.length === 0) return input.items;
1028 return input.items.filter((item) => item.value !== "all" && input.matches(item, query));
1030​
1031export interface SidebarProjectScopeMenuState {
1032 readonly open: boolean;
1033 readonly query: string;
1035​
1036export type SidebarProjectScopeMenuAction =
1037 | { readonly type: "query-changed"; readonly query: string }
1038 | { readonly type: "open-changed"; readonly open: boolean }
1039 | { readonly type: "project-settings-opened" };
1040​
1041export function reduceSidebarProjectScopeMenuState(
1042 state: SidebarProjectScopeMenuState,
1043 action: SidebarProjectScopeMenuAction,
1044): SidebarProjectScopeMenuState {
1045 switch (action.type) {
1046 case "query-changed":
1047 return { ...state, query: action.query };
1048 case "open-changed":
1049 return { open: action.open, query: "" };
1050 case "project-settings-opened":
1051 return { open: false, query: "" };
1054​
1055export function resolveWorkingStartedAt(
1056 thread: Pick<SidebarThreadSummary, "latestRun" | "runtime">,
1057): string | null {
1058 return resolveThreadWorkingStartedAt(thread);
1060​
1061export function resolveThreadStatusPill(input: {
1062 thread: ThreadStatusInput;
1063}): ThreadStatusPill | null {
1064 const { thread } = input;
1065​
1066 if (thread.hasPendingApprovals || thread.pendingSubagentRequest === "approval") {
1067 return {
1068 label: "Pending Approval",
1069 colorClass: "text-amber-600 dark:text-amber-300/90",
1070 dotClass: "bg-amber-500 dark:bg-amber-300/90",
1071 pulse: false,
1072 };
1074​
1075 if (thread.hasPendingUserInput || thread.pendingSubagentRequest === "user_input") {
1076 return {
1077 label: "Awaiting Input",
1078 colorClass: "text-indigo-600 dark:text-indigo-300/90",
1079 dotClass: "bg-indigo-500 dark:bg-indigo-300/90",
1080 pulse: false,
1081 };
1083​
1084 if ((thread.pendingGuestMessageCount ?? 0) > 0) {
1085 return {
1086 label: "Guest Request",
1087 colorClass: "text-guest-foreground",
1088 dotClass: "bg-guest",
1089 pulse: false,
1090 };
1092​
1093 if (
1094 (thread.runtime?.status === "running" && thread.blockedOnThreadWait !== true) ||
1095 thread.runtime?.status === "waiting"
1096 ) {
1097 return {
1098 label: "Working",
1099 colorClass: "text-sky-600 dark:text-sky-300/80",
1100 dotClass: "bg-sky-500 dark:bg-sky-300/80",
1101 pulse: true,
1102 };
1104​
1105 if (
1106 thread.runtime?.status === "preparing" ||
1107 thread.runtime?.status === "starting" ||
1108 thread.runtime?.status === "queued"
1109 ) {
1110 return {
1111 label: "Connecting",
1112 colorClass: "text-sky-600 dark:text-sky-300/80",
1113 dotClass: "bg-sky-500 dark:bg-sky-300/80",
1114 pulse: true,
1115 };
1117​
1118 if (
1119 (thread.runtime?.status === "running" && thread.blockedOnThreadWait === true) ||
1120 backgroundWorkHoldsCompletion(thread.pendingBackgroundTasks ?? [])
1121 ) {
1122 return {
1123 label: "Waiting",
1124 colorClass: "text-sidebar-muted-foreground",
1125 dotClass: "bg-sidebar-muted-foreground",
1126 pulse: false,
1127 };
1129​
1130 if (hasUnseenFailure(thread)) {
1131 return {
1132 label: "Failed",
1133 colorClass: "text-red-600 dark:text-red-300/90",
1134 dotClass: "bg-red-500 dark:bg-red-300/90",
1135 pulse: false,
1136 };
1138​
1139 const hasPlanReadyPrompt =
1140 !thread.hasPendingUserInput &&
1141 thread.interactionMode === "plan" &&
1142 isLatestRunSettled(thread.latestRun, thread.runtime) &&
1143 thread.hasActionableProposedPlan;
1144 if (hasPlanReadyPrompt) {
1145 return {
1146 label: "Plan Ready",
1147 colorClass: "text-violet-600 dark:text-violet-300/90",
1148 dotClass: "bg-violet-500 dark:bg-violet-300/90",
1149 pulse: false,
1150 };
1152​
1153 if (hasUnseenCompletion(thread)) {
1154 return {
1155 label: "Completed",
1156 colorClass: "text-emerald-600 dark:text-emerald-300/90",
1157 dotClass: "bg-emerald-500 dark:bg-emerald-300/90",
1158 pulse: false,
1159 };
1161​
1162 return null;
1164​
1165export function resolveProjectStatusIndicator(
1166 statuses: ReadonlyArray<ThreadStatusPill | null>,
1167): ThreadStatusPill | null {
1168 let highestPriorityStatus: ThreadStatusPill | null = null;
1169​
1170 for (const status of statuses) {
1171 if (status === null) continue;
1172 if (
1173 highestPriorityStatus === null ||
1174 THREAD_STATUS_PRIORITY[status.label] > THREAD_STATUS_PRIORITY[highestPriorityStatus.label]
1175 ) {
1176 highestPriorityStatus = status;
1179​
1180 return highestPriorityStatus;
1182​
1183export function getFallbackThreadIdAfterDelete<
1184 T extends Pick<Thread, "id" | "projectId" | "createdAt" | "updatedAt"> & ThreadSortInput,
1185>(input: {
1186 threads: readonly T[];
1187 deletedThreadId: T["id"];
1188 sortOrder: SidebarThreadSortOrder;
1189 deletedThreadIds?: ReadonlySet<T["id"]>;
1190}): T["id"] | null {
1191 const { deletedThreadId, deletedThreadIds, sortOrder, threads } = input;
1192 const deletedThread = threads.find((thread) => thread.id === deletedThreadId);
1193 if (!deletedThread) {
1194 return null;
1196​
1197 return (
1198 sortThreads(
1199 threads.filter(
1200 (thread) =>
1201 thread.projectId === deletedThread.projectId &&
1202 thread.id !== deletedThreadId &&
1203 !deletedThreadIds?.has(thread.id),
1204 ),
1205 sortOrder,
1206 )[0]?.id ?? null
1207 );
1209function getProjectSortTimestamp(
1210 project: SidebarProject,
1211 projectThreads: readonly ThreadSortInput[],
1212 sortOrder: Exclude<SidebarProjectSortOrder, "manual">,
1213): number {
1214 if (projectThreads.length > 0) {
1215 return projectThreads.reduce(
1216 (latest, thread) => Math.max(latest, getThreadSortTimestamp(thread, sortOrder)),
1217 Number.NEGATIVE_INFINITY,
1218 );
1220​
1221 if (sortOrder === "created_at") {
1222 return toSortableTimestamp(project.createdAt) ?? Number.NEGATIVE_INFINITY;
1224 return toSortableTimestamp(project.updatedAt ?? project.createdAt) ?? Number.NEGATIVE_INFINITY;
1226​
1227function sortProjectsByActivity<TProject extends SidebarProject>(
1228 projects: readonly TProject[],
1229 sortOrder: SidebarProjectSortOrder,
1230 getProjectThreads: (project: TProject) => readonly ThreadSortInput[],
1231 compareTies: (left: TProject, right: TProject) => number,
1232): TProject[] {
1233 if (sortOrder === "manual") {
1234 return [...projects];
1236​
1237 // Project timestamps scan all threads; compute once per project instead of per comparison.
1238 return projects
1239 .map((project) => ({
1240 project,
1241 timestamp: getProjectSortTimestamp(project, getProjectThreads(project), sortOrder),
1242 }))
1243 .sort((left, right) => {
1244 const byTimestamp =
1245 right.timestamp === left.timestamp ? 0 : right.timestamp > left.timestamp ? 1 : -1;
1246 return byTimestamp || compareTies(left.project, right.project);
1247 })
1248 .map(({ project }) => project);
1250​
1251export function sortProjectsForSidebar<
1252 TProject extends SidebarProject,
1253 TThread extends Pick<Thread, "projectId" | "createdAt" | "updatedAt"> & ThreadSortInput,
1255 projects: readonly TProject[],
1256 threads: readonly TThread[],
1257 sortOrder: SidebarProjectSortOrder,
1258): TProject[] {
1259 const threadsByProjectId = new Map<string, TThread[]>();
1260 for (const thread of threads) {
1261 const existing = threadsByProjectId.get(thread.projectId) ?? [];
1262 existing.push(thread);
1263 threadsByProjectId.set(thread.projectId, existing);
1265​
1266 return sortProjectsByActivity(
1267 projects,
1268 sortOrder,
1269 (project) => threadsByProjectId.get(project.id) ?? [],
1270 (left, right) => left.title.localeCompare(right.title) || left.id.localeCompare(right.id),
1271 );
1273​
1274export function sortLogicalProjectsForSidebar<
1275 TProject extends LogicalSidebarProject,
1276 TThread extends ScopedSidebarThread,
1278 projects: readonly TProject[],
1279 threads: readonly TThread[],
1280 sortOrder: SidebarProjectSortOrder,
1281): TProject[] {
1282 const groupKeyByProjectRef = new Map(
1283 projects.flatMap((project) =>
1284 project.memberProjectRefs.map(
1285 (projectRef) =>
1286 [`${projectRef.environmentId}\0${projectRef.projectId}`, project.projectKey] as const,
1287 ),
1288 ),
1289 );
1290 const threadsByProjectKey = new Map<string, TThread[]>();
1291 for (const thread of threads) {
1292 if (thread.archivedAt !== null) continue;
1293 const projectKey = groupKeyByProjectRef.get(`${thread.environmentId}\0${thread.projectId}`);
1294 if (!projectKey) continue;
1295 const existing = threadsByProjectKey.get(projectKey);
1296 if (existing) {
1297 existing.push(thread);
1298 } else {
1299 threadsByProjectKey.set(projectKey, [thread]);
1302​
1303 return sortProjectsByActivity(
1304 projects,
1305 sortOrder,
1306 (project) => threadsByProjectKey.get(project.projectKey) ?? [],
1307 (left, right) =>
1308 left.title.localeCompare(right.title) || left.projectKey.localeCompare(right.projectKey),
1309 );
1311​
1312export function sortSidebarV2ProjectGroups<
1313 TProject extends LogicalSidebarProject,
1314 TThread extends ScopedSidebarThread &
1315 Pick<SidebarThreadSummary, "environmentId" | "id" | "lineage">,
1317 projects: readonly TProject[],
1318 threads: readonly TThread[],
1319 sortOrder: SidebarProjectSortOrder,
1320 delegatedUnderParent: ReadonlySet<string>,
1321): TProject[] {
1322 return sortLogicalProjectsForSidebar(
1323 projects,
1324 filterSidebarV2VisibleThreads(threads, null, delegatedUnderParent),
1325 sortOrder,
1326 );
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 );