Open History to see the last commit
1import * as React from "react";
2import { defaultAnimateLayoutChanges, type AnimateLayoutChanges } from "@dnd-kit/sortable";
3import {
4 isAtomCommandInterrupted,
5 type AtomCommandResult,
6} from "@t3tools/client-runtime/state/runtime";
7import { hasUnseenThreadCompletion } from "@t3tools/client-runtime/state/thread-read-state";
8import type { ContextMenuItem } from "@t3tools/contracts";
9import type { SidebarProjectSortOrder, SidebarThreadSortOrder } from "@t3tools/contracts/settings";
10import type { AsyncResult } from "effect/unstable/reactivity";
11import { planPinnedReorder } from "@t3tools/client-runtime/state/thread-sort";
12import {
13 getThreadSortTimestamp,
14 resolveSettledThreadTimestamp,
15 sortThreads,
16 toSortableTimestamp,
17 type SettledThreadTimestampInput,
18 type ThreadSortInput,
19} from "../lib/threadSort";
20import type { SidebarThreadSummary, Thread } from "../types";
21import { cn } from "../lib/utils";
22import { isLatestTurnSettled } from "../session-logic";
23
24const THREAD_SELECTION_SAFE_SELECTOR = "[data-thread-item], [data-thread-selection-safe]";
25export const THREAD_JUMP_HINT_SHOW_DELAY_MS = 200;
26// Visible sidebar rows are prewarmed into the thread-detail cache so opening a
27// nearby thread usually reuses an already-hot subscription. Each prewarmed
28// thread holds a live, fully hydrated detail subscription (all messages and
29// activities, growing as agents work) for as long as the row stays visible,
30// so this limit is a direct renderer-heap and server-load multiplier — keep
31// it small; cold opens still render instantly from the cached snapshot.
32const SIDEBAR_THREAD_PREWARM_LIMIT = 3;
33// A small buffer keeps the next few rows warm without leasing every row that
34// content-visibility leaves mounted below the scroll viewport.
35const SIDEBAR_ROW_SUBSCRIPTION_OVERSCAN_PX = 160;
36
37export function useSidebarRowSubscriptionLease(isActive: boolean): {
38 readonly leaseLiveStatus: boolean;
39 readonly rowRef: React.Dispatch<React.SetStateAction<HTMLElement | null>>;
40} {
41 const [row, setRow] = React.useState<HTMLElement | null>(null);
42 const [isNearViewport, setIsNearViewport] = React.useState(isActive);
43
44 React.useEffect(() => {
45 if (isActive) {
46 setIsNearViewport(true);
47 return;
48 }
49 if (row === null) return;
50 if (typeof IntersectionObserver === "undefined") {
51 setIsNearViewport(true);
52 return;
53 }
54
55 const scrollRoot = row.closest<HTMLElement>('[data-slot="scroll-area-viewport"]');
56 const observer = new IntersectionObserver(
57 ([entry]) => setIsNearViewport(entry?.isIntersecting === true),
58 {
59 root: scrollRoot,
60 rootMargin: `${SIDEBAR_ROW_SUBSCRIPTION_OVERSCAN_PX}px 0px`,
61 },
62 );
63 observer.observe(row);
64 return () => observer.disconnect();
65 }, [isActive, row]);
66
67 return {
68 leaseLiveStatus: isActive || isNearViewport,
69 rowRef: setRow,
70 };
71}
72
73// A row keeps the last live value it rendered so a released lease never
74// blanks its badge. The value is bound to `key`, so a different worktree or
75// linked pull request cannot reuse the previous one.
76export function useRetainedValue<T>(key: string | null, value: T | null): T | null {
77 const retained = React.useRef<{ readonly key: string; readonly value: T } | null>(null);
78 if (key !== null && value !== null) {
79 retained.current = { key, value };
80 }
81 if (value !== null) return value;
82 return key !== null && retained.current?.key === key ? retained.current.value : null;
83}
84
85// Sidebar.motion handles ordinary section changes. Sortable transforms own
86// dragging; replaying their committed DOM order would animate the drop twice.
87export const animateSidebarLayoutChanges: AnimateLayoutChanges = (args) =>
88 args.isSorting ? defaultAnimateLayoutChanges(args) : false;
89
90// Rows and section markers share one sortable list. The separators resolve
91// the lifecycle action; Sidebar.drag previews the resulting layout. Pinned
92// and active threads keep the dragged position; settled threads use time
93// order. Snoozed rows can leave the shelf, but dropping into it is not
94// supported because snoozing requires a wake time.
95
96export type SidebarSection = "pinned" | "active" | "snoozed" | "settled";
97
98/** Sortable ids: thread rows use their scoped key; structural items use a
99 colon-free prefix: scoped thread keys always contain a colon. */
100const SIDEBAR_MARKER_PREFIX = "sidebar-marker-";
101
102export type SidebarListMarker =
103 /** The top boundary is also a landing target when there are no pins. */
104 | "pinned-header"
105 /** Stand-in rows so an empty section has somewhere for the gap to open. */
106 | "active-placeholder"
107 | "settled-placeholder"
108 /** The boundary between pinned and active rows. */
109 | "pinned-divider"
110 | "snoozed-header"
111 | "settled-header";
112
113export function sidebarMarkerId(marker: SidebarListMarker): string {
114 return `${SIDEBAR_MARKER_PREFIX}${marker}`;
115}
116
117export type SidebarListItem =
118 | { readonly kind: "thread"; readonly key: string; readonly section: SidebarSection }
119 | { readonly kind: "marker"; readonly marker: SidebarListMarker };
120
121export function sidebarListItemId(item: SidebarListItem): string {
122 return item.kind === "thread" ? item.key : sidebarMarkerId(item.marker);
123}
124
125/** The section a slot belongs to, read off the markers around it: from
126 the top down, everything before the pinned divider is pinned, then the
127 inbox until the snoozed header, the shelf until the settled header,
128 then settled. */
129function sectionAtSidebarSlot(items: readonly SidebarListItem[], index: number): SidebarSection {
130 let section: SidebarSection = "pinned";
131 for (let i = 0; i < index && i < items.length; i += 1) {
132 const item = items[i]!;
133 if (item.kind !== "marker") continue;
134 if (item.marker === "pinned-divider") section = "active";
135 else if (item.marker === "snoozed-header") section = "snoozed";
136 else if (item.marker === "settled-header") section = "settled";
137 }
138 return section;
139}
140
141/** Resolve the destination section and manual order from an arrayMove across
142 * the separators. The snoozed shelf is never a destination. */
143export type SidebarDropTarget = {
144 readonly section: "pinned" | "active" | "settled";
145 readonly pinnedOrder: readonly string[];
146 readonly activeOrder: readonly string[];
147};
148
149export function resolveSidebarDropTarget(
150 items: readonly SidebarListItem[],
151 activeKey: string,
152 overId: string,
153): SidebarDropTarget | null {
154 const activeIndex = items.findIndex((item) => sidebarListItemId(item) === activeKey);
155 const overIndex = items.findIndex((item) => sidebarListItemId(item) === overId);
156 if (activeIndex === -1 || overIndex === -1 || items[activeIndex]?.kind !== "thread") return null;
157 const moved = items.filter((_, index) => index !== activeIndex);
158 moved.splice(overIndex, 0, items[activeIndex]!);
159 const section = sectionAtSidebarSlot(moved, overIndex);
160 if (section === "snoozed") return null;
161 const pinnedOrder: string[] = [];
162 const activeOrder: string[] = [];
163 let currentSection: SidebarSection = "pinned";
164 for (const item of moved) {
165 if (item.kind === "marker") {
166 if (item.marker === "pinned-divider") currentSection = "active";
167 else if (item.marker === "snoozed-header" || item.marker === "settled-header") break;
168 } else if (currentSection === "pinned") pinnedOrder.push(item.key);
169 else activeOrder.push(item.key);
170 }
171 return { section, pinnedOrder, activeOrder };
172}
173
174export type SidebarThreadDropPlan =
175 | { readonly kind: "none" }
176 /** Within the pinned block: the existing key writes. */
177 | {
178 readonly kind: "reorder-pinned";
179 readonly order: readonly string[];
180 readonly assignments: ReadonlyArray<{ readonly id: string; readonly orderKey: string }>;
181 }
182 /** From another section into the pinned block. Fresh pins take `orderKey`
183 on the pin command. `extraAssignments` land afterward, including the
184 moved row when it was already pinned beneath a snooze. */
185 | {
186 readonly kind: "pin";
187 readonly order: readonly string[];
188 readonly orderKey: string | undefined;
189 readonly extraAssignments: ReadonlyArray<{ readonly id: string; readonly orderKey: string }>;
190 }
191 | {
192 readonly kind: "move-active";
193 readonly order: readonly string[];
194 readonly assignments: ReadonlyArray<{ readonly id: string; readonly orderKey: string }>;
195 readonly unpin: boolean;
196 readonly unsettle: boolean;
197 readonly unsnooze: boolean;
198 }
199 | { readonly kind: "settle" };
200
201/** What dropping in `to` does to a thread lifted from `from`, for the badge
202 on the lifted row. Null while reordering inside one section and for the
203 snoozed shelf, which cannot be a drop target. */
204export type SidebarDropVerb = "pin" | "unpin" | "settle" | "unsettle" | "wake";
205
206export function resolveSidebarDropVerb(
207 from: SidebarSection,
208 to: SidebarSection | null,
209): SidebarDropVerb | null {
210 if (to === null || to === from || to === "snoozed") return null;
211 if (to === "pinned") return "pin";
212 if (to === "settled") return "settle";
213 if (from === "pinned") return "unpin";
214 if (from === "settled") return "unsettle";
215 return "wake";
216}
217
218export function planSidebarThreadDrop(input: {
219 readonly activeKey: string;
220 readonly activeSection: SidebarSection;
221 /** Snoozed threads can retain pinning and settlement beneath the shelf. */
222 readonly activePinned?: boolean;
223 readonly activeSettled?: boolean;
224 readonly supportsSettlement?: boolean;
225 readonly target: SidebarDropTarget;
226 /** All pinned keys in displayed order before the drop. */
227 readonly pinnedOrder: readonly string[];
228 readonly pinnedKeysById: ReadonlyMap<string, string | null | undefined>;
229 readonly reorderableKeys?: ReadonlySet<string>;
230 readonly activeOrder: readonly string[];
231 readonly activeKeysById: ReadonlyMap<string, string | null | undefined>;
232 readonly activeReorderableKeys?: ReadonlySet<string>;
233}): SidebarThreadDropPlan {
234 const {
235 activeKey,
236 activeSection,
237 activePinned = activeSection === "pinned",
238 activeSettled = activeSection === "settled",
239 target,
240 pinnedOrder,
241 pinnedKeysById,
242 reorderableKeys,
243 activeOrder,
244 activeKeysById,
245 activeReorderableKeys,
246 } = input;
247 if (input.supportsSettlement === false && (target.section === "settled" || activeSettled)) {
248 return { kind: "none" };
249 }
250 switch (target.section) {
251 case "active": {
252 const order = target.activeOrder;
253 if (
254 activeSection === "active" &&
255 order.length === activeOrder.length &&
256 order.every((key, index) => key === activeOrder[index])
257 ) {
258 return { kind: "none" };
259 }
260 const assignments = planPinnedReorder({
261 orderedIds: order,
262 keysById: activeKeysById,
263 movedId: activeKey,
264 });
265 if (activeReorderableKeys && assignments.some(({ id }) => !activeReorderableKeys.has(id))) {
266 return { kind: "none" };
267 }
268 return {
269 kind: "move-active",
270 order,
271 assignments,
272 unpin: activePinned,
273 unsettle: activeSettled,
274 unsnooze: activeSection === "snoozed",
275 };
276 }
277 case "settled":
278 return activeSection === "settled" ? { kind: "none" } : { kind: "settle" };
279 case "pinned": {
280 const order = target.pinnedOrder;
281 // Dropped back where it started: nothing to write.
282 if (
283 activeSection === "pinned" &&
284 order.length === pinnedOrder.length &&
285 order.every((key, index) => key === pinnedOrder[index])
286 ) {
287 return { kind: "none" };
288 }
289 const assignments = planPinnedReorder({
290 orderedIds: order,
291 keysById: pinnedKeysById,
292 movedId: activeKey,
293 });
294 if (reorderableKeys && assignments.some(({ id }) => !reorderableKeys.has(id))) {
295 return { kind: "none" };
296 }
297 if (activeSection === "pinned") {
298 return assignments.length === 0
299 ? { kind: "none" }
300 : { kind: "reorder-pinned", order, assignments };
301 }
302 return {
303 kind: "pin",
304 order,
305 orderKey: assignments.find((assignment) => assignment.id === activeKey)?.orderKey,
306 extraAssignments: activePinned
307 ? assignments
308 : assignments.filter((assignment) => assignment.id !== activeKey),
309 };
310 }
311 }
312}
313
314/** Project a drop's lifecycle fields before sorting its destination. Reusing
315 the server's re-entry rules keeps the preview in place when events arrive. */
316export function applySidebarThreadDrop<
317 T extends Pick<
318 SidebarThreadSummary,
319 | "pinnedAt"
320 | "pinOrderKey"
321 | "activeOrderKey"
322 | "snoozedAt"
323 | "snoozedUntil"
324 | "settledAt"
325 | "settledOverride"
326 | "unsettledAt"
327 >,
328>(thread: T, section: "pinned" | "active" | "settled", now: string, orderKey?: string): T {
329 const wasSettled = thread.settledOverride === "settled";
330 const awake = { ...thread, snoozedAt: null, snoozedUntil: null };
331 if (section === "settled") {
332 return {
333 ...awake,
334 pinnedAt: null,
335 pinOrderKey: null,
336 activeOrderKey: null,
337 settledOverride: "settled",
338 settledAt: wasSettled ? (thread.settledAt ?? now) : now,
339 unsettledAt: null,
340 };
341 }
342 const resumed = wasSettled
343 ? { ...awake, settledOverride: "active" as const, settledAt: null, unsettledAt: now }
344 : awake;
345 return {
346 ...resumed,
347 pinnedAt: section === "pinned" ? (thread.pinnedAt ?? now) : null,
348 pinOrderKey: section === "pinned" ? (orderKey ?? thread.pinOrderKey) : null,
349 ...(section === "active" && orderKey !== undefined ? { activeOrderKey: orderKey } : {}),
350 };
351}
352
353type SidebarProject = {
354 id: string;
355 title: string;
356 createdAt?: string | undefined;
357 updatedAt?: string | undefined;
358};
359
360type ScopedSidebarProject = SidebarProject & {
361 environmentId: string;
362};
363
364type ScopedSidebarThread = ThreadSortInput & {
365 environmentId: string;
366 projectId: string;
367 archivedAt: string | null;
368};
369
370type LogicalSidebarProject = SidebarProject & {
371 projectKey: string;
372 memberProjectRefs: readonly {
373 environmentId: string;
374 projectId: string;
375 }[];
376};
377
378export type ThreadTraversalDirection = "previous" | "next";
379
380/**
381 * Shared-worktree checks must exclude only successful deletions, never the
382 * whole batch. A null result skips an entry that the caller can no longer find.
383 */
384export async function deleteSelectedThreadEntries<
385 TEntry extends { readonly threadKey: string },
386>(input: {
387 entries: readonly TEntry[];
388 delete: (
389 entry: TEntry,
390 deletedThreadKeys: ReadonlySet<string>,
391 ) => Promise<AtomCommandResult<unknown, unknown> | null>;
392}) {
393 const deletedThreadKeys = new Set<string>();
394 let firstFailure: AsyncResult.Failure<unknown, unknown> | null = null;
395
396 for (const entry of input.entries) {
397 const result = await input.delete(entry, deletedThreadKeys);
398 if (result === null) continue;
399 if (result._tag === "Failure") {
400 if (isAtomCommandInterrupted(result)) break;
401 firstFailure ??= result;
402 continue;
403 }
404 deletedThreadKeys.add(entry.threadKey);
405 }
406
407 return { deletedThreadKeys, firstFailure };
408}
409
410export async function archiveSelectedThreadEntries<
411 TEntry extends { readonly threadKey: string },
412 TResult extends { readonly _tag: "Success" | "Failure" },
413>(input: {
414 entries: readonly TEntry[];
415 archive: (entry: TEntry, onArchived: () => void) => Promise<TResult>;
416}): Promise<{
417 archivedThreadKeys: readonly string[];
418 mutationFailure: Extract<TResult, { readonly _tag: "Failure" }> | null;
419 followupFailures: readonly Extract<TResult, { readonly _tag: "Failure" }>[];
420}> {
421 const archivedThreadKeys: string[] = [];
422 const followupFailures: Extract<TResult, { readonly _tag: "Failure" }>[] = [];
423
424 for (const entry of input.entries) {
425 let didArchive = false;
426 const result = await input.archive(entry, () => {
427 didArchive = true;
428 });
429 if (didArchive || result._tag === "Success") {
430 archivedThreadKeys.push(entry.threadKey);
431 }
432 if (result._tag === "Success") continue;
433 const failure = result as Extract<TResult, { readonly _tag: "Failure" }>;
434 if (didArchive) {
435 followupFailures.push(failure);
436 continue;
437 }
438 return { archivedThreadKeys, mutationFailure: failure, followupFailures };
439 }
440
441 return { archivedThreadKeys, mutationFailure: null, followupFailures };
442}
443
444export function buildMultiSelectThreadContextMenuItems(input: {
445 count: number;
446 hasRunningThread: boolean;
447}): readonly ContextMenuItem<"mark-unread" | "archive" | "delete">[] {
448 return [
449 { id: "mark-unread", label: `Mark unread (${input.count})` },
450 {
451 id: "archive",
452 label: `Archive (${input.count})`,
453 disabled: input.hasRunningThread,
454 },
455 { id: "delete", label: `Delete (${input.count})`, destructive: true },
456 ];
457}
458
459export function buildBulkTitleRegenerationContextMenuItem(input: {
460 supportedCount: number;
461 actionableCount: number;
462}): ContextMenuItem<"regenerate-title"> | null {
463 if (input.supportedCount === 0) return null;
464 if (input.actionableCount === 0) {
465 return {
466 id: "regenerate-title",
467 label: `Regenerating… (${input.supportedCount})`,
468 disabled: true,
469 };
470 }
471 return {
472 id: "regenerate-title",
473 label: `Regenerate titles (${input.actionableCount})`,
474 };
475}
476
477/**
478 * Bulk unpin follows the same "count only what the action will touch" rule
479 * as title regeneration: on a mixed selection the label counts the pinned
480 * rows alone, and the item disappears when nothing selected is pinned.
481 */
482export function buildBulkUnpinContextMenuItem(input: {
483 pinnedCount: number;
484}): ContextMenuItem<"unpin"> | null {
485 if (input.pinnedCount === 0) return null;
486 return { id: "unpin", label: `Unpin (${input.pinnedCount})` };
487}
488
489export interface ThreadStatusPill {
490 label:
491 | "Working"
492 | "Monitoring"
493 | "Connecting"
494 | "Completed"
495 | "Pending Approval"
496 | "Awaiting Input"
497 | "Plan Ready";
498 colorClass: string;
499 dotClass: string;
500 pulse: boolean;
501}
502
503// Rollup order mirrors the per-thread resolver exactly: attention states,
504// then active work, then the actionable plan prompt, then passive
505// monitoring. A Monitoring sibling must never hide a Plan Ready thread.
506const THREAD_STATUS_PRIORITY: Record<ThreadStatusPill["label"], number> = {
507 "Pending Approval": 6,
508 "Awaiting Input": 5,
509 Working: 4,
510 Connecting: 4,
511 "Plan Ready": 3,
512 Monitoring: 2,
513 Completed: 1,
514};
515
516type ThreadStatusInput = Pick<
517 SidebarThreadSummary,
518 | "hasActionableProposedPlan"
519 | "hasPendingApprovals"
520 | "hasPendingUserInput"
521 | "interactionMode"
522 | "latestTurn"
523 | "session"
524 | "backgroundLiveness"
525> & {
526 lastVisitedAt?: string | undefined;
527};
528
529export interface ThreadJumpHintVisibilityController {
530 sync: (shouldShow: boolean) => void;
531 dispose: () => void;
532}
533
534export function createThreadJumpHintVisibilityController(input: {
535 delayMs: number;
536 onVisibilityChange: (visible: boolean) => void;
537 setTimeoutFn?: typeof globalThis.setTimeout;
538 clearTimeoutFn?: typeof globalThis.clearTimeout;
539}): ThreadJumpHintVisibilityController {
540 const setTimeoutFn = input.setTimeoutFn ?? globalThis.setTimeout;
541 const clearTimeoutFn = input.clearTimeoutFn ?? globalThis.clearTimeout;
542 let isVisible = false;
543 let timeoutId: NodeJS.Timeout | null = null;
544
545 const clearPendingShow = () => {
546 if (timeoutId === null) {
547 return;
548 }
549 clearTimeoutFn(timeoutId);
550 timeoutId = null;
551 };
552
553 return {
554 sync: (shouldShow) => {
555 if (!shouldShow) {
556 clearPendingShow();
557 if (isVisible) {
558 isVisible = false;
559 input.onVisibilityChange(false);
560 }
561 return;
562 }
563
564 if (isVisible || timeoutId !== null) {
565 return;
566 }
567
568 timeoutId = setTimeoutFn(() => {
569 timeoutId = null;
570 isVisible = true;
571 input.onVisibilityChange(true);
572 }, input.delayMs);
573 },
574 dispose: () => {
575 clearPendingShow();
576 },
577 };
578}
579
580export function useThreadJumpHintVisibility(): {
581 showThreadJumpHints: boolean;
582 updateThreadJumpHintsVisibility: (shouldShow: boolean) => void;
583} {
584 const [showThreadJumpHints, setShowThreadJumpHints] = React.useState(false);
585 const controllerRef = React.useRef<ThreadJumpHintVisibilityController | null>(null);
586
587 React.useEffect(() => {
588 const controller = createThreadJumpHintVisibilityController({
589 delayMs: THREAD_JUMP_HINT_SHOW_DELAY_MS,
590 onVisibilityChange: (visible) => {
591 setShowThreadJumpHints(visible);
592 },
593 setTimeoutFn: window.setTimeout.bind(window),
594 clearTimeoutFn: window.clearTimeout.bind(window),
595 });
596 controllerRef.current = controller;
597
598 return () => {
599 controller.dispose();
600 controllerRef.current = null;
601 };
602 }, []);
603
604 const updateThreadJumpHintsVisibility = React.useCallback((shouldShow: boolean) => {
605 controllerRef.current?.sync(shouldShow);
606 }, []);
607
608 return {
609 showThreadJumpHints,
610 updateThreadJumpHintsVisibility,
611 };
612}
613
614export function shouldClearThreadSelectionOnMouseDown(target: HTMLElement | null): boolean {
615 if (target === null) return true;
616 return !target.closest(THREAD_SELECTION_SAFE_SELECTOR);
617}
618
619// A double-click dispatches two `click` events before `dblclick`: the first has
620// `detail === 1`, the second `detail === 2`. The second click must not run the
621// row's single-click navigation, otherwise double-click-to-rename would also
622// navigate. `MouseEvent.detail` is 0 for synthetic/keyboard activations, which
623// still count as a normal single activation.
624export function isTrailingDoubleClick(detail: number): boolean {
625 return detail > 1;
626}
627
628function nodeClosest(node: object | null, selector: string): unknown {
629 if (node === null || !("closest" in node) || typeof node.closest !== "function") return null;
630 return node.closest(selector);
631}
632
633/** Clicks on a nested link keep the link's meaning. The row must not treat them as multi-select. */
634export function isSidebarNestedLinkClick(target: EventTarget | null): boolean {
635 if (target == null || typeof target !== "object") return false;
636 if (nodeClosest(target, "a[href]") !== null) return true;
637 const parent =
638 "parentElement" in target &&
639 target.parentElement !== null &&
640 typeof target.parentElement === "object"
641 ? target.parentElement
642 : null;
643 return nodeClosest(parent, "a[href]") !== null;
644}
645
646// Shift+click on the new thread button creates directly in the current
647// project, skipping the command palette's project picker. With a single
648// project there is nothing to pick, so a plain click already creates
649// immediately and the modifier changes nothing.
650export function shouldCreateNewThreadInCurrentProject(
651 shiftKey: boolean,
652 projectGroupCount: number,
653): boolean {
654 return shiftKey || projectGroupCount <= 1;
655}
656
657export function orderItemsByPreferredIds<TItem, TId>(input: {
658 items: readonly TItem[];
659 preferredIds: readonly TId[];
660 getId: (item: TItem) => TId;
661 getPreferenceIds?: (item: TItem) => readonly TId[];
662}): TItem[] {
663 const { getId, getPreferenceIds, items, preferredIds } = input;
664 if (preferredIds.length === 0) {
665 return [...items];
666 }
667
668 const indexesByPreferenceId = new Map<TId, number[]>();
669 for (const [index, item] of items.entries()) {
670 const preferenceIds = getPreferenceIds?.(item) ?? [getId(item)];
671 for (const preferenceId of new Set(preferenceIds)) {
672 const indexes = indexesByPreferenceId.get(preferenceId);
673 if (indexes) {
674 indexes.push(index);
675 } else {
676 indexesByPreferenceId.set(preferenceId, [index]);
677 }
678 }
679 }
680
681 const emittedIndexes = new Set<number>();
682 const ordered = preferredIds.flatMap((id) => {
683 const index = indexesByPreferenceId
684 .get(id)
685 ?.find((candidate) => !emittedIndexes.has(candidate));
686 if (index === undefined) {
687 return [];
688 }
689 emittedIndexes.add(index);
690 return [items[index]!];
691 });
692 const remaining = items.filter((_, index) => !emittedIndexes.has(index));
693 return [...ordered, ...remaining];
694}
695
696export function getSidebarThreadIdsToPrewarm<TThreadId>(
697 visibleThreadIds: readonly TThreadId[],
698 limit = SIDEBAR_THREAD_PREWARM_LIMIT,
699): TThreadId[] {
700 return visibleThreadIds.slice(0, Math.max(0, limit));
701}
702
703export function resolveAdjacentThreadId<T>(input: {
704 threadIds: readonly T[];
705 currentThreadId: T | null;
706 direction: ThreadTraversalDirection;
707}): T | null {
708 const { currentThreadId, direction, threadIds } = input;
709
710 if (threadIds.length === 0) {
711 return null;
712 }
713
714 if (currentThreadId === null) {
715 return direction === "previous" ? (threadIds.at(-1) ?? null) : (threadIds[0] ?? null);
716 }
717
718 const currentIndex = threadIds.indexOf(currentThreadId);
719 if (currentIndex === -1) {
720 return null;
721 }
722
723 if (direction === "previous") {
724 return currentIndex > 0 ? (threadIds[currentIndex - 1] ?? null) : null;
725 }
726
727 return currentIndex < threadIds.length - 1 ? (threadIds[currentIndex + 1] ?? null) : null;
728}
729
730export function isContextMenuPointerDown(input: {
731 button: number;
732 ctrlKey: boolean;
733 isMac: boolean;
734}): boolean {
735 if (input.button === 2) return true;
736 return input.isMac && input.button === 0 && input.ctrlKey;
737}
738
739export function resolveThreadRowClassName(input: {
740 isActive: boolean;
741 isSelected: boolean;
742}): string {
743 const baseClassName =
744 "h-8 w-full translate-x-0 cursor-pointer justify-start rounded-md px-2 text-left text-sm select-none focus-visible:ring-1 focus-visible:ring-inset focus-visible:ring-ring";
745
746 if (input.isSelected && input.isActive) {
747 return cn(
748 baseClassName,
749 "bg-sidebar-row-active text-sidebar-foreground font-medium hover:bg-sidebar-row-active hover:text-sidebar-foreground",
750 );
751 }
752
753 if (input.isSelected) {
754 return cn(
755 baseClassName,
756 "bg-sidebar-row-selected text-sidebar-foreground hover:bg-sidebar-row-active hover:text-sidebar-foreground",
757 );
758 }
759
760 if (input.isActive) {
761 return cn(
762 baseClassName,
763 "bg-sidebar-row-active text-sidebar-foreground font-medium hover:bg-sidebar-row-active hover:text-sidebar-foreground",
764 );
765 }
766
767 return cn(
768 baseClassName,
769 "text-sidebar-muted-foreground/80 hover:bg-sidebar-row-hover hover:text-sidebar-foreground",
770 );
771}
772
773// ── Sidebar thread status model ─────────────────────────────────────
774// Five visual states, three colors: color is reserved for "act now"
775// (approval), "in motion" (working), and "broken" (failed). Ready is the
776// unlabeled resting state — the agent stopped and is waiting on the user,
777// whether it finished, asked a question, or proposed a plan.
778// Unread completion is tracked separately: it describes whether a ready
779// thread needs attention, not what the thread is currently doing.
780export type SidebarThreadStatus =
781 | "approval"
782 | "input"
783 | "working"
784 | "monitoring"
785 | "failed"
786 | "ready";
787
788export function shouldRecedeSidebarThread(input: {
789 status: SidebarThreadStatus;
790 isUnread: boolean;
791 isWoke: boolean;
792 isActive: boolean;
793 isSelected: boolean;
794}): boolean {
795 if (input.isActive || input.isSelected) return false;
796 if (input.status === "working" || input.status === "monitoring") return true;
797 if (input.status === "ready" || input.status === "approval" || input.status === "input") {
798 return !input.isUnread && !input.isWoke;
799 }
800 return false;
801}
802
803type SidebarThreadStatusInput = Pick<
804 SidebarThreadSummary,
805 "hasPendingApprovals" | "hasPendingUserInput" | "session" | "backgroundLiveness"
806>;
807
808export function resolveSidebarThreadStatus(thread: SidebarThreadStatusInput): SidebarThreadStatus {
809 if (thread.hasPendingApprovals) {
810 return "approval";
811 }
812 if (thread.hasPendingUserInput) {
813 return "input";
814 }
815 if (thread.session?.status === "running" || thread.session?.status === "starting") {
816 return "working";
817 }
818 // A failed session outranks lingering background liveness: the user must
819 // see the failure, not a stale Working (review finding).
820 if (thread.session?.status === "error") {
821 return "failed";
822 }
823 // Background work outlives the turn: fleets read as working; monitoring
824 // only when watch loops are the sole live work.
825 if (thread.backgroundLiveness === "working") {
826 return "working";
827 }
828 if (thread.backgroundLiveness === "monitoring") {
829 return "monitoring";
830 }
831 return "ready";
832}
833
834/** First VALID timestamp wins: `a ?? b` falls through on null, but a present-
835 yet-malformed string must also fall through to the next candidate rather
836 than sink the row to the epoch. */
837export function firstValidTimestampMs(
838 ...candidates: ReadonlyArray<string | null | undefined>
839): number {
840 for (const candidate of candidates) {
841 if (candidate == null) continue;
842 const parsed = Date.parse(candidate);
843 if (!Number.isNaN(parsed)) return parsed;
844 }
845 return 0;
846}
847
848/** String twin of firstValidTimestampMs for callers that need the ISO string
849 (display labels, tick anchors) rather than epoch ms. */
850function firstValidTimestamp(
851 ...candidates: ReadonlyArray<string | null | undefined>
852): string | null {
853 for (const candidate of candidates) {
854 if (candidate == null) continue;
855 if (!Number.isNaN(Date.parse(candidate))) return candidate;
856 }
857 return null;
858}
859
860export { sortActiveThreadsByOrderKey as sortThreadsForSidebar } from "@t3tools/client-runtime/state/thread-sort";
861
862// Pinned-reorder key math and the keyed sort live in client-runtime
863// (state/thread-sort) so web and mobile compute identical pinned orders.
864export { pinOrderKeyBetween, planPinnedReorder } from "@t3tools/client-runtime/state/thread-sort";
865export { sortPinnedThreadsByOrderKey as sortPinnedThreadsForSidebar } from "@t3tools/client-runtime/state/thread-sort";
866
867/**
868 * Search the already-ordered sidebar thread collection by title only.
869 * Keeping the input order means lifecycle ordering (active, snoozed, settled)
870 * remains stable while the user narrows the list.
871 */
872export function searchSidebarThreadsByTitle<T extends { readonly title: string }>(
873 threads: readonly T[],
874 query: string,
875): T[] {
876 const normalizedQuery = query.trim().toLowerCase();
877 if (normalizedQuery.length === 0) return [];
878 return threads.filter((thread) => thread.title.toLowerCase().includes(normalizedQuery));
879}
880
881export function filterSidebarProjectScopeItems<TItem extends { readonly value: string }>(input: {
882 items: readonly TItem[];
883 activeScopeKey: string | null;
884 query: string;
885 matches: (item: TItem, query: string) => boolean;
886}): readonly TItem[] {
887 const projectItems = input.items.filter((item) => item.value !== "all");
888 const query = input.query.trim();
889 if (query.length > 0) {
890 return projectItems.filter((item) => input.matches(item, query));
891 }
892 return input.activeScopeKey === null ? projectItems : input.items;
893}
894
895export interface SidebarProjectScopeMenuState {
896 readonly open: boolean;
897 readonly query: string;
898}
899
900export type SidebarProjectScopeMenuAction =
901 | { readonly type: "query-changed"; readonly query: string }
902 | { readonly type: "open-changed"; readonly open: boolean }
903 | { readonly type: "project-settings-opened" };
904
905export function reduceSidebarProjectScopeMenuState(
906 state: SidebarProjectScopeMenuState,
907 action: SidebarProjectScopeMenuAction,
908): SidebarProjectScopeMenuState {
909 switch (action.type) {
910 case "query-changed":
911 return { ...state, query: action.query };
912 case "open-changed":
913 return { open: action.open, query: "" };
914 case "project-settings-opened":
915 return { open: false, query: "" };
916 }
917}
918
919// Settled rows are history, so they order by when the work ENDED, not when
920// the thread was created or last touched.
921export function sortSettledThreadsForSidebar<
922 T extends SettledThreadTimestampInput & { readonly id: string },
923>(threads: readonly T[]): T[] {
924 const timestampMs = (thread: T) => {
925 const timestamp = resolveSettledThreadTimestamp(thread);
926 return timestamp === null ? 0 : Date.parse(timestamp);
927 };
928 return [...threads].toSorted(
929 (left, right) => timestampMs(right) - timestampMs(left) || left.id.localeCompare(right.id),
930 );
931}
932
933/** The timestamp a working thread's elapsed label counts from: the running
934 turn's start (request time until adoption), falling back to the session's
935 last transition when the turn projection lags behind. Malformed
936 timestamps fall through to the next candidate, not just missing ones. */
937export function resolveWorkingStartedAt(
938 thread: Pick<SidebarThreadSummary, "latestTurn" | "session">,
939): string | null {
940 const turn = thread.latestTurn;
941 if (turn && turn.completedAt === null) {
942 return firstValidTimestamp(turn.startedAt, turn.requestedAt, thread.session?.updatedAt);
943 }
944 return firstValidTimestamp(thread.session?.updatedAt);
945}
946
947export function formatWorkingDurationLabel(elapsedMs: number): string {
948 const seconds = Number.isFinite(elapsedMs) ? Math.max(0, Math.floor(elapsedMs / 1000)) : 0;
949 if (seconds < 60) return `${seconds}s`;
950 const minutes = Math.floor(seconds / 60);
951 if (minutes < 60) return `${minutes}m`;
952 return `${Math.floor(minutes / 60)}h ${minutes % 60}m`;
953}
954
955export function resolveThreadStatusPill(input: {
956 thread: ThreadStatusInput;
957}): ThreadStatusPill | null {
958 const { thread } = input;
959
960 if (thread.hasPendingApprovals) {
961 return {
962 label: "Pending Approval",
963 colorClass: "text-amber-600 dark:text-amber-300/90",
964 dotClass: "bg-amber-500 dark:bg-amber-300/90",
965 pulse: false,
966 };
967 }
968
969 if (thread.hasPendingUserInput) {
970 return {
971 label: "Awaiting Input",
972 colorClass: "text-indigo-600 dark:text-indigo-300/90",
973 dotClass: "bg-indigo-500 dark:bg-indigo-300/90",
974 pulse: false,
975 };
976 }
977
978 if (thread.session?.status === "running") {
979 return {
980 label: "Working",
981 colorClass: "text-sky-600 dark:text-sky-300/80",
982 dotClass: "bg-sky-500 dark:bg-sky-300/80",
983 pulse: true,
984 };
985 }
986
987 if (thread.session?.status === "starting") {
988 return {
989 label: "Connecting",
990 colorClass: "text-sky-600 dark:text-sky-300/80",
991 dotClass: "bg-sky-500 dark:bg-sky-300/80",
992 pulse: true,
993 };
994 }
995
996 // An actionable plan prompt outranks lingering background work: it needs
997 // the user's decision, while liveness merely reports (review finding).
998 const hasPlanReadyPrompt =
999 !thread.hasPendingUserInput &&
1000 thread.interactionMode === "plan" &&
1001 isLatestTurnSettled(thread.latestTurn, thread.session) &&
1002 thread.hasActionableProposedPlan;
1003 if (hasPlanReadyPrompt) {
1004 return {
1005 label: "Plan Ready",
1006 colorClass: "text-violet-600 dark:text-violet-300/90",
1007 dotClass: "bg-violet-500 dark:bg-violet-300/90",
1008 pulse: false,
1009 };
1010 }
1011
1012 // The turn can settle while native background work runs on. Subagent and
1013 // workflow fleets read as plain Working; Monitoring is reserved for watch
1014 // loops (a parent agent babysitting a PR, tailing checks) with no other
1015 // live work. Same recede treatment as Working per inbox-zero.
1016 if (thread.backgroundLiveness === "working") {
1017 return {
1018 label: "Working",
1019 colorClass: "text-sky-600 dark:text-sky-300/80",
1020 dotClass: "bg-sky-500 dark:bg-sky-300/80",
1021 pulse: true,
1022 };
1023 }
1024
1025 if (thread.backgroundLiveness === "monitoring") {
1026 return {
1027 label: "Monitoring",
1028 colorClass: "text-sky-600 dark:text-sky-300/80",
1029 dotClass: "bg-sky-500 dark:bg-sky-300/80",
1030 pulse: false,
1031 };
1032 }
1033
1034 if (hasUnseenThreadCompletion(thread, thread.lastVisitedAt)) {
1035 return {
1036 label: "Completed",
1037 colorClass: "text-emerald-600 dark:text-emerald-300/90",
1038 dotClass: "bg-emerald-500 dark:bg-emerald-300/90",
1039 pulse: false,
1040 };
1041 }
1042
1043 return null;
1044}
1045
1046export function resolveProjectStatusIndicator(
1047 statuses: ReadonlyArray<ThreadStatusPill | null>,
1048): ThreadStatusPill | null {
1049 let highestPriorityStatus: ThreadStatusPill | null = null;
1050
1051 for (const status of statuses) {
1052 if (status === null) continue;
1053 if (
1054 highestPriorityStatus === null ||
1055 THREAD_STATUS_PRIORITY[status.label] > THREAD_STATUS_PRIORITY[highestPriorityStatus.label]
1056 ) {
1057 highestPriorityStatus = status;
1058 }
1059 }
1060
1061 return highestPriorityStatus;
1062}
1063
1064export function getFallbackThreadIdAfterDelete<
1065 T extends Pick<Thread, "id" | "projectId" | "createdAt" | "updatedAt"> & ThreadSortInput,
1066>(input: {
1067 threads: readonly T[];
1068 deletedThreadId: T["id"];
1069 sortOrder: SidebarThreadSortOrder;
1070 deletedThreadIds?: ReadonlySet<T["id"]>;
1071}): T["id"] | null {
1072 const { deletedThreadId, deletedThreadIds, sortOrder, threads } = input;
1073 const deletedThread = threads.find((thread) => thread.id === deletedThreadId);
1074 if (!deletedThread) {
1075 return null;
1076 }
1077
1078 return (
1079 sortThreads(
1080 threads.filter(
1081 (thread) =>
1082 thread.projectId === deletedThread.projectId &&
1083 thread.id !== deletedThreadId &&
1084 !deletedThreadIds?.has(thread.id),
1085 ),
1086 sortOrder,
1087 )[0]?.id ?? null
1088 );
1089}
1090export function getProjectSortTimestamp(
1091 project: SidebarProject,
1092 projectThreads: readonly ThreadSortInput[],
1093 sortOrder: Exclude<SidebarProjectSortOrder, "manual">,
1094): number {
1095 if (projectThreads.length > 0) {
1096 return projectThreads.reduce(
1097 (latest, thread) => Math.max(latest, getThreadSortTimestamp(thread, sortOrder)),
1098 Number.NEGATIVE_INFINITY,
1099 );
1100 }
1101
1102 if (sortOrder === "created_at") {
1103 return toSortableTimestamp(project.createdAt) ?? Number.NEGATIVE_INFINITY;
1104 }
1105 return toSortableTimestamp(project.updatedAt ?? project.createdAt) ?? Number.NEGATIVE_INFINITY;
1106}
1107
1108function sortProjectsByActivity<TProject extends SidebarProject>(
1109 projects: readonly TProject[],
1110 sortOrder: SidebarProjectSortOrder,
1111 getProjectThreads: (project: TProject) => readonly ThreadSortInput[],
1112 compareTies: (left: TProject, right: TProject) => number,
1113): TProject[] {
1114 if (sortOrder === "manual") {
1115 return [...projects];
1116 }
1117
1118 return [...projects].toSorted((left, right) => {
1119 const rightTimestamp = getProjectSortTimestamp(right, getProjectThreads(right), sortOrder);
1120 const leftTimestamp = getProjectSortTimestamp(left, getProjectThreads(left), sortOrder);
1121 const byTimestamp =
1122 rightTimestamp === leftTimestamp ? 0 : rightTimestamp > leftTimestamp ? 1 : -1;
1123 return byTimestamp || compareTies(left, right);
1124 });
1125}
1126
1127export function sortProjectsForSidebar<
1128 TProject extends SidebarProject,
1129 TThread extends Pick<Thread, "projectId" | "createdAt" | "updatedAt"> & ThreadSortInput,
1130>(
1131 projects: readonly TProject[],
1132 threads: readonly TThread[],
1133 sortOrder: SidebarProjectSortOrder,
1134): TProject[] {
1135 const threadsByProjectId = new Map<string, TThread[]>();
1136 for (const thread of threads) {
1137 const existing = threadsByProjectId.get(thread.projectId) ?? [];
1138 existing.push(thread);
1139 threadsByProjectId.set(thread.projectId, existing);
1140 }
1141
1142 return sortProjectsByActivity(
1143 projects,
1144 sortOrder,
1145 (project) => threadsByProjectId.get(project.id) ?? [],
1146 (left, right) => left.title.localeCompare(right.title) || left.id.localeCompare(right.id),
1147 );
1148}
1149
1150export function sortLogicalProjectsForSidebar<
1151 TProject extends LogicalSidebarProject,
1152 TThread extends ScopedSidebarThread,
1153>(
1154 projects: readonly TProject[],
1155 threads: readonly TThread[],
1156 sortOrder: SidebarProjectSortOrder,
1157): TProject[] {
1158 const groupKeyByProjectRef = new Map(
1159 projects.flatMap((project) =>
1160 project.memberProjectRefs.map(
1161 (projectRef) =>
1162 [`${projectRef.environmentId}\0${projectRef.projectId}`, project.projectKey] as const,
1163 ),
1164 ),
1165 );
1166 const threadsByProjectKey = new Map<string, TThread[]>();
1167 for (const thread of threads) {
1168 if (thread.archivedAt !== null) continue;
1169 const projectKey = groupKeyByProjectRef.get(`${thread.environmentId}\0${thread.projectId}`);
1170 if (!projectKey) continue;
1171 const existing = threadsByProjectKey.get(projectKey);
1172 if (existing) {
1173 existing.push(thread);
1174 } else {
1175 threadsByProjectKey.set(projectKey, [thread]);
1176 }
1177 }
1178
1179 return sortProjectsByActivity(
1180 projects,
1181 sortOrder,
1182 (project) => threadsByProjectKey.get(project.projectKey) ?? [],
1183 (left, right) =>
1184 left.title.localeCompare(right.title) || left.projectKey.localeCompare(right.projectKey),
1185 );
1186}
1187
1188/**
1189 * Sorts the cross-environment project collection used by landing surfaces.
1190 * Project ids are only unique within an environment, and archived threads
1191 * must not make a project appear recently active.
1192 */
1193export function sortScopedProjectsForSidebar<
1194 TProject extends ScopedSidebarProject,
1195 TThread extends ScopedSidebarThread,
1196>(
1197 projects: readonly TProject[],
1198 threads: readonly TThread[],
1199 sortOrder: SidebarProjectSortOrder,
1200): TProject[] {
1201 const scopedKey = (environmentId: string, projectId: string) =>
1202 `${environmentId}\u0000${projectId}`;
1203 const threadsByProject = new Map<string, TThread[]>();
1204 for (const thread of threads) {
1205 if (thread.archivedAt !== null) {
1206 continue;
1207 }
1208 const key = scopedKey(thread.environmentId, thread.projectId);
1209 const existing = threadsByProject.get(key) ?? [];
1210 existing.push(thread);
1211 threadsByProject.set(key, existing);
1212 }
1213
1214 return sortProjectsByActivity(
1215 projects,
1216 sortOrder,
1217 (project) => threadsByProject.get(scopedKey(project.environmentId, project.id)) ?? [],
1218 (left, right) =>
1219 left.title.localeCompare(right.title) ||
1220 left.environmentId.localeCompare(right.environmentId) ||
1221 left.id.localeCompare(right.id),
1222 );
1223}