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
771// ── Sidebar thread status model ─────────────────────────────────────
772// Five visual states, three colors: color is reserved for "act now"
773// (approval), "in motion" (working), and "broken" (failed). Ready is the
774// unlabeled resting state — the agent stopped and is waiting on the user,
775// whether it finished, asked a question, or proposed a plan.
776// Unread completion is tracked separately: it describes whether a ready
777// thread needs attention, not what the thread is currently doing.
778export type SidebarThreadStatus =
779 | "approval"
780 | "input"
781 | "working"
782 | "monitoring"
783 | "failed"
784 | "ready";
785
786export function shouldRecedeSidebarThread(input: {
787 status: SidebarThreadStatus;
788 isUnread: boolean;
789 isWoke: boolean;
790 isActive: boolean;
791 isSelected: boolean;
792}): boolean {
793 if (input.isActive || input.isSelected || input.status === "input") return false;
794 if (input.status === "working" || input.status === "monitoring") return true;
795 if (input.status === "ready" || input.status === "approval") {
796 return !input.isUnread && !input.isWoke;
797 }
798 return false;
799}
800
801type SidebarThreadStatusInput = Pick<
802 SidebarThreadSummary,
803 "hasPendingApprovals" | "hasPendingUserInput" | "session" | "backgroundLiveness"
804>;
805
806export function resolveSidebarThreadStatus(thread: SidebarThreadStatusInput): SidebarThreadStatus {
807 if (thread.hasPendingApprovals) {
808 return "approval";
809 }
810 if (thread.hasPendingUserInput) {
811 return "input";
812 }
813 if (thread.session?.status === "running" || thread.session?.status === "starting") {
814 return "working";
815 }
816 // A failed session outranks lingering background liveness: the user must
817 // see the failure, not a stale Working (review finding).
818 if (thread.session?.status === "error") {
819 return "failed";
820 }
821 // Background work outlives the turn: fleets read as working; monitoring
822 // only when watch loops are the sole live work.
823 if (thread.backgroundLiveness === "working") {
824 return "working";
825 }
826 if (thread.backgroundLiveness === "monitoring") {
827 return "monitoring";
828 }
829 return "ready";
830}
831
832/** First VALID timestamp wins: `a ?? b` falls through on null, but a present-
833 yet-malformed string must also fall through to the next candidate rather
834 than sink the row to the epoch. */
835export function firstValidTimestampMs(
836 ...candidates: ReadonlyArray<string | null | undefined>
837): number {
838 for (const candidate of candidates) {
839 if (candidate == null) continue;
840 const parsed = Date.parse(candidate);
841 if (!Number.isNaN(parsed)) return parsed;
842 }
843 return 0;
844}
845
846/** String twin of firstValidTimestampMs for callers that need the ISO string
847 (display labels, tick anchors) rather than epoch ms. */
848function firstValidTimestamp(
849 ...candidates: ReadonlyArray<string | null | undefined>
850): string | null {
851 for (const candidate of candidates) {
852 if (candidate == null) continue;
853 if (!Number.isNaN(Date.parse(candidate))) return candidate;
854 }
855 return null;
856}
857
858export { sortActiveThreadsByOrderKey as sortThreadsForSidebar } from "@t3tools/client-runtime/state/thread-sort";
859
860// Pinned-reorder key math and the keyed sort live in client-runtime
861// (state/thread-sort) so web and mobile compute identical pinned orders.
862export { pinOrderKeyBetween, planPinnedReorder } from "@t3tools/client-runtime/state/thread-sort";
863export { sortPinnedThreadsByOrderKey as sortPinnedThreadsForSidebar } from "@t3tools/client-runtime/state/thread-sort";
864
865const EMPTY_CONTENT_MATCH_KEYS: ReadonlySet<string> = new Set<string>();
866
867/**
868 * Search the already-ordered sidebar thread collection by title or linked PR,
869 * plus any thread whose messages the server matched (`contentMatchKeys`, keyed
870 * by `threadSearchMatchKey`). Keeping the input order means lifecycle ordering
871 * (active, snoozed, settled) remains stable while the user narrows the list.
872 */
873export function searchSidebarThreads<
874 T extends {
875 readonly environmentId: EnvironmentId;
876 readonly id: ThreadId;
877 readonly title: string;
878 } & Parameters<typeof threadPullRequestSearchTerms>[0],
879>(
880 threads: readonly T[],
881 query: string,
882 contentMatchKeys: ReadonlySet<string> = EMPTY_CONTENT_MATCH_KEYS,
883): T[] {
884 const normalizedQuery = query.trim().toLowerCase();
885 if (normalizedQuery.length === 0) return [];
886 const titleMatches: T[] = [];
887 const contentMatches: T[] = [];
888 for (const thread of threads) {
889 const matchesTitle = [thread.title, ...threadPullRequestSearchTerms(thread)].some((term) =>
890 term.toLowerCase().includes(normalizedQuery),
891 );
892 if (matchesTitle) {
893 titleMatches.push(thread);
894 } else if (
895 contentMatchKeys.size > 0 &&
896 contentMatchKeys.has(
897 threadSearchMatchKey({ environmentId: thread.environmentId, threadId: thread.id }),
898 )
899 ) {
900 contentMatches.push(thread);
901 }
902 }
903 return [...titleMatches, ...contentMatches];
904}
905
906export function filterSidebarProjectScopeItems<TItem extends { readonly value: string }>(input: {
907 items: readonly TItem[];
908 query: string;
909 matches: (item: TItem, query: string) => boolean;
910}): readonly TItem[] {
911 const query = input.query.trim();
912 if (query.length === 0) return input.items;
913 return input.items.filter((item) => item.value !== "all" && input.matches(item, query));
914}
915
916export interface SidebarProjectScopeMenuState {
917 readonly open: boolean;
918 readonly query: string;
919}
920
921export type SidebarProjectScopeMenuAction =
922 | { readonly type: "query-changed"; readonly query: string }
923 | { readonly type: "open-changed"; readonly open: boolean }
924 | { readonly type: "project-settings-opened" };
925
926export function reduceSidebarProjectScopeMenuState(
927 state: SidebarProjectScopeMenuState,
928 action: SidebarProjectScopeMenuAction,
929): SidebarProjectScopeMenuState {
930 switch (action.type) {
931 case "query-changed":
932 return { ...state, query: action.query };
933 case "open-changed":
934 return { open: action.open, query: "" };
935 case "project-settings-opened":
936 return { open: false, query: "" };
937 }
938}
939
940// Settled rows are history, so they order by when the work ENDED, not when
941// the thread was created or last touched.
942export function sortSettledThreadsForSidebar<
943 T extends SettledThreadTimestampInput & { readonly id: string },
944>(threads: readonly T[]): T[] {
945 const timestampMs = (thread: T) => {
946 const timestamp = resolveSettledThreadTimestamp(thread);
947 return timestamp === null ? 0 : Date.parse(timestamp);
948 };
949 return [...threads].toSorted(
950 (left, right) => timestampMs(right) - timestampMs(left) || left.id.localeCompare(right.id),
951 );
952}
953
954/** The timestamp a working thread's elapsed label counts from: the running
955 turn's start (request time until adoption), falling back to the session's
956 last transition when the turn projection lags behind. Malformed
957 timestamps fall through to the next candidate, not just missing ones. */
958export function resolveWorkingStartedAt(
959 thread: Pick<SidebarThreadSummary, "latestTurn" | "session">,
960): string | null {
961 const turn = thread.latestTurn;
962 if (turn && turn.completedAt === null) {
963 return firstValidTimestamp(turn.startedAt, turn.requestedAt, thread.session?.updatedAt);
964 }
965 return firstValidTimestamp(thread.session?.updatedAt);
966}
967
968export function formatWorkingDurationLabel(elapsedMs: number): string {
969 const seconds = Number.isFinite(elapsedMs) ? Math.max(0, Math.floor(elapsedMs / 1000)) : 0;
970 if (seconds < 60) return `${seconds}s`;
971 const minutes = Math.floor(seconds / 60);
972 if (minutes < 60) return `${minutes}m`;
973 return `${Math.floor(minutes / 60)}h ${minutes % 60}m`;
974}
975
976export function resolveThreadStatusPill(input: {
977 thread: ThreadStatusInput;
978}): ThreadStatusPill | null {
979 const { thread } = input;
980
981 if (thread.hasPendingApprovals) {
982 return {
983 label: "Pending Approval",
984 colorClass: "text-amber-600 dark:text-amber-300/90",
985 dotClass: "bg-amber-500 dark:bg-amber-300/90",
986 pulse: false,
987 };
988 }
989
990 if (thread.hasPendingUserInput) {
991 return {
992 label: "Awaiting Input",
993 colorClass: "text-indigo-600 dark:text-indigo-300/90",
994 dotClass: "bg-indigo-500 dark:bg-indigo-300/90",
995 pulse: false,
996 };
997 }
998
999 if (thread.session?.status === "running") {
1000 return {
1001 label: "Working",
1002 colorClass: "text-sky-600 dark:text-sky-300/80",
1003 dotClass: "bg-sky-500 dark:bg-sky-300/80",
1004 pulse: true,
1005 };
1006 }
1007
1008 if (thread.session?.status === "starting") {
1009 return {
1010 label: "Connecting",
1011 colorClass: "text-sky-600 dark:text-sky-300/80",
1012 dotClass: "bg-sky-500 dark:bg-sky-300/80",
1013 pulse: true,
1014 };
1015 }
1016
1017 // An actionable plan prompt outranks lingering background work: it needs
1018 // the user's decision, while liveness merely reports (review finding).
1019 const hasPlanReadyPrompt =
1020 !thread.hasPendingUserInput &&
1021 thread.interactionMode === "plan" &&
1022 isLatestTurnSettled(thread.latestTurn, thread.session) &&
1023 thread.hasActionableProposedPlan;
1024 if (hasPlanReadyPrompt) {
1025 return {
1026 label: "Plan Ready",
1027 colorClass: "text-violet-600 dark:text-violet-300/90",
1028 dotClass: "bg-violet-500 dark:bg-violet-300/90",
1029 pulse: false,
1030 };
1031 }
1032
1033 // The turn can settle while native background work runs on. Subagent and
1034 // workflow fleets read as plain Working; Monitoring is reserved for watch
1035 // loops (a parent agent babysitting a PR, tailing checks) with no other
1036 // live work. Same recede treatment as Working per inbox-zero.
1037 if (thread.backgroundLiveness === "working") {
1038 return {
1039 label: "Working",
1040 colorClass: "text-sky-600 dark:text-sky-300/80",
1041 dotClass: "bg-sky-500 dark:bg-sky-300/80",
1042 pulse: true,
1043 };
1044 }
1045
1046 if (thread.backgroundLiveness === "monitoring") {
1047 return {
1048 label: "Monitoring",
1049 colorClass: "text-sky-600 dark:text-sky-300/80",
1050 dotClass: "bg-sky-500 dark:bg-sky-300/80",
1051 pulse: false,
1052 };
1053 }
1054
1055 if (hasUnseenCompletion(thread)) {
1056 return {
1057 label: "Completed",
1058 colorClass: "text-emerald-600 dark:text-emerald-300/90",
1059 dotClass: "bg-emerald-500 dark:bg-emerald-300/90",
1060 pulse: false,
1061 };
1062 }
1063
1064 return null;
1065}
1066
1067export function resolveProjectStatusIndicator(
1068 statuses: ReadonlyArray<ThreadStatusPill | null>,
1069): ThreadStatusPill | null {
1070 let highestPriorityStatus: ThreadStatusPill | null = null;
1071
1072 for (const status of statuses) {
1073 if (status === null) continue;
1074 if (
1075 highestPriorityStatus === null ||
1076 THREAD_STATUS_PRIORITY[status.label] > THREAD_STATUS_PRIORITY[highestPriorityStatus.label]
1077 ) {
1078 highestPriorityStatus = status;
1079 }
1080 }
1081
1082 return highestPriorityStatus;
1083}
1084
1085export function getFallbackThreadIdAfterDelete<
1086 T extends Pick<Thread, "id" | "projectId" | "createdAt" | "updatedAt"> & ThreadSortInput,
1087>(input: {
1088 threads: readonly T[];
1089 deletedThreadId: T["id"];
1090 sortOrder: SidebarThreadSortOrder;
1091 deletedThreadIds?: ReadonlySet<T["id"]>;
1092}): T["id"] | null {
1093 const { deletedThreadId, deletedThreadIds, sortOrder, threads } = input;
1094 const deletedThread = threads.find((thread) => thread.id === deletedThreadId);
1095 if (!deletedThread) {
1096 return null;
1097 }
1098
1099 return (
1100 sortThreads(
1101 threads.filter(
1102 (thread) =>
1103 thread.projectId === deletedThread.projectId &&
1104 thread.id !== deletedThreadId &&
1105 !deletedThreadIds?.has(thread.id),
1106 ),
1107 sortOrder,
1108 )[0]?.id ?? null
1109 );
1110}
1111export function getProjectSortTimestamp(
1112 project: SidebarProject,
1113 projectThreads: readonly ThreadSortInput[],
1114 sortOrder: Exclude<SidebarProjectSortOrder, "manual">,
1115): number {
1116 if (projectThreads.length > 0) {
1117 return projectThreads.reduce(
1118 (latest, thread) => Math.max(latest, getThreadSortTimestamp(thread, sortOrder)),
1119 Number.NEGATIVE_INFINITY,
1120 );
1121 }
1122
1123 if (sortOrder === "created_at") {
1124 return toSortableTimestamp(project.createdAt) ?? Number.NEGATIVE_INFINITY;
1125 }
1126 return toSortableTimestamp(project.updatedAt ?? project.createdAt) ?? Number.NEGATIVE_INFINITY;
1127}
1128
1129function sortProjectsByActivity<TProject extends SidebarProject>(
1130 projects: readonly TProject[],
1131 sortOrder: SidebarProjectSortOrder,
1132 getProjectThreads: (project: TProject) => readonly ThreadSortInput[],
1133 compareTies: (left: TProject, right: TProject) => number,
1134): TProject[] {
1135 if (sortOrder === "manual") {
1136 return [...projects];
1137 }
1138
1139 return [...projects].toSorted((left, right) => {
1140 const rightTimestamp = getProjectSortTimestamp(right, getProjectThreads(right), sortOrder);
1141 const leftTimestamp = getProjectSortTimestamp(left, getProjectThreads(left), sortOrder);
1142 const byTimestamp =
1143 rightTimestamp === leftTimestamp ? 0 : rightTimestamp > leftTimestamp ? 1 : -1;
1144 return byTimestamp || compareTies(left, right);
1145 });
1146}
1147
1148export function sortProjectsForSidebar<
1149 TProject extends SidebarProject,
1150 TThread extends Pick<Thread, "projectId" | "createdAt" | "updatedAt"> & ThreadSortInput,
1151>(
1152 projects: readonly TProject[],
1153 threads: readonly TThread[],
1154 sortOrder: SidebarProjectSortOrder,
1155): TProject[] {
1156 const threadsByProjectId = new Map<string, TThread[]>();
1157 for (const thread of threads) {
1158 const existing = threadsByProjectId.get(thread.projectId) ?? [];
1159 existing.push(thread);
1160 threadsByProjectId.set(thread.projectId, existing);
1161 }
1162
1163 return sortProjectsByActivity(
1164 projects,
1165 sortOrder,
1166 (project) => threadsByProjectId.get(project.id) ?? [],
1167 (left, right) => left.title.localeCompare(right.title) || left.id.localeCompare(right.id),
1168 );
1169}
1170
1171export function sortLogicalProjectsForSidebar<
1172 TProject extends LogicalSidebarProject,
1173 TThread extends ScopedSidebarThread,
1174>(
1175 projects: readonly TProject[],
1176 threads: readonly TThread[],
1177 sortOrder: SidebarProjectSortOrder,
1178): TProject[] {
1179 const groupKeyByProjectRef = new Map(
1180 projects.flatMap((project) =>
1181 project.memberProjectRefs.map(
1182 (projectRef) =>
1183 [`${projectRef.environmentId}\0${projectRef.projectId}`, project.projectKey] as const,
1184 ),
1185 ),
1186 );
1187 const threadsByProjectKey = new Map<string, TThread[]>();
1188 for (const thread of threads) {
1189 if (thread.archivedAt !== null) continue;
1190 const projectKey = groupKeyByProjectRef.get(`${thread.environmentId}\0${thread.projectId}`);
1191 if (!projectKey) continue;
1192 const existing = threadsByProjectKey.get(projectKey);
1193 if (existing) {
1194 existing.push(thread);
1195 } else {
1196 threadsByProjectKey.set(projectKey, [thread]);
1197 }
1198 }
1199
1200 return sortProjectsByActivity(
1201 projects,
1202 sortOrder,
1203 (project) => threadsByProjectKey.get(project.projectKey) ?? [],
1204 (left, right) =>
1205 left.title.localeCompare(right.title) || left.projectKey.localeCompare(right.projectKey),
1206 );
1207}
1208
1209/**
1210 * Sorts the cross-environment project collection used by landing surfaces.
1211 * Project ids are only unique within an environment, and archived threads
1212 * must not make a project appear recently active.
1213 */
1214export function sortScopedProjectsForSidebar<
1215 TProject extends ScopedSidebarProject,
1216 TThread extends ScopedSidebarThread,
1217>(
1218 projects: readonly TProject[],
1219 threads: readonly TThread[],
1220 sortOrder: SidebarProjectSortOrder,
1221): TProject[] {
1222 const scopedKey = (environmentId: string, projectId: string) =>
1223 `${environmentId}\u0000${projectId}`;
1224 const threadsByProject = new Map<string, TThread[]>();
1225 for (const thread of threads) {
1226 if (thread.archivedAt !== null) {
1227 continue;
1228 }
1229 const key = scopedKey(thread.environmentId, thread.projectId);
1230 const existing = threadsByProject.get(key) ?? [];
1231 existing.push(thread);
1232 threadsByProject.set(key, existing);
1233 }
1234
1235 return sortProjectsByActivity(
1236 projects,
1237 sortOrder,
1238 (project) => threadsByProject.get(scopedKey(project.environmentId, project.id)) ?? [],
1239 (left, right) =>
1240 left.title.localeCompare(right.title) ||
1241 left.environmentId.localeCompare(right.environmentId) ||
1242 left.id.localeCompare(right.id),
1243 );
1244}