Open History to see the last commit
1import { threadPullRequestSearchTerms } from "@t3tools/shared/threadPullRequests";
2import * as React from "react";
3import { defaultAnimateLayoutChanges, type AnimateLayoutChanges } from "@dnd-kit/sortable";
4import {
5 isAtomCommandInterrupted,
6 type AtomCommandResult,
7} from "@t3tools/client-runtime/state/runtime";
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 hasUnseenCompletion(thread: ThreadStatusInput): boolean {
615 if (!thread.latestTurn?.completedAt) return false;
616 const completedAt = Date.parse(thread.latestTurn.completedAt);
617 if (Number.isNaN(completedAt)) return false;
618 if (!thread.lastVisitedAt) return false;
619
620 const lastVisitedAt = Date.parse(thread.lastVisitedAt);
621 if (Number.isNaN(lastVisitedAt)) return true;
622 return completedAt > lastVisitedAt;
623}
624
625export function shouldClearThreadSelectionOnMouseDown(target: HTMLElement | null): boolean {
626 if (target === null) return true;
627 return !target.closest(THREAD_SELECTION_SAFE_SELECTOR);
628}
629
630// A double-click dispatches two `click` events before `dblclick`: the first has
631// `detail === 1`, the second `detail === 2`. The second click must not run the
632// row's single-click navigation, otherwise double-click-to-rename would also
633// navigate. `MouseEvent.detail` is 0 for synthetic/keyboard activations, which
634// still count as a normal single activation.
635export function isTrailingDoubleClick(detail: number): boolean {
636 return detail > 1;
637}
638
639function nodeClosest(node: object | null, selector: string): unknown {
640 if (node === null || !("closest" in node) || typeof node.closest !== "function") return null;
641 return node.closest(selector);
642}
643
644/** Clicks on a nested link keep the link's meaning. The row must not treat them as multi-select. */
645export function isSidebarNestedLinkClick(target: EventTarget | null): boolean {
646 if (target == null || typeof target !== "object") return false;
647 if (nodeClosest(target, "a[href]") !== null) return true;
648 const parent =
649 "parentElement" in target &&
650 target.parentElement !== null &&
651 typeof target.parentElement === "object"
652 ? target.parentElement
653 : null;
654 return nodeClosest(parent, "a[href]") !== null;
655}
656
657// Shift+click on the new thread button creates directly in the current
658// project, skipping the command palette's project picker. With a single
659// project there is nothing to pick, so a plain click already creates
660// immediately and the modifier changes nothing.
661export function shouldCreateNewThreadInCurrentProject(
662 shiftKey: boolean,
663 projectGroupCount: number,
664): boolean {
665 return shiftKey || projectGroupCount <= 1;
666}
667
668export function orderItemsByPreferredIds<TItem, TId>(input: {
669 items: readonly TItem[];
670 preferredIds: readonly TId[];
671 getId: (item: TItem) => TId;
672 getPreferenceIds?: (item: TItem) => readonly TId[];
673}): TItem[] {
674 const { getId, getPreferenceIds, items, preferredIds } = input;
675 if (preferredIds.length === 0) {
676 return [...items];
677 }
678
679 const indexesByPreferenceId = new Map<TId, number[]>();
680 for (const [index, item] of items.entries()) {
681 const preferenceIds = getPreferenceIds?.(item) ?? [getId(item)];
682 for (const preferenceId of new Set(preferenceIds)) {
683 const indexes = indexesByPreferenceId.get(preferenceId);
684 if (indexes) {
685 indexes.push(index);
686 } else {
687 indexesByPreferenceId.set(preferenceId, [index]);
688 }
689 }
690 }
691
692 const emittedIndexes = new Set<number>();
693 const ordered = preferredIds.flatMap((id) => {
694 const index = indexesByPreferenceId
695 .get(id)
696 ?.find((candidate) => !emittedIndexes.has(candidate));
697 if (index === undefined) {
698 return [];
699 }
700 emittedIndexes.add(index);
701 return [items[index]!];
702 });
703 const remaining = items.filter((_, index) => !emittedIndexes.has(index));
704 return [...ordered, ...remaining];
705}
706
707export function getSidebarThreadIdsToPrewarm<TThreadId>(
708 visibleThreadIds: readonly TThreadId[],
709 limit = SIDEBAR_THREAD_PREWARM_LIMIT,
710): TThreadId[] {
711 return visibleThreadIds.slice(0, Math.max(0, limit));
712}
713
714export function resolveAdjacentThreadId<T>(input: {
715 threadIds: readonly T[];
716 currentThreadId: T | null;
717 direction: ThreadTraversalDirection;
718}): T | null {
719 const { currentThreadId, direction, threadIds } = input;
720
721 if (threadIds.length === 0) {
722 return null;
723 }
724
725 if (currentThreadId === null) {
726 return direction === "previous" ? (threadIds.at(-1) ?? null) : (threadIds[0] ?? null);
727 }
728
729 const currentIndex = threadIds.indexOf(currentThreadId);
730 if (currentIndex === -1) {
731 return null;
732 }
733
734 if (direction === "previous") {
735 return currentIndex > 0 ? (threadIds[currentIndex - 1] ?? null) : null;
736 }
737
738 return currentIndex < threadIds.length - 1 ? (threadIds[currentIndex + 1] ?? null) : null;
739}
740
741export function isContextMenuPointerDown(input: {
742 button: number;
743 ctrlKey: boolean;
744 isMac: boolean;
745}): boolean {
746 if (input.button === 2) return true;
747 return input.isMac && input.button === 0 && input.ctrlKey;
748}
749
750export function resolveThreadRowClassName(input: {
751 isActive: boolean;
752 isSelected: boolean;
753}): string {
754 const baseClassName =
755 "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";
756
757 if (input.isSelected && input.isActive) {
758 return cn(
759 baseClassName,
760 "bg-sidebar-row-active text-sidebar-foreground font-medium hover:bg-sidebar-row-active hover:text-sidebar-foreground",
761 );
762 }
763
764 if (input.isSelected) {
765 return cn(
766 baseClassName,
767 "bg-sidebar-row-selected text-sidebar-foreground hover:bg-sidebar-row-active hover:text-sidebar-foreground",
768 );
769 }
770
771 if (input.isActive) {
772 return cn(
773 baseClassName,
774 "bg-sidebar-row-active text-sidebar-foreground font-medium hover:bg-sidebar-row-active hover:text-sidebar-foreground",
775 );
776 }
777
778 return cn(
779 baseClassName,
780 "text-sidebar-muted-foreground/80 hover:bg-sidebar-row-hover hover:text-sidebar-foreground",
781 );
782}
783
784// ── Sidebar thread status model ─────────────────────────────────────
785// Five visual states, three colors: color is reserved for "act now"
786// (approval), "in motion" (working), and "broken" (failed). Ready is the
787// unlabeled resting state — the agent stopped and is waiting on the user,
788// whether it finished, asked a question, or proposed a plan.
789// Unread completion is tracked separately: it describes whether a ready
790// thread needs attention, not what the thread is currently doing.
791export type SidebarThreadStatus =
792 | "approval"
793 | "input"
794 | "working"
795 | "monitoring"
796 | "failed"
797 | "ready";
798
799export function shouldRecedeSidebarThread(input: {
800 status: SidebarThreadStatus;
801 isUnread: boolean;
802 isWoke: boolean;
803 isActive: boolean;
804 isSelected: boolean;
805}): boolean {
806 if (input.isActive || input.isSelected || input.status === "input") return false;
807 if (input.status === "working" || input.status === "monitoring") return true;
808 if (input.status === "ready" || input.status === "approval") {
809 return !input.isUnread && !input.isWoke;
810 }
811 return false;
812}
813
814type SidebarThreadStatusInput = Pick<
815 SidebarThreadSummary,
816 "hasPendingApprovals" | "hasPendingUserInput" | "session" | "backgroundLiveness"
817>;
818
819export function resolveSidebarThreadStatus(thread: SidebarThreadStatusInput): SidebarThreadStatus {
820 if (thread.hasPendingApprovals) {
821 return "approval";
822 }
823 if (thread.hasPendingUserInput) {
824 return "input";
825 }
826 if (thread.session?.status === "running" || thread.session?.status === "starting") {
827 return "working";
828 }
829 // A failed session outranks lingering background liveness: the user must
830 // see the failure, not a stale Working (review finding).
831 if (thread.session?.status === "error") {
832 return "failed";
833 }
834 // Background work outlives the turn: fleets read as working; monitoring
835 // only when watch loops are the sole live work.
836 if (thread.backgroundLiveness === "working") {
837 return "working";
838 }
839 if (thread.backgroundLiveness === "monitoring") {
840 return "monitoring";
841 }
842 return "ready";
843}
844
845/** First VALID timestamp wins: `a ?? b` falls through on null, but a present-
846 yet-malformed string must also fall through to the next candidate rather
847 than sink the row to the epoch. */
848export function firstValidTimestampMs(
849 ...candidates: ReadonlyArray<string | null | undefined>
850): number {
851 for (const candidate of candidates) {
852 if (candidate == null) continue;
853 const parsed = Date.parse(candidate);
854 if (!Number.isNaN(parsed)) return parsed;
855 }
856 return 0;
857}
858
859/** String twin of firstValidTimestampMs for callers that need the ISO string
860 (display labels, tick anchors) rather than epoch ms. */
861function firstValidTimestamp(
862 ...candidates: ReadonlyArray<string | null | undefined>
863): string | null {
864 for (const candidate of candidates) {
865 if (candidate == null) continue;
866 if (!Number.isNaN(Date.parse(candidate))) return candidate;
867 }
868 return null;
869}
870
871export { sortActiveThreadsByOrderKey as sortThreadsForSidebar } from "@t3tools/client-runtime/state/thread-sort";
872
873// Pinned-reorder key math and the keyed sort live in client-runtime
874// (state/thread-sort) so web and mobile compute identical pinned orders.
875export { pinOrderKeyBetween, planPinnedReorder } from "@t3tools/client-runtime/state/thread-sort";
876export { sortPinnedThreadsByOrderKey as sortPinnedThreadsForSidebar } from "@t3tools/client-runtime/state/thread-sort";
877
878/**
879 * Search the already-ordered sidebar thread collection by title or linked PR.
880 * Keeping the input order means lifecycle ordering (active, snoozed, settled)
881 * remains stable while the user narrows the list.
882 */
883export function searchSidebarThreads<
884 T extends { readonly title: string } & Parameters<typeof threadPullRequestSearchTerms>[0],
885>(threads: readonly T[], query: string): T[] {
886 const normalizedQuery = query.trim().toLowerCase();
887 if (normalizedQuery.length === 0) return [];
888 return threads.filter((thread) =>
889 [thread.title, ...threadPullRequestSearchTerms(thread)].some((term) =>
890 term.toLowerCase().includes(normalizedQuery),
891 ),
892 );
893}
894
895export function filterSidebarProjectScopeItems<TItem extends { readonly value: string }>(input: {
896 items: readonly TItem[];
897 query: string;
898 matches: (item: TItem, query: string) => boolean;
899}): readonly TItem[] {
900 const query = input.query.trim();
901 if (query.length === 0) return input.items;
902 return input.items.filter((item) => item.value !== "all" && input.matches(item, query));
903}
904
905export interface SidebarProjectScopeMenuState {
906 readonly open: boolean;
907 readonly query: string;
908}
909
910export type SidebarProjectScopeMenuAction =
911 | { readonly type: "query-changed"; readonly query: string }
912 | { readonly type: "open-changed"; readonly open: boolean }
913 | { readonly type: "project-settings-opened" };
914
915export function reduceSidebarProjectScopeMenuState(
916 state: SidebarProjectScopeMenuState,
917 action: SidebarProjectScopeMenuAction,
918): SidebarProjectScopeMenuState {
919 switch (action.type) {
920 case "query-changed":
921 return { ...state, query: action.query };
922 case "open-changed":
923 return { open: action.open, query: "" };
924 case "project-settings-opened":
925 return { open: false, query: "" };
926 }
927}
928
929// Settled rows are history, so they order by when the work ENDED, not when
930// the thread was created or last touched.
931export function sortSettledThreadsForSidebar<
932 T extends SettledThreadTimestampInput & { readonly id: string },
933>(threads: readonly T[]): T[] {
934 const timestampMs = (thread: T) => {
935 const timestamp = resolveSettledThreadTimestamp(thread);
936 return timestamp === null ? 0 : Date.parse(timestamp);
937 };
938 return [...threads].toSorted(
939 (left, right) => timestampMs(right) - timestampMs(left) || left.id.localeCompare(right.id),
940 );
941}
942
943/** The timestamp a working thread's elapsed label counts from: the running
944 turn's start (request time until adoption), falling back to the session's
945 last transition when the turn projection lags behind. Malformed
946 timestamps fall through to the next candidate, not just missing ones. */
947export function resolveWorkingStartedAt(
948 thread: Pick<SidebarThreadSummary, "latestTurn" | "session">,
949): string | null {
950 const turn = thread.latestTurn;
951 if (turn && turn.completedAt === null) {
952 return firstValidTimestamp(turn.startedAt, turn.requestedAt, thread.session?.updatedAt);
953 }
954 return firstValidTimestamp(thread.session?.updatedAt);
955}
956
957export function formatWorkingDurationLabel(elapsedMs: number): string {
958 const seconds = Number.isFinite(elapsedMs) ? Math.max(0, Math.floor(elapsedMs / 1000)) : 0;
959 if (seconds < 60) return `${seconds}s`;
960 const minutes = Math.floor(seconds / 60);
961 if (minutes < 60) return `${minutes}m`;
962 return `${Math.floor(minutes / 60)}h ${minutes % 60}m`;
963}
964
965export function resolveThreadStatusPill(input: {
966 thread: ThreadStatusInput;
967}): ThreadStatusPill | null {
968 const { thread } = input;
969
970 if (thread.hasPendingApprovals) {
971 return {
972 label: "Pending Approval",
973 colorClass: "text-amber-600 dark:text-amber-300/90",
974 dotClass: "bg-amber-500 dark:bg-amber-300/90",
975 pulse: false,
976 };
977 }
978
979 if (thread.hasPendingUserInput) {
980 return {
981 label: "Awaiting Input",
982 colorClass: "text-indigo-600 dark:text-indigo-300/90",
983 dotClass: "bg-indigo-500 dark:bg-indigo-300/90",
984 pulse: false,
985 };
986 }
987
988 if (thread.session?.status === "running") {
989 return {
990 label: "Working",
991 colorClass: "text-sky-600 dark:text-sky-300/80",
992 dotClass: "bg-sky-500 dark:bg-sky-300/80",
993 pulse: true,
994 };
995 }
996
997 if (thread.session?.status === "starting") {
998 return {
999 label: "Connecting",
1000 colorClass: "text-sky-600 dark:text-sky-300/80",
1001 dotClass: "bg-sky-500 dark:bg-sky-300/80",
1002 pulse: true,
1003 };
1004 }
1005
1006 // An actionable plan prompt outranks lingering background work: it needs
1007 // the user's decision, while liveness merely reports (review finding).
1008 const hasPlanReadyPrompt =
1009 !thread.hasPendingUserInput &&
1010 thread.interactionMode === "plan" &&
1011 isLatestTurnSettled(thread.latestTurn, thread.session) &&
1012 thread.hasActionableProposedPlan;
1013 if (hasPlanReadyPrompt) {
1014 return {
1015 label: "Plan Ready",
1016 colorClass: "text-violet-600 dark:text-violet-300/90",
1017 dotClass: "bg-violet-500 dark:bg-violet-300/90",
1018 pulse: false,
1019 };
1020 }
1021
1022 // The turn can settle while native background work runs on. Subagent and
1023 // workflow fleets read as plain Working; Monitoring is reserved for watch
1024 // loops (a parent agent babysitting a PR, tailing checks) with no other
1025 // live work. Same recede treatment as Working per inbox-zero.
1026 if (thread.backgroundLiveness === "working") {
1027 return {
1028 label: "Working",
1029 colorClass: "text-sky-600 dark:text-sky-300/80",
1030 dotClass: "bg-sky-500 dark:bg-sky-300/80",
1031 pulse: true,
1032 };
1033 }
1034
1035 if (thread.backgroundLiveness === "monitoring") {
1036 return {
1037 label: "Monitoring",
1038 colorClass: "text-sky-600 dark:text-sky-300/80",
1039 dotClass: "bg-sky-500 dark:bg-sky-300/80",
1040 pulse: false,
1041 };
1042 }
1043
1044 if (hasUnseenCompletion(thread)) {
1045 return {
1046 label: "Completed",
1047 colorClass: "text-emerald-600 dark:text-emerald-300/90",
1048 dotClass: "bg-emerald-500 dark:bg-emerald-300/90",
1049 pulse: false,
1050 };
1051 }
1052
1053 return null;
1054}
1055
1056export function resolveProjectStatusIndicator(
1057 statuses: ReadonlyArray<ThreadStatusPill | null>,
1058): ThreadStatusPill | null {
1059 let highestPriorityStatus: ThreadStatusPill | null = null;
1060
1061 for (const status of statuses) {
1062 if (status === null) continue;
1063 if (
1064 highestPriorityStatus === null ||
1065 THREAD_STATUS_PRIORITY[status.label] > THREAD_STATUS_PRIORITY[highestPriorityStatus.label]
1066 ) {
1067 highestPriorityStatus = status;
1068 }
1069 }
1070
1071 return highestPriorityStatus;
1072}
1073
1074export function getFallbackThreadIdAfterDelete<
1075 T extends Pick<Thread, "id" | "projectId" | "createdAt" | "updatedAt"> & ThreadSortInput,
1076>(input: {
1077 threads: readonly T[];
1078 deletedThreadId: T["id"];
1079 sortOrder: SidebarThreadSortOrder;
1080 deletedThreadIds?: ReadonlySet<T["id"]>;
1081}): T["id"] | null {
1082 const { deletedThreadId, deletedThreadIds, sortOrder, threads } = input;
1083 const deletedThread = threads.find((thread) => thread.id === deletedThreadId);
1084 if (!deletedThread) {
1085 return null;
1086 }
1087
1088 return (
1089 sortThreads(
1090 threads.filter(
1091 (thread) =>
1092 thread.projectId === deletedThread.projectId &&
1093 thread.id !== deletedThreadId &&
1094 !deletedThreadIds?.has(thread.id),
1095 ),
1096 sortOrder,
1097 )[0]?.id ?? null
1098 );
1099}
1100export function getProjectSortTimestamp(
1101 project: SidebarProject,
1102 projectThreads: readonly ThreadSortInput[],
1103 sortOrder: Exclude<SidebarProjectSortOrder, "manual">,
1104): number {
1105 if (projectThreads.length > 0) {
1106 return projectThreads.reduce(
1107 (latest, thread) => Math.max(latest, getThreadSortTimestamp(thread, sortOrder)),
1108 Number.NEGATIVE_INFINITY,
1109 );
1110 }
1111
1112 if (sortOrder === "created_at") {
1113 return toSortableTimestamp(project.createdAt) ?? Number.NEGATIVE_INFINITY;
1114 }
1115 return toSortableTimestamp(project.updatedAt ?? project.createdAt) ?? Number.NEGATIVE_INFINITY;
1116}
1117
1118function sortProjectsByActivity<TProject extends SidebarProject>(
1119 projects: readonly TProject[],
1120 sortOrder: SidebarProjectSortOrder,
1121 getProjectThreads: (project: TProject) => readonly ThreadSortInput[],
1122 compareTies: (left: TProject, right: TProject) => number,
1123): TProject[] {
1124 if (sortOrder === "manual") {
1125 return [...projects];
1126 }
1127
1128 return [...projects].toSorted((left, right) => {
1129 const rightTimestamp = getProjectSortTimestamp(right, getProjectThreads(right), sortOrder);
1130 const leftTimestamp = getProjectSortTimestamp(left, getProjectThreads(left), sortOrder);
1131 const byTimestamp =
1132 rightTimestamp === leftTimestamp ? 0 : rightTimestamp > leftTimestamp ? 1 : -1;
1133 return byTimestamp || compareTies(left, right);
1134 });
1135}
1136
1137export function sortProjectsForSidebar<
1138 TProject extends SidebarProject,
1139 TThread extends Pick<Thread, "projectId" | "createdAt" | "updatedAt"> & ThreadSortInput,
1140>(
1141 projects: readonly TProject[],
1142 threads: readonly TThread[],
1143 sortOrder: SidebarProjectSortOrder,
1144): TProject[] {
1145 const threadsByProjectId = new Map<string, TThread[]>();
1146 for (const thread of threads) {
1147 const existing = threadsByProjectId.get(thread.projectId) ?? [];
1148 existing.push(thread);
1149 threadsByProjectId.set(thread.projectId, existing);
1150 }
1151
1152 return sortProjectsByActivity(
1153 projects,
1154 sortOrder,
1155 (project) => threadsByProjectId.get(project.id) ?? [],
1156 (left, right) => left.title.localeCompare(right.title) || left.id.localeCompare(right.id),
1157 );
1158}
1159
1160export function sortLogicalProjectsForSidebar<
1161 TProject extends LogicalSidebarProject,
1162 TThread extends ScopedSidebarThread,
1163>(
1164 projects: readonly TProject[],
1165 threads: readonly TThread[],
1166 sortOrder: SidebarProjectSortOrder,
1167): TProject[] {
1168 const groupKeyByProjectRef = new Map(
1169 projects.flatMap((project) =>
1170 project.memberProjectRefs.map(
1171 (projectRef) =>
1172 [`${projectRef.environmentId}\0${projectRef.projectId}`, project.projectKey] as const,
1173 ),
1174 ),
1175 );
1176 const threadsByProjectKey = new Map<string, TThread[]>();
1177 for (const thread of threads) {
1178 if (thread.archivedAt !== null) continue;
1179 const projectKey = groupKeyByProjectRef.get(`${thread.environmentId}\0${thread.projectId}`);
1180 if (!projectKey) continue;
1181 const existing = threadsByProjectKey.get(projectKey);
1182 if (existing) {
1183 existing.push(thread);
1184 } else {
1185 threadsByProjectKey.set(projectKey, [thread]);
1186 }
1187 }
1188
1189 return sortProjectsByActivity(
1190 projects,
1191 sortOrder,
1192 (project) => threadsByProjectKey.get(project.projectKey) ?? [],
1193 (left, right) =>
1194 left.title.localeCompare(right.title) || left.projectKey.localeCompare(right.projectKey),
1195 );
1196}
1197
1198/**
1199 * Sorts the cross-environment project collection used by landing surfaces.
1200 * Project ids are only unique within an environment, and archived threads
1201 * must not make a project appear recently active.
1202 */
1203export function sortScopedProjectsForSidebar<
1204 TProject extends ScopedSidebarProject,
1205 TThread extends ScopedSidebarThread,
1206>(
1207 projects: readonly TProject[],
1208 threads: readonly TThread[],
1209 sortOrder: SidebarProjectSortOrder,
1210): TProject[] {
1211 const scopedKey = (environmentId: string, projectId: string) =>
1212 `${environmentId}\u0000${projectId}`;
1213 const threadsByProject = new Map<string, TThread[]>();
1214 for (const thread of threads) {
1215 if (thread.archivedAt !== null) {
1216 continue;
1217 }
1218 const key = scopedKey(thread.environmentId, thread.projectId);
1219 const existing = threadsByProject.get(key) ?? [];
1220 existing.push(thread);
1221 threadsByProject.set(key, existing);
1222 }
1223
1224 return sortProjectsByActivity(
1225 projects,
1226 sortOrder,
1227 (project) => threadsByProject.get(scopedKey(project.environmentId, project.id)) ?? [],
1228 (left, right) =>
1229 left.title.localeCompare(right.title) ||
1230 left.environmentId.localeCompare(right.environmentId) ||
1231 left.id.localeCompare(right.id),
1232 );
1233}