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