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

Sidebar.logic.ts

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