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