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

Sidebar.logic.ts

1,450 lines47.9 KB

1import type { EnvironmentServerConfig } from "@t3tools/client-runtime/connection";
2import { scopeThreadRef, scopedThreadKey } from "@t3tools/client-runtime/environment";
3import { resolveThreadWorkingStartedAt } from "@t3tools/client-runtime/state/models";
4import { isShownUnderParent } from "@t3tools/client-runtime/state/threads";
5import { backgroundWorkHoldsCompletion } from "@t3tools/shared/orchestrationV2PendingBackgroundWork";
6import { threadPullRequestSearchTerms } from "@t3tools/shared/threadPullRequests";
7import * as React from "react";
8import {
9 isAtomCommandInterrupted,
10 type AtomCommandResult,
11} from "@t3tools/client-runtime/state/runtime";
12import { defaultAnimateLayoutChanges, type AnimateLayoutChanges } from "@dnd-kit/sortable";
13import {
14 threadSearchMatchKey,
15 threadSearchSubject,
16 type ThreadSearchShell,
17} from "@t3tools/client-runtime/state/thread-search";
18import { foldSearchQuery, rankSearchItems, scoreThreadSearch } from "@t3tools/shared/paletteSearch";
19import {
20 isListedThreadLineage,
21 type ContextMenuItem,
22 type EnvironmentId,
23 type ResolvedKeybindingsConfig,
24 type ScopedThreadRef,
25 type ThreadId,
26} from "@t3tools/contracts";
27import type { SidebarProjectSortOrder, SidebarThreadSortOrder } from "@t3tools/contracts/settings";
28import type { AsyncResult } from "effect/reactivity";
29import {
30 effectiveSnoozed,
31 type ThreadSnoozeShell,
32} from "@t3tools/client-runtime/state/thread-settled";
33import {
34 getThreadSortTimestamp,
35 planPinnedReorder,
36 sortThreads,
37 toSortableTimestamp,
38 type ThreadSortInput,
39} from "@t3tools/client-runtime/state/thread-sort";
40import type { SidebarThreadSummary, Thread } from "../types";
41import { normalizeSearchText } from "../lib/utils";
42import { isLatestRunSettled } from "../session-logic";
43import { observeIntersection } from "../lib/observeIntersection";
44import { deadlineAfter, deadlineStore, type ClockStore } from "@t3tools/client-runtime/clock";
45import { useDeadlinePassed } from "../hooks/useDeadline";
46import { legacyProjectCwdPreferenceKey } from "../uiStateStore";
47import { isElectron } from "../env";
48import { shouldShowThreadJumpHintsForModifiers } from "../keybindings";
49import { isTerminalFocused, subscribeToTerminalFocusChanges } from "../lib/terminalFocus";
50import { isPreviewFocused } from "../lib/previewFocus";
51import { isModelPickerOpen, subscribeToModelPickerVisibility } from "../modelPickerVisibility";
52import { shortcutModifierStore } from "../shortcutModifierState";
53import { selectThreadTerminalUiState, useTerminalUiStateStore } from "../terminalUiStateStore";
54import { selectActiveRightPanel, useRightPanelStore } from "../rightPanelStore";
55​
56export function shouldNavigateAfterThreadPark(input: {
57 readonly threadKey: string;
58 readonly currentThreadKey: string | null;
59 readonly action: "settle" | "snooze";
60 readonly now: string;
61 readonly thread: (ThreadSnoozeShell & Pick<SidebarThreadSummary, "settledOverride">) | null;
62}): boolean {
63 return (
64 input.threadKey === input.currentThreadKey &&
65 input.thread !== null &&
66 (input.action === "settle"
67 ? input.thread.settledOverride === "settled"
68 : effectiveSnoozed(input.thread, { now: input.now }))
69 );
71​
72export const THREAD_JUMP_HINT_SHOW_DELAY_MS = 200;
73​
74export function resolveSidebarRowAccessibility(input: {
75 readonly title: string;
76 readonly statusLabel: string | null;
77 readonly projectDisplayName: string | null;
78 readonly isActive: boolean;
79}): { readonly label: string; readonly current: "page" | undefined } {
80 return {
81 label: [input.title, input.statusLabel, input.projectDisplayName].filter(Boolean).join(", "),
82 current: input.isActive ? "page" : undefined,
83 };
85​
86// Each prewarm retains growing thread detail and a live subscription, multiplying heap and server load.
87const SIDEBAR_ROW_SUBSCRIPTION_OVERSCAN_PX = 160;
88​
89export function useSidebarRowSubscriptionLease(isActive: boolean): {
90 readonly leaseLiveStatus: boolean;
91 readonly rowRef: (row: HTMLElement | null) => (() => void) | undefined;
92} {
93 const [isNearViewport, setIsNearViewport] = React.useState(isActive);
94 if (isActive && !isNearViewport) setIsNearViewport(true);
95 const canObserve = typeof IntersectionObserver !== "undefined";
96​
97 return {
98 leaseLiveStatus: isActive || isNearViewport || !canObserve,
99 rowRef: (row) => {
100 if (row === null || isActive || !canObserve) return undefined;
101 // The overscan has to apply to the sidebar's own scroller; a viewport-rooted
102 // margin is still clipped by it.
103 return observeIntersection(row, (entry) => setIsNearViewport(entry.isIntersecting), {
104 root: row.closest('[data-slot="scroll-area-viewport"]'),
105 rootMargin: `${SIDEBAR_ROW_SUBSCRIPTION_OVERSCAN_PX}px 0px`,
106 });
107 },
108 };
110​
111const fileDragClears = new Set<(active: false) => void>();
112function clearFileDrags() {
113 const clears = [...fileDragClears];
114 fileDragClears.clear();
115 for (const clear of clears) clear(false);
117​
118/**
119 * A file drag that ends outside every drop target (Escape, or a drop elsewhere)
120 * sends no dragleave to the row it last entered, so the window's dragend clears it.
121 */
122export function setFileDragActive(setActive: (active: boolean) => void, active: boolean) {
123 setActive(active);
124 if (typeof window === "undefined") return;
125 if (!active) {
126 if (fileDragClears.delete(setActive) && fileDragClears.size === 0) {
127 window.removeEventListener("dragend", clearFileDrags);
128 }
129 return;
130 }
131 if (fileDragClears.size === 0) window.addEventListener("dragend", clearFileDrags, { once: true });
132 fileDragClears.add(setActive);
134​
135/**
136 * A clock that advances exactly when a snooze wake time passes, so a woken
137 * thread leaves the shelf on time without a per-second clock.
138 */
139export function useSnoozeWakeClock(
140 threads: ReadonlyArray<{ readonly snoozedUntil?: string | null | undefined }>,
141): number {
142 const [clockMs, setClockMs] = React.useState(() => Date.now());
143 const wakeTimes: number[] = [];
144 let nextWakeAt: number | null = null;
145 for (const thread of threads) {
146 const wakeAt = thread.snoozedUntil == null ? Number.NaN : Date.parse(thread.snoozedUntil);
147 if (!(wakeAt > clockMs)) continue;
148 wakeTimes.push(wakeAt);
149 if (nextWakeAt === null || wakeAt < nextWakeAt) nextWakeAt = wakeAt;
150 }
151 const woke = useDeadlinePassed(nextWakeAt);
152 // Advancing to the latest wake that has passed skips every wake that elapsed
153 // meanwhile, e.g. across a laptop sleep. Stepping one wake at a time would
154 // re-render once per elapsed wake and hit React's limit.
155 if (woke && nextWakeAt !== null) {
156 let nextClockMs = nextWakeAt;
157 for (const wakeAt of wakeTimes) {
158 if (wakeAt > nextClockMs && deadlineStore(wakeAt).getSnapshot()) nextClockMs = wakeAt;
159 }
160 setClockMs(nextClockMs);
161 return nextClockMs;
162 }
163 return clockMs;
165​
166export function useRetainedValue<T>(key: string | null, value: T | null): T | null {
167 const [retained, setRetained] = React.useState<{
168 readonly key: string;
169 readonly value: T;
170 } | null>(null);
171 if (key !== null && value !== null && (retained?.key !== key || retained.value !== value)) {
172 setRetained({ key, value });
173 }
174 if (value !== null) return value;
175 return key !== null && retained?.key === key ? retained.value : null;
177​
178// Sortable owns drag transforms; replaying committed order would animate drops twice.
179export const animateSidebarLayoutChanges: AnimateLayoutChanges = (args) =>
180 args.isSorting ? defaultAnimateLayoutChanges(args) : false;
181​
182// Snoozed rows cannot accept drops without a wake time. Working rows only drag out as chat context.
183​
184export type SidebarSection = "pinned" | "active" | "working" | "snoozed" | "settled";
185​
186export function resolveSidebarThreadSection(input: {
187 readonly snoozed: boolean;
188 readonly settled: boolean;
189 readonly pinned: boolean;
190}): SidebarSection {
191 if (input.snoozed) return "snoozed";
192 if (input.settled) return "settled";
193 if (input.pinned) return "pinned";
194 return "active";
196​
197const SIDEBAR_MARKER_PREFIX = "sidebar-marker-";
198​
199export type SidebarListMarker =
200 | "pinned-header"
201 | "active-placeholder"
202 | "settled-placeholder"
203 | "pinned-divider"
204 | "working-header"
205 | "snoozed-header"
206 | "settled-header";
207​
208export function sidebarMarkerId(marker: SidebarListMarker): string {
209 return `${SIDEBAR_MARKER_PREFIX}${marker}`;
211​
212export type SidebarListItem =
213 | { readonly kind: "thread"; readonly key: string; readonly section: SidebarSection }
214 | { readonly kind: "marker"; readonly marker: SidebarListMarker };
215​
216export function sidebarListItemId(item: SidebarListItem): string {
217 return item.kind === "thread" ? item.key : sidebarMarkerId(item.marker);
219​
220function sectionAtSidebarSlot(items: readonly SidebarListItem[], index: number): SidebarSection {
221 let section: SidebarSection = "pinned";
222 for (let i = 0; i < index && i < items.length; i += 1) {
223 const item = items[i]!;
224 if (item.kind !== "marker") continue;
225 if (item.marker === "pinned-divider") section = "active";
226 else if (item.marker === "working-header") section = "working";
227 else if (item.marker === "snoozed-header") section = "snoozed";
228 else if (item.marker === "settled-header") section = "settled";
229 }
230 return section;
232​
233type SidebarDropTarget = {
234 readonly section: "pinned" | "active" | "settled";
235 readonly pinnedOrder: readonly string[];
236 readonly activeOrder: readonly string[];
237};
238​
239export function resolveSidebarDropTarget(
240 items: readonly SidebarListItem[],
241 activeKey: string,
242 overId: string,
243): SidebarDropTarget | null {
244 const activeIndex = items.findIndex((item) => sidebarListItemId(item) === activeKey);
245 const overIndex = items.findIndex((item) => sidebarListItemId(item) === overId);
246 if (activeIndex === -1 || overIndex === -1 || items[activeIndex]?.kind !== "thread") return null;
247 const moved = items.filter((_, index) => index !== activeIndex);
248 moved.splice(overIndex, 0, items[activeIndex]!);
249 const section = sectionAtSidebarSlot(moved, overIndex);
250 if (section === "working" || section === "snoozed") return null;
251 const pinnedOrder: string[] = [];
252 const activeOrder: string[] = [];
253 let currentSection: SidebarSection = "pinned";
254 for (const item of moved) {
255 if (item.kind === "marker") {
256 if (item.marker === "pinned-divider") currentSection = "active";
257 else if (
258 item.marker === "working-header" ||
259 item.marker === "snoozed-header" ||
260 item.marker === "settled-header"
261 )
262 break;
263 } else if (currentSection === "pinned") pinnedOrder.push(item.key);
264 else activeOrder.push(item.key);
265 }
266 return { section, pinnedOrder, activeOrder };
268​
269type SidebarThreadDropPlan =
270 | { readonly kind: "none" }
271 | {
272 readonly kind: "reorder-pinned";
273 readonly order: readonly string[];
274 readonly assignments: ReadonlyArray<{ readonly id: string; readonly orderKey: string }>;
275 }
276 | {
277 readonly kind: "pin";
278 readonly order: readonly string[];
279 readonly orderKey: string | undefined;
280 readonly extraAssignments: ReadonlyArray<{ readonly id: string; readonly orderKey: string }>;
281 }
282 | {
283 readonly kind: "move-active";
284 readonly order: readonly string[] | null;
285 readonly assignments: ReadonlyArray<{ readonly id: string; readonly orderKey: string }>;
286 readonly unpin: boolean;
287 readonly unsettle: boolean;
288 readonly unsnooze: boolean;
289 }
290 | { readonly kind: "settle" };
291​
292export type SidebarDropVerb = "pin" | "unpin" | "settle" | "unsettle" | "wake";
293​
294export function resolveSidebarDropVerb(
295 from: SidebarSection,
296 to: SidebarSection | null,
297): SidebarDropVerb | null {
298 if (to === null || to === from || to === "working" || to === "snoozed") return null;
299 if (to === "pinned") return "pin";
300 if (to === "settled") return "settle";
301 if (from === "pinned") return "unpin";
302 if (from === "settled") return "unsettle";
303 return "wake";
305​
306export function resolveSidebarSweepKeys(
307 orderedKeys: readonly string[],
308 originKey: string,
309 targetKey: string,
310 canApply: (key: string) => boolean,
311): string[] {
312 const origin = orderedKeys.indexOf(originKey);
313 const target = orderedKeys.indexOf(targetKey);
314 if (origin === -1 || target === -1) return [];
315 return orderedKeys.slice(Math.min(origin, target), Math.max(origin, target) + 1).filter(canApply);
317​
318export function sidebarThreadKeyAtY(list: HTMLElement, y: number): string | null {
319 const viewport = list.closest('[data-slot="scroll-area-viewport"]')?.getBoundingClientRect();
320 const visibleY = viewport ? Math.min(Math.max(y, viewport.top), viewport.bottom - 1) : y;
321 let key: string | null = null;
322 for (const row of list.querySelectorAll<HTMLElement>("li[data-thread-item]")) {
323 if (key !== null && row.getBoundingClientRect().top > visibleY) break;
324 key = row.dataset.threadItem ?? null;
325 }
326 return key;
328​
329export function resolveSidebarReorderableThreadKeys(input: {
330 readonly threads: ReadonlyArray<Pick<SidebarThreadSummary, "environmentId" | "id">>;
331 readonly serverConfigs: ReadonlyMap<EnvironmentId, Pick<EnvironmentServerConfig, "environment">>;
332 readonly connectedEnvironmentIds: readonly EnvironmentId[];
333}) {
334 const connectedEnvironmentIds = new Set(input.connectedEnvironmentIds);
335 const draggableThreadKeys = new Set<string>();
336 const activeReorderableThreadKeys = new Set<string>();
337​
338 for (const thread of input.threads) {
339 // Config is cached for offline rendering, so its presence does not make a row writable.
340 if (
341 !connectedEnvironmentIds.has(thread.environmentId) ||
342 !input.serverConfigs.has(thread.environmentId)
343 ) {
344 continue;
345 }
346​
347 const threadKey = scopedThreadKey(scopeThreadRef(thread.environmentId, thread.id));
348 activeReorderableThreadKeys.add(threadKey);
349 draggableThreadKeys.add(threadKey);
350 }
351​
352 return { draggableThreadKeys, activeReorderableThreadKeys };
354​
355export function planSidebarThreadDrop(input: {
356 readonly activeKey: string;
357 readonly activeSection: SidebarSection;
358 readonly activePinned?: boolean;
359 readonly activeSettled?: boolean;
360 readonly supportsSettlement?: boolean;
361 readonly target: SidebarDropTarget;
362 readonly pinnedOrder: readonly string[];
363 readonly pinnedKeysById: ReadonlyMap<string, string | null | undefined>;
364 readonly reorderableKeys?: ReadonlySet<string>;
365 readonly activeOrder: readonly string[];
366 readonly activeKeysById: ReadonlyMap<string, string | null | undefined>;
367 readonly activeReorderableKeys?: ReadonlySet<string>;
368 readonly activeTimeOrdered?: boolean;
369}): SidebarThreadDropPlan {
370 const {
371 activeKey,
372 activeSection,
373 activePinned = activeSection === "pinned",
374 activeSettled = activeSection === "settled",
375 target,
376 pinnedOrder,
377 pinnedKeysById,
378 reorderableKeys,
379 activeOrder,
380 activeKeysById,
381 activeReorderableKeys,
382 } = input;
383 if (activeSection === "working") return { kind: "none" };
384 if (input.supportsSettlement === false && (target.section === "settled" || activeSettled)) {
385 return { kind: "none" };
386 }
387 const arrange = (
388 order: readonly string[],
389 keysById: ReadonlyMap<string, string | null | undefined>,
390 writable: ReadonlySet<string> | undefined,
391 ) => {
392 if (!writable) return planPinnedReorder({ orderedIds: order, keysById, movedId: activeKey });
393 if (!writable.has(activeKey)) return null;
394 const assignments = planPinnedReorder({
395 orderedIds: order.filter((key) => writable.has(key) || keysById.get(key) != null),
396 keysById,
397 movedId: activeKey,
398 });
399 if (assignments.some(({ id }) => !writable.has(id))) return null;
400​
401 // Keyless Active rows sort before keyed rows; keyless Pinned rows sort after them.
402 // Materializing any row across a frozen keyless boundary cannot persist that position.
403 const assignedIds = new Set(assignments.map(({ id }) => id));
404 let hasFrozenKeylessBefore = false;
405 let hasAssignedBefore = false;
406 for (const id of order) {
407 const isFrozenKeyless = !writable.has(id) && keysById.get(id) == null;
408 const isAssigned = assignedIds.has(id);
409 if (
410 (target.section === "active" && isFrozenKeyless && hasAssignedBefore) ||
411 (target.section === "pinned" && isAssigned && hasFrozenKeylessBefore)
412 ) {
413 return null;
414 }
415​
416 hasFrozenKeylessBefore ||= isFrozenKeyless;
417 hasAssignedBefore ||= isAssigned;
418 }
419​
420 return assignments;
421 };
422 switch (target.section) {
423 case "active": {
424 if (input.activeTimeOrdered) {
425 return activeSection === "active"
426 ? { kind: "none" }
427 : {
428 kind: "move-active",
429 order: null,
430 assignments: [],
431 unpin: activePinned,
432 unsettle: activeSettled,
433 unsnooze: activeSection === "snoozed",
434 };
435 }
436 const order = target.activeOrder;
437 if (
438 activeSection === "active" &&
439 order.length === activeOrder.length &&
440 order.every((key, index) => key === activeOrder[index])
441 ) {
442 return { kind: "none" };
443 }
444 const assignments = arrange(order, activeKeysById, activeReorderableKeys);
445 if (assignments === null) return { kind: "none" };
446 return {
447 kind: "move-active",
448 order,
449 assignments,
450 unpin: activePinned,
451 unsettle: activeSettled,
452 unsnooze: activeSection === "snoozed",
453 };
454 }
455 case "settled":
456 return activeSection === "settled" ? { kind: "none" } : { kind: "settle" };
457 case "pinned": {
458 const order = target.pinnedOrder;
459 if (
460 activeSection === "pinned" &&
461 order.length === pinnedOrder.length &&
462 order.every((key, index) => key === pinnedOrder[index])
463 ) {
464 return { kind: "none" };
465 }
466 const assignments = arrange(order, pinnedKeysById, reorderableKeys);
467 if (assignments === null) return { kind: "none" };
468 if (activeSection === "pinned") {
469 return assignments.length === 0
470 ? { kind: "none" }
471 : { kind: "reorder-pinned", order, assignments };
472 }
473 return {
474 kind: "pin",
475 order,
476 orderKey: assignments.find((assignment) => assignment.id === activeKey)?.orderKey,
477 extraAssignments: activePinned
478 ? assignments
479 : assignments.filter((assignment) => assignment.id !== activeKey),
480 };
481 }
482 }
484​
485export function applySidebarThreadDrop<
486 T extends Pick<
487 SidebarThreadSummary,
488 | "pinnedAt"
489 | "pinOrderKey"
490 | "activeOrderKey"
491 | "snoozedAt"
492 | "snoozedUntil"
493 | "settledAt"
494 | "settledOverride"
495 | "unsettledAt"
496 >,
497>(thread: T, section: "pinned" | "active" | "settled", now: string, orderKey?: string): T {
498 const wasSettled = thread.settledOverride === "settled";
499 const awake = { ...thread, snoozedAt: null, snoozedUntil: null };
500 if (section === "settled") {
501 return {
502 ...awake,
503 pinnedAt: null,
504 pinOrderKey: null,
505 activeOrderKey: null,
506 settledOverride: "settled",
507 settledAt: wasSettled ? (thread.settledAt ?? now) : now,
508 unsettledAt: null,
509 };
510 }
511 const resumed = wasSettled
512 ? { ...awake, settledOverride: "active" as const, settledAt: null, unsettledAt: now }
513 : awake;
514 return {
515 ...resumed,
516 pinnedAt: section === "pinned" ? (thread.pinnedAt ?? now) : null,
517 pinOrderKey: section === "pinned" ? (orderKey ?? thread.pinOrderKey) : null,
518 ...(section === "active" && orderKey !== undefined ? { activeOrderKey: orderKey } : {}),
519 };
521​
522type SidebarProject = {
523 id: string;
524 title: string;
525 createdAt?: string | undefined;
526 updatedAt?: string | undefined;
527};
528​
529type ScopedSidebarProject = SidebarProject & {
530 environmentId: string;
531};
532​
533type ScopedSidebarThread = ThreadSortInput & {
534 environmentId: string;
535 projectId: string;
536 archivedAt: string | null;
537};
538​
539type LogicalSidebarProject = SidebarProject & {
540 projectKey: string;
541 memberProjectRefs: readonly {
542 environmentId: string;
543 projectId: string;
544 }[];
545};
546​
547type ThreadTraversalDirection = "previous" | "next";
548​
549/** Exclude only successful deletions from shared-worktree checks. */
550export async function deleteSelectedThreadEntries<
551 TEntry extends { readonly threadKey: string },
552>(input: {
553 entries: readonly TEntry[];
554 delete: (
555 entry: TEntry,
556 deletedThreadKeys: ReadonlySet<string>,
557 ) => Promise<AtomCommandResult<unknown, unknown> | null>;
558}) {
559 const deletedThreadKeys = new Set<string>();
560 let firstFailure: AsyncResult.Failure<unknown, unknown> | null = null;
561​
562 for (const entry of input.entries) {
563 const result = await input.delete(entry, deletedThreadKeys);
564 if (result === null) continue;
565 if (result._tag === "Failure") {
566 if (isAtomCommandInterrupted(result)) break;
567 firstFailure ??= result;
568 continue;
569 }
570 deletedThreadKeys.add(entry.threadKey);
571 }
572​
573 return { deletedThreadKeys, firstFailure };
575​
576export function isSidebarHiddenThread(thread: Pick<SidebarThreadSummary, "lineage">): boolean {
577 return !isListedThreadLineage(thread.lineage);
579​
580// Subagent and side-chat threads have no sidebar row, so an open one is represented by
581// its nearest listed ancestor. A broken chain (missing parent, cycle,
582// other environment) resolves to the thread itself, which then matches no row.
583export function resolveSidebarRowThreadId(
584 threadId: ThreadId,
585 environmentId: EnvironmentId,
586 threads: readonly Pick<SidebarThreadSummary, "id" | "environmentId" | "lineage">[],
587): ThreadId {
588 const findThread = (id: ThreadId) =>
589 threads.find((thread) => thread.id === id && thread.environmentId === environmentId);
590 const visited = new Set<ThreadId>();
591 let thread = findThread(threadId);
592 while (thread !== undefined && isSidebarHiddenThread(thread)) {
593 if (thread.lineage.parentThreadId === null || visited.has(thread.id)) return threadId;
594 visited.add(thread.id);
595 thread = findThread(thread.lineage.parentThreadId);
596 }
597 return thread?.id ?? threadId;
599​
600/**
601 * `delegatedUnderParent` holds the tasks linked environments run for a thread
602 * the sidebar lists, by thread key; they show under that thread, as subagents do.
603 */
604export function filterSidebarV2VisibleThreads<
605 T extends Pick<SidebarThreadSummary, "archivedAt" | "environmentId" | "id" | "lineage"> & {
606 projectId: string;
607 },
608>(
609 threads: readonly T[],
610 scopedProjectKeys: ReadonlySet<string> | null,
611 delegatedUnderParent: ReadonlySet<string>,
612): T[] {
613 return threads.filter(
614 (thread) =>
615 thread.archivedAt === null &&
616 !isShownUnderParent(
617 { environmentId: thread.environmentId, threadId: thread.id },
618 thread.lineage,
619 delegatedUnderParent,
620 ) &&
621 (scopedProjectKeys === null ||
622 scopedProjectKeys.has(`${thread.environmentId}:${thread.projectId}`)),
623 );
625​
626export function buildBulkTitleRegenerationContextMenuItem(input: {
627 supportedCount: number;
628 actionableCount: number;
629}): ContextMenuItem<"regenerate-title"> | null {
630 if (input.supportedCount === 0) return null;
631 if (input.actionableCount === 0) {
632 return {
633 id: "regenerate-title",
634 label: `Regenerating… (${input.supportedCount})`,
635 disabled: true,
636 };
637 }
638 return {
639 id: "regenerate-title",
640 label: `Regenerate titles (${input.actionableCount})`,
641 };
643​
644export function buildBulkUnpinContextMenuItem(input: {
645 pinnedCount: number;
646}): ContextMenuItem<"unpin"> | null {
647 if (input.pinnedCount === 0) return null;
648 return { id: "unpin", label: `Unpin (${input.pinnedCount})` };
650​
651export interface ThreadStatusPill {
652 label:
653 | "Working"
654 | "Connecting"
655 | "Completed"
656 | "Failed"
657 | "Pending Approval"
658 | "Awaiting Input"
659 | "Guest Request"
660 | "Waiting"
661 | "Plan Ready";
662 colorClass: string;
663 dotClass: string;
664 pulse: boolean;
666​
667type ThreadStatusInput = Pick<
668 SidebarThreadSummary,
669 | "hasActionableProposedPlan"
670 | "hasPendingApprovals"
671 | "hasPendingUserInput"
672 | "pendingSubagentRequest"
673 | "pendingGuestMessageCount"
674 | "interactionMode"
675 | "latestRun"
676 | "runtime"
677> & {
678 lastVisitedAt?: string | null | undefined;
679 pendingBackgroundTasks?: SidebarThreadSummary["pendingBackgroundTasks"] | undefined;
680 blockedOnThreadWait?: boolean | undefined;
681};
682​
683// Read at event time: subscribing Sidebar to terminal or modifier state re-renders every row.
684export function threadShortcutContext(routeThreadRef: ScopedThreadRef | null) {
685 return {
686 terminalFocus: isTerminalFocused(),
687 terminalOpen:
688 routeThreadRef !== null &&
689 selectThreadTerminalUiState(
690 useTerminalUiStateStore.getState().terminalUiStateByThreadKey,
691 routeThreadRef,
692 ).terminalOpen,
693 previewFocus: isPreviewFocused(),
694 previewOpen:
695 selectActiveRightPanel(useRightPanelStore.getState().byThreadKey, routeThreadRef) ===
696 "preview",
697 modelPickerOpen: isModelPickerOpen(),
698 isWeb: !isElectron,
699 isDesktop: isElectron,
700 };
702​
703/** Whether the current modifier combination, including none, has been held unchanged for `delayMs`. */
704function createModifierHoldStore(delayMs: number): ClockStore<boolean> {
705 const listeners = new Set<() => void>();
706 let held = false;
707 let stopDeadline = () => {};
708 let stopModifiers: (() => void) | null = null;
709​
710 const setHeld = (next: boolean) => {
711 if (held === next) return;
712 held = next;
713 for (const listener of listeners) listener();
714 };
715 const onModifiersChange = () => {
716 stopDeadline();
717 const deadline = deadlineStore(deadlineAfter(delayMs));
718 stopDeadline = deadline.subscribe(() => setHeld(true));
719 // A deadline another subscriber already passed never notifies a late joiner.
720 setHeld(deadline.getSnapshot());
721 };
722​
723 return {
724 subscribe: (listener) => {
725 listeners.add(listener);
726 if (stopModifiers === null) {
727 stopModifiers = shortcutModifierStore.subscribe(onModifiersChange);
728 onModifiersChange();
729 }
730 return () => {
731 listeners.delete(listener);
732 if (listeners.size > 0) return;
733 stopModifiers?.();
734 stopModifiers = null;
735 stopDeadline();
736 stopDeadline = () => {};
737 held = false;
738 };
739 },
740 getSnapshot: () => held,
741 };
743​
744const threadJumpModifierHold = createModifierHoldStore(THREAD_JUMP_HINT_SHOW_DELAY_MS);
745​
746function subscribeToThreadJumpHintInputs(listener: () => void): () => void {
747 const unsubscribeHold = threadJumpModifierHold.subscribe(listener);
748 const unsubscribeFocus = subscribeToTerminalFocusChanges(listener);
749 const unsubscribeTerminals = useTerminalUiStateStore.subscribe(listener);
750 const unsubscribeRightPanels = useRightPanelStore.subscribe(listener);
751 const unsubscribeModelPicker = subscribeToModelPickerVisibility(listener);
752 return () => {
753 unsubscribeHold();
754 unsubscribeFocus();
755 unsubscribeTerminals();
756 unsubscribeRightPanels();
757 unsubscribeModelPicker();
758 };
760​
761/**
762 * Thread jump hints appear once the jump modifier has been held for a moment,
763 * so a quick shortcut never flashes them, and hide as soon as it is released.
764 * The snapshot is the visibility itself, so a quick shortcut never re-renders the caller.
765 */
766export function useThreadJumpHintsVisible(
767 keybindings: ResolvedKeybindingsConfig,
768 routeThreadRef: ScopedThreadRef | null,
769): boolean {
770 return React.useSyncExternalStore(
771 subscribeToThreadJumpHintInputs,
772 () =>
773 threadJumpModifierHold.getSnapshot() &&
774 shouldShowThreadJumpHintsForModifiers(shortcutModifierStore.getSnapshot(), keybindings, {
775 platform: navigator.platform,
776 context: threadShortcutContext(routeThreadRef),
777 }),
778 );
780​
781export function resolveThreadLastVisitedAt(
782 serverLastVisitedAt: string | null | undefined,
783 localLastVisitedAt: string | undefined,
784): string | undefined {
785 // Server visits override local watermarks, including mark-unread rewinds; use local values only on older
786 // servers.
787 if (serverLastVisitedAt === undefined) return localLastVisitedAt;
788 return serverLastVisitedAt ?? undefined;
790​
791export function hasUnseenCompletion(thread: ThreadStatusInput): boolean {
792 if (!thread.latestRun?.completedAt) return false;
793 const completedAt = Date.parse(thread.latestRun.completedAt);
794 if (Number.isNaN(completedAt)) return false;
795 if (!thread.lastVisitedAt) return false;
796​
797 const lastVisitedAt = Date.parse(thread.lastVisitedAt);
798 if (Number.isNaN(lastVisitedAt)) return true;
799 return completedAt > lastVisitedAt;
801​
802/** Unopened threads' failures still count as unseen, unlike completions. */
803function hasUnseenFailure(thread: ThreadStatusInput): boolean {
804 if (thread.latestRun?.status !== "failed") return false;
805 if (!thread.lastVisitedAt) return true;
806 const completedAt = Date.parse(thread.latestRun.completedAt ?? "");
807 const lastVisitedAt = Date.parse(thread.lastVisitedAt);
808 if (Number.isNaN(completedAt) || Number.isNaN(lastVisitedAt)) return true;
809 return completedAt > lastVisitedAt;
811​
812// Suppress trailing double-click navigation; keyboard and synthetic clicks use detail 0.
813export function isTrailingDoubleClick(detail: number): boolean {
814 return detail > 1;
816​
817function nodeClosest(node: object | null, selector: string): unknown {
818 if (node === null || !("closest" in node) || typeof node.closest !== "function") return null;
819 return node.closest(selector);
821​
822export function isSidebarNestedLinkClick(target: EventTarget | null): boolean {
823 if (target == null || typeof target !== "object") return false;
824 if (nodeClosest(target, "a[href]") !== null) return true;
825 const parent =
826 "parentElement" in target &&
827 target.parentElement !== null &&
828 typeof target.parentElement === "object"
829 ? target.parentElement
830 : null;
831 return nodeClosest(parent, "a[href]") !== null;
833​
834/** The "New thread in" picker opens unless there is one open project or none; then the current context decides. */
835export function shouldCreateNewThreadInCurrentProject(
836 shiftKey: boolean,
837 openProjectGroupCount: number,
838 projectGroupCount: number,
839): boolean {
840 return shiftKey || openProjectGroupCount === 1 || projectGroupCount === 0;
842​
843export function orderItemsByPreferredIds<TItem, TId>(input: {
844 items: readonly TItem[];
845 preferredIds: readonly TId[];
846 getId: (item: TItem) => TId;
847 getPreferenceIds?: (item: TItem) => readonly TId[];
848}): TItem[] {
849 const { getId, getPreferenceIds, items, preferredIds } = input;
850 if (preferredIds.length === 0) {
851 return [...items];
852 }
853​
854 const indexesByPreferenceId = new Map<TId, number[]>();
855 for (const [index, item] of items.entries()) {
856 const preferenceIds = getPreferenceIds?.(item) ?? [getId(item)];
857 for (const preferenceId of new Set(preferenceIds)) {
858 const indexes = indexesByPreferenceId.get(preferenceId);
859 if (indexes) {
860 indexes.push(index);
861 } else {
862 indexesByPreferenceId.set(preferenceId, [index]);
863 }
864 }
865 }
866​
867 const emittedIndexes = new Set<number>();
868 const ordered = preferredIds.flatMap((id) => {
869 const index = indexesByPreferenceId
870 .get(id)
871 ?.find((candidate) => !emittedIndexes.has(candidate));
872 if (index === undefined) {
873 return [];
874 }
875 emittedIndexes.add(index);
876 return [items[index]!];
877 });
878 const remaining = items.filter((_, index) => !emittedIndexes.has(index));
879 return [...ordered, ...remaining];
881​
882export function resolveAdjacentThreadId<T>(input: {
883 threadIds: readonly T[];
884 currentThreadId: T | null;
885 direction: ThreadTraversalDirection;
886}): T | null {
887 const { currentThreadId, direction, threadIds } = input;
888​
889 if (threadIds.length === 0) {
890 return null;
891 }
892​
893 if (currentThreadId === null) {
894 return direction === "previous" ? (threadIds.at(-1) ?? null) : (threadIds[0] ?? null);
895 }
896​
897 const currentIndex = threadIds.indexOf(currentThreadId);
898 if (currentIndex === -1) {
899 return null;
900 }
901​
902 if (direction === "previous") {
903 return currentIndex > 0 ? (threadIds[currentIndex - 1] ?? null) : null;
904 }
905​
906 return currentIndex < threadIds.length - 1 ? (threadIds[currentIndex + 1] ?? null) : null;
908​
909export type SidebarThreadStatus =
910 | "approval"
911 | "input"
912 | "request"
913 | "preparing"
914 | "working"
915 | "waiting"
916 | "failed"
917 | "limited"
918 | "ready";
919​
920export function shouldRecedeSidebarThread(input: {
921 status: SidebarThreadStatus;
922 isUnread: boolean;
923 isWoke: boolean;
924 isActive: boolean;
925 isSelected: boolean;
926}): boolean {
927 if (
928 input.isActive ||
929 input.isSelected ||
930 input.status === "input" ||
931 input.status === "request"
932 ) {
933 return false;
934 }
935 if (input.status === "preparing" || input.status === "working" || input.status === "waiting") {
936 return true;
937 }
938 if (input.status === "ready" || input.status === "approval") {
939 return !input.isUnread && !input.isWoke;
940 }
941 return false;
943​
944type SidebarThreadStatusInput = Pick<
945 SidebarThreadSummary,
946 | "hasPendingApprovals"
947 | "hasPendingUserInput"
948 | "pendingSubagentRequest"
949 | "pendingGuestMessageCount"
950 | "runtime"
951 | "blockedOnThreadWait"
952>;
953​
954export function resolveSidebarThreadStatus(thread: SidebarThreadStatusInput): SidebarThreadStatus {
955 if (thread.hasPendingApprovals || thread.pendingSubagentRequest === "approval") {
956 return "approval";
957 }
958 if (thread.hasPendingUserInput || thread.pendingSubagentRequest === "user_input") {
959 return "input";
960 }
961 // A guest is waiting on the owner; the agent's own requests come first.
962 if ((thread.pendingGuestMessageCount ?? 0) > 0) {
963 return "request";
964 }
965 if (thread.runtime?.status === "running" && thread.blockedOnThreadWait === true) {
966 return "waiting";
967 }
968 if (thread.runtime?.status === "preparing") {
969 return "preparing";
970 }
971 if (
972 thread.runtime !== null &&
973 ["queued", "starting", "running", "waiting"].includes(thread.runtime.status)
974 ) {
975 return "working";
976 }
977 if (thread.runtime?.status === "idle") {
978 return "waiting";
979 }
980 if (thread.runtime?.status === "failed") {
981 return thread.runtime.lastErrorClass === "usage_limit" ? "limited" : "failed";
982 }
983 return "ready";
985​
986/**
987 * The dot on a closed boring-sidebar folder: the most urgent state among its
988 * hidden threads. Waiting threads stay quiet, like their rows.
989 */
990export function resolveSidebarFolderDot(
991 threads: ReadonlyArray<ThreadStatusInput & SidebarThreadStatusInput>,
992): "attention" | "failed" | "unread" | "working" | null {
993 const statuses = new Set(threads.map(resolveSidebarThreadStatus));
994 if (
995 statuses.has("input") ||
996 statuses.has("approval") ||
997 statuses.has("request") ||
998 statuses.has("limited")
999 ) {
1000 return "attention";
1002 if (statuses.has("failed")) return "failed";
1003 // Rows show Done only for ready threads, so the dot follows the same rule.
1004 const hasUnread = threads.some(
1005 (thread) => resolveSidebarThreadStatus(thread) === "ready" && hasUnseenCompletion(thread),
1006 );
1007 if (hasUnread) return "unread";
1008 if (statuses.has("working") || statuses.has("preparing")) return "working";
1009 return null;
1011​
1012/**
1013 * Keys the old per-project sidebar saved folder open state under, most
1014 * specific first, for `resolveProjectExpanded`. Boring folders read and write
1015 * the same keys, so a legacy user's closed folders stay closed after regrouping.
1016 */
1017export function sidebarFolderExpansionKeys(group: {
1018 readonly projectKey: string;
1019 readonly memberProjects: ReadonlyArray<{
1020 readonly physicalProjectKey: string;
1021 readonly workspaceRoot: string;
1022 }>;
1023}): string[] {
1024 return [
1025 group.projectKey,
1026 ...group.memberProjects.map((member) => member.physicalProjectKey),
1027 ...group.memberProjects.map((member) => legacyProjectCwdPreferenceKey(member.workspaceRoot)),
1028 ];
1030​
1031/**
1032 * Boring sidebar folders. Folders follow `groups` order and threads keep their
1033 * input order. A project with no threads gets a folder only when `keepEmpty` says so.
1034 * A thread whose project is in no group has no folder and is left out.
1035 */
1036export function groupSidebarThreadsByProject<
1037 TGroup extends {
1038 readonly memberProjectRefs: ReadonlyArray<{
1039 readonly environmentId: EnvironmentId;
1040 readonly projectId: string;
1041 }>;
1042 },
1043 TThread extends Pick<SidebarThreadSummary, "environmentId" | "projectId">,
1045 groups: readonly TGroup[],
1046 threads: readonly TThread[],
1047 keepEmpty: (group: TGroup) => boolean,
1048): Array<{ group: TGroup; threads: TThread[] }> {
1049 const folders = groups.map((group) => ({ group, threads: [] as TThread[] }));
1050 const folderByProject = new Map<string, (typeof folders)[number]>();
1051 for (const folder of folders) {
1052 for (const ref of folder.group.memberProjectRefs) {
1053 folderByProject.set(`${ref.environmentId}:${ref.projectId}`, folder);
1056 for (const thread of threads) {
1057 folderByProject.get(`${thread.environmentId}:${thread.projectId}`)?.threads.push(thread);
1059 return folders.filter((folder) => folder.threads.length > 0 || keepEmpty(folder.group));
1061​
1062export type SidebarV2TopStatusKind =
1063 | "approval"
1064 | "done"
1065 | "failed"
1066 | "limited"
1067 | "input"
1068 | "request"
1069 | "waiting"
1070 | "woke"
1071 | "working";
1072​
1073export function firstValidTimestampMs(
1074 ...candidates: ReadonlyArray<string | null | undefined>
1075): number {
1076 for (const candidate of candidates) {
1077 if (candidate == null) continue;
1078 const parsed = Date.parse(candidate);
1079 if (!Number.isNaN(parsed)) return parsed;
1081 return 0;
1083​
1084export { sortActiveThreadsByOrderKey as sortThreadsForSidebar } from "@t3tools/client-runtime/state/thread-sort";
1085export {
1086 sortInboxThreadsByReturn,
1087 sortWorkingThreadsBySend,
1088} from "@t3tools/client-runtime/state/thread-inbox";
1089​
1090export { pinOrderKeyBetween } from "@t3tools/client-runtime/state/thread-sort";
1091export { sortPinnedThreadsByOrderKey as sortPinnedThreadsForSidebar } from "@t3tools/client-runtime/state/thread-sort";
1092​
1093const EMPTY_CONTENT_MATCH_KEYS: ReadonlySet<string> = new Set<string>();
1094​
1095/**
1096 * Sidebar search results: title, branch, and pull request matches ranked as
1097 * the command palette ranks them, then threads listed only because their
1098 * messages match, in `contentMatchKeys` order.
1099 */
1100export function searchSidebarThreads<
1101 T extends ThreadSearchShell & {
1102 readonly environmentId: EnvironmentId;
1103 readonly id: ThreadId;
1104 },
1106 threads: readonly T[],
1107 query: string,
1108 contentMatchKeys: ReadonlySet<string> = EMPTY_CONTENT_MATCH_KEYS,
1109 now = Date.now(),
1110): { readonly titleMatches: T[]; readonly contentMatches: T[] } {
1111 const normalizedQuery = foldSearchQuery(query);
1112 if (normalizedQuery.length === 0) return { titleMatches: [], contentMatches: [] };
1113 const titleMatches = rankSearchItems(threads, (thread, options) =>
1114 scoreThreadSearch(normalizedQuery, threadSearchSubject(thread, null), now, {
1115 ...options,
1116 picks: false,
1117 }),
1118 ).map(({ item }) => item);
1119 const listed = new Set(titleMatches);
1120 // In the order the server ranked their messages, as the palette lists them.
1121 const threadByKey = new Map(
1122 threads.map((thread) => [
1123 threadSearchMatchKey({ environmentId: thread.environmentId, threadId: thread.id }),
1124 thread,
1125 ]),
1126 );
1127 const contentMatches = [...contentMatchKeys].flatMap((key) => {
1128 const thread = threadByKey.get(key);
1129 return thread && !listed.has(thread) ? [thread] : [];
1130 });
1131 return { titleMatches, contentMatches };
1133​
1134export function pullRequestMatchesSearchQuery(
1135 pullRequest: Parameters<typeof threadPullRequestSearchTerms>[0],
1136 query: string,
1137): boolean {
1138 const normalizedQuery = normalizeSearchText(query);
1139 if (normalizedQuery.length === 0) return false;
1140 const haystack = normalizeSearchText(threadPullRequestSearchTerms(pullRequest).join(" "));
1141 return normalizedQuery.split(" ").every((token) => haystack.includes(token));
1143​
1144export function filterSidebarProjectScopeItems<TItem extends { readonly value: string }>(input: {
1145 items: readonly TItem[];
1146 query: string;
1147 matches: (item: TItem, query: string) => boolean;
1148}): readonly TItem[] {
1149 const query = input.query.trim();
1150 if (query.length === 0) return input.items;
1151 return input.items.filter((item) => item.value !== "all" && input.matches(item, query));
1153​
1154interface SidebarProjectScopeMenuState {
1155 readonly open: boolean;
1156 readonly query: string;
1158​
1159type SidebarProjectScopeMenuAction =
1160 | { readonly type: "query-changed"; readonly query: string }
1161 | { readonly type: "open-changed"; readonly open: boolean }
1162 | { readonly type: "project-settings-opened" };
1163​
1164export function reduceSidebarProjectScopeMenuState(
1165 state: SidebarProjectScopeMenuState,
1166 action: SidebarProjectScopeMenuAction,
1167): SidebarProjectScopeMenuState {
1168 switch (action.type) {
1169 case "query-changed":
1170 return { ...state, query: action.query };
1171 case "open-changed":
1172 return { open: action.open, query: "" };
1173 case "project-settings-opened":
1174 return { open: false, query: "" };
1177​
1178export function resolveWorkingStartedAt(
1179 thread: Pick<SidebarThreadSummary, "latestRun" | "runtime">,
1180): string | null {
1181 return resolveThreadWorkingStartedAt(thread);
1183​
1184export function resolveThreadStatusPill(input: {
1185 thread: ThreadStatusInput;
1186}): ThreadStatusPill | null {
1187 const { thread } = input;
1188​
1189 if (thread.hasPendingApprovals || thread.pendingSubagentRequest === "approval") {
1190 return {
1191 label: "Pending Approval",
1192 colorClass: "text-amber-600 dark:text-amber-300/90",
1193 dotClass: "bg-amber-500 dark:bg-amber-300/90",
1194 pulse: false,
1195 };
1197​
1198 if (thread.hasPendingUserInput || thread.pendingSubagentRequest === "user_input") {
1199 return {
1200 label: "Awaiting Input",
1201 colorClass: "text-indigo-600 dark:text-indigo-300/90",
1202 dotClass: "bg-indigo-500 dark:bg-indigo-300/90",
1203 pulse: false,
1204 };
1206​
1207 if ((thread.pendingGuestMessageCount ?? 0) > 0) {
1208 return {
1209 label: "Guest Request",
1210 colorClass: "text-guest-foreground",
1211 dotClass: "bg-guest",
1212 pulse: false,
1213 };
1215​
1216 if (
1217 (thread.runtime?.status === "running" && thread.blockedOnThreadWait !== true) ||
1218 thread.runtime?.status === "waiting"
1219 ) {
1220 return {
1221 label: "Working",
1222 colorClass: "text-sky-600 dark:text-sky-300/80",
1223 dotClass: "bg-sky-500 dark:bg-sky-300/80",
1224 pulse: true,
1225 };
1227​
1228 if (
1229 thread.runtime?.status === "preparing" ||
1230 thread.runtime?.status === "starting" ||
1231 thread.runtime?.status === "queued"
1232 ) {
1233 return {
1234 label: "Connecting",
1235 colorClass: "text-sky-600 dark:text-sky-300/80",
1236 dotClass: "bg-sky-500 dark:bg-sky-300/80",
1237 pulse: true,
1238 };
1240​
1241 if (
1242 (thread.runtime?.status === "running" && thread.blockedOnThreadWait === true) ||
1243 backgroundWorkHoldsCompletion(thread.pendingBackgroundTasks ?? [])
1244 ) {
1245 return {
1246 label: "Waiting",
1247 colorClass: "text-sidebar-muted-foreground",
1248 dotClass: "bg-sidebar-muted-foreground",
1249 pulse: false,
1250 };
1252​
1253 if (hasUnseenFailure(thread)) {
1254 return {
1255 label: "Failed",
1256 colorClass: "text-red-600 dark:text-red-300/90",
1257 dotClass: "bg-red-500 dark:bg-red-300/90",
1258 pulse: false,
1259 };
1261​
1262 const hasPlanReadyPrompt =
1263 !thread.hasPendingUserInput &&
1264 thread.interactionMode === "plan" &&
1265 isLatestRunSettled(thread.latestRun, thread.runtime) &&
1266 thread.hasActionableProposedPlan;
1267 if (hasPlanReadyPrompt) {
1268 return {
1269 label: "Plan Ready",
1270 colorClass: "text-violet-600 dark:text-violet-300/90",
1271 dotClass: "bg-violet-500 dark:bg-violet-300/90",
1272 pulse: false,
1273 };
1275​
1276 if (hasUnseenCompletion(thread)) {
1277 return {
1278 label: "Completed",
1279 colorClass: "text-emerald-600 dark:text-emerald-300/90",
1280 dotClass: "bg-emerald-500 dark:bg-emerald-300/90",
1281 pulse: false,
1282 };
1284​
1285 return null;
1287​
1288export function getFallbackThreadIdAfterDelete<
1289 T extends Pick<
1290 Thread,
1291 "id" | "projectId" | "createdAt" | "updatedAt" | "settledOverride" | "lineage"
1292 > &
1293 ThreadSortInput &
1294 ThreadSnoozeShell,
1295>(input: {
1296 threads: readonly T[];
1297 deletedThreadId: T["id"];
1298 sortOrder: SidebarThreadSortOrder;
1299 now: string;
1300 deletedThreadIds?: ReadonlySet<T["id"]>;
1301}): T["id"] | null {
1302 const { deletedThreadId, deletedThreadIds, sortOrder, now, threads } = input;
1303 const deletedThread = threads.find((thread) => thread.id === deletedThreadId);
1304 if (!deletedThread) {
1305 return null;
1307​
1308 return (
1309 sortThreads(
1310 threads.filter(
1311 (thread) =>
1312 thread.projectId === deletedThread.projectId &&
1313 thread.id !== deletedThreadId &&
1314 !deletedThreadIds?.has(thread.id) &&
1315 thread.settledOverride !== "settled" &&
1316 !effectiveSnoozed(thread, { now }) &&
1317 !isSidebarHiddenThread(thread),
1318 ),
1319 sortOrder,
1320 )[0]?.id ?? null
1321 );
1323function getProjectSortTimestamp(
1324 project: SidebarProject,
1325 projectThreads: readonly ThreadSortInput[],
1326 sortOrder: Exclude<SidebarProjectSortOrder, "manual">,
1327): number {
1328 if (projectThreads.length > 0) {
1329 return projectThreads.reduce(
1330 (latest, thread) => Math.max(latest, getThreadSortTimestamp(thread, sortOrder)),
1331 Number.NEGATIVE_INFINITY,
1332 );
1334​
1335 if (sortOrder === "created_at") {
1336 return toSortableTimestamp(project.createdAt) ?? Number.NEGATIVE_INFINITY;
1338 return toSortableTimestamp(project.updatedAt ?? project.createdAt) ?? Number.NEGATIVE_INFINITY;
1340​
1341function sortProjectsByActivity<TProject extends SidebarProject>(
1342 projects: readonly TProject[],
1343 sortOrder: SidebarProjectSortOrder,
1344 getProjectThreads: (project: TProject) => readonly ThreadSortInput[],
1345 compareTies: (left: TProject, right: TProject) => number,
1346): TProject[] {
1347 if (sortOrder === "manual") {
1348 return [...projects];
1350​
1351 // Project timestamps scan all threads; compute once per project instead of per comparison.
1352 return projects
1353 .map((project) => ({
1354 project,
1355 timestamp: getProjectSortTimestamp(project, getProjectThreads(project), sortOrder),
1356 }))
1357 .sort((left, right) => {
1358 const byTimestamp =
1359 right.timestamp === left.timestamp ? 0 : right.timestamp > left.timestamp ? 1 : -1;
1360 return byTimestamp || compareTies(left.project, right.project);
1361 })
1362 .map(({ project }) => project);
1364​
1365export function sortLogicalProjectsForSidebar<
1366 TProject extends LogicalSidebarProject,
1367 TThread extends ScopedSidebarThread,
1369 projects: readonly TProject[],
1370 threads: readonly TThread[],
1371 sortOrder: SidebarProjectSortOrder,
1372): TProject[] {
1373 const groupKeyByProjectRef = new Map(
1374 projects.flatMap((project) =>
1375 project.memberProjectRefs.map(
1376 (projectRef) =>
1377 [`${projectRef.environmentId}\0${projectRef.projectId}`, project.projectKey] as const,
1378 ),
1379 ),
1380 );
1381 const threadsByProjectKey = new Map<string, TThread[]>();
1382 for (const thread of threads) {
1383 if (thread.archivedAt !== null) continue;
1384 const projectKey = groupKeyByProjectRef.get(`${thread.environmentId}\0${thread.projectId}`);
1385 if (!projectKey) continue;
1386 const existing = threadsByProjectKey.get(projectKey);
1387 if (existing) {
1388 existing.push(thread);
1389 } else {
1390 threadsByProjectKey.set(projectKey, [thread]);
1393​
1394 return sortProjectsByActivity(
1395 projects,
1396 sortOrder,
1397 (project) => threadsByProjectKey.get(project.projectKey) ?? [],
1398 (left, right) =>
1399 left.title.localeCompare(right.title) || left.projectKey.localeCompare(right.projectKey),
1400 );
1402​
1403export function sortSidebarV2ProjectGroups<
1404 TProject extends LogicalSidebarProject,
1405 TThread extends ScopedSidebarThread &
1406 Pick<SidebarThreadSummary, "environmentId" | "id" | "lineage">,
1408 projects: readonly TProject[],
1409 threads: readonly TThread[],
1410 sortOrder: SidebarProjectSortOrder,
1411 delegatedUnderParent: ReadonlySet<string>,
1412): TProject[] {
1413 return sortLogicalProjectsForSidebar(
1414 projects,
1415 filterSidebarV2VisibleThreads(threads, null, delegatedUnderParent),
1416 sortOrder,
1417 );
1419​
1420export function sortScopedProjectsForSidebar<
1421 TProject extends ScopedSidebarProject,
1422 TThread extends ScopedSidebarThread,
1424 projects: readonly TProject[],
1425 threads: readonly TThread[],
1426 sortOrder: SidebarProjectSortOrder,
1427): TProject[] {
1428 const scopedKey = (environmentId: string, projectId: string) =>
1429 `${environmentId}\u0000${projectId}`;
1430 const threadsByProject = new Map<string, TThread[]>();
1431 for (const thread of threads) {
1432 if (thread.archivedAt !== null) {
1433 continue;
1435 const key = scopedKey(thread.environmentId, thread.projectId);
1436 const existing = threadsByProject.get(key) ?? [];
1437 existing.push(thread);
1438 threadsByProject.set(key, existing);
1440​
1441 return sortProjectsByActivity(
1442 projects,
1443 sortOrder,
1444 (project) => threadsByProject.get(scopedKey(project.environmentId, project.id)) ?? [],
1445 (left, right) =>
1446 left.title.localeCompare(right.title) ||
1447 left.environmentId.localeCompare(right.environmentId) ||
1448 left.id.localeCompare(right.id),
1449 );