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