Open History to see the last commit
1import { resolveThreadWorkingStartedAt } from "@t3tools/client-runtime/state/models";
2import { backgroundWorkHoldsCompletion } from "@t3tools/shared/orchestrationV2PendingBackgroundWork";
3import { threadPullRequestSearchTerms } from "@t3tools/shared/threadPullRequests";
4import * as React from "react";
5import {
6 isAtomCommandInterrupted,
7 type AtomCommandResult,
8} from "@t3tools/client-runtime/state/runtime";
9import { defaultAnimateLayoutChanges, type AnimateLayoutChanges } from "@dnd-kit/sortable";
10import { threadSearchMatchKey } from "@t3tools/client-runtime/state/thread-search";
11import type { ContextMenuItem, EnvironmentId, ThreadId } from "@t3tools/contracts";
12import type { SidebarProjectSortOrder, SidebarThreadSortOrder } from "@t3tools/contracts/settings";
13import type { AsyncResult } from "effect/reactivity";
14import { planPinnedReorder } from "@t3tools/client-runtime/state/thread-sort";
15import {
16 effectiveSnoozed,
17 type ThreadSnoozeShell,
18} from "@t3tools/client-runtime/state/thread-settled";
19import {
20 getThreadSortTimestamp,
21 sortThreads,
22 toSortableTimestamp,
23 type ThreadSortInput,
24} from "../lib/threadSort";
25import type { SidebarThreadSummary, Thread } from "../types";
26import { cn, normalizeSearchText } from "../lib/utils";
27import { isLatestRunSettled } from "../session-logic";
28import { resolveServerBackedAppStageLabel } from "../branding.logic";
29
30export function shouldNavigateAfterThreadPark(input: {
31 readonly threadKey: string;
32 readonly currentThreadKey: string | null;
33 readonly action: "settle" | "snooze";
34 readonly now: string;
35 readonly thread: (ThreadSnoozeShell & Pick<SidebarThreadSummary, "settledOverride">) | null;
36}): boolean {
37 return (
38 input.threadKey === input.currentThreadKey &&
39 input.thread !== null &&
40 (input.action === "settle"
41 ? input.thread.settledOverride === "settled"
42 : effectiveSnoozed(input.thread, { now: input.now }))
43 );
44}
45
46const THREAD_SELECTION_SAFE_SELECTOR = "[data-thread-item], [data-thread-selection-safe]";
47export const THREAD_JUMP_HINT_SHOW_DELAY_MS = 200;
48
49export function resolveSidebarRowAccessibility(input: {
50 readonly title: string;
51 readonly statusLabel: string | null;
52 readonly projectDisplayName: string | null;
53 readonly isActive: boolean;
54}): { readonly label: string; readonly current: "page" | undefined } {
55 return {
56 label: [input.title, input.statusLabel, input.projectDisplayName].filter(Boolean).join(", "),
57 current: input.isActive ? "page" : undefined,
58 };
59}
60
61// Each prewarmed thread holds a live, fully hydrated detail subscription (all
62// messages and activities, growing as agents work) for as long as the row stays
63// visible, so this limit is a direct renderer-heap and server-load multiplier —
64// keep it small; cold opens still render instantly from the cached snapshot.
65const SIDEBAR_THREAD_PREWARM_LIMIT = 3;
66const SIDEBAR_ROW_SUBSCRIPTION_OVERSCAN_PX = 160;
67
68export function useSidebarRowSubscriptionLease(isActive: boolean): {
69 readonly leaseLiveStatus: boolean;
70 readonly rowRef: React.Dispatch<React.SetStateAction<HTMLElement | null>>;
71} {
72 const [row, setRow] = React.useState<HTMLElement | null>(null);
73 const [isNearViewport, setIsNearViewport] = React.useState(isActive);
74
75 React.useEffect(() => {
76 if (isActive) {
77 setIsNearViewport(true);
78 return;
79 }
80 if (row === null) return;
81 if (typeof IntersectionObserver === "undefined") {
82 setIsNearViewport(true);
83 return;
84 }
85
86 const scrollRoot = row.closest<HTMLElement>('[data-slot="scroll-area-viewport"]');
87 const observer = new IntersectionObserver(
88 ([entry]) => setIsNearViewport(entry?.isIntersecting === true),
89 {
90 root: scrollRoot,
91 rootMargin: `${SIDEBAR_ROW_SUBSCRIPTION_OVERSCAN_PX}px 0px`,
92 },
93 );
94 observer.observe(row);
95 return () => observer.disconnect();
96 }, [isActive, row]);
97
98 return {
99 leaseLiveStatus: isActive || isNearViewport,
100 rowRef: setRow,
101 };
102}
103
104export function useRetainedValue<T>(key: string | null, value: T | null): T | null {
105 const retained = React.useRef<{ readonly key: string; readonly value: T } | null>(null);
106 if (key !== null && value !== null) {
107 retained.current = { key, value };
108 }
109 if (value !== null) return value;
110 return key !== null && retained.current?.key === key ? retained.current.value : null;
111}
112
113// Sidebar.motion handles ordinary section changes. Sortable transforms own
114// dragging; replaying their committed DOM order would animate the drop twice.
115export const animateSidebarLayoutChanges: AnimateLayoutChanges = (args) =>
116 args.isSorting ? defaultAnimateLayoutChanges(args) : false;
117
118// Snoozed rows can leave the shelf, but dropping into it is not supported
119// because snoozing requires a wake time. The Working shelf (beta) follows live
120// status, so it is neither a drag source nor a destination.
121
122export type SidebarSection = "pinned" | "active" | "working" | "snoozed" | "settled";
123
124export function resolveSidebarThreadSection(input: {
125 readonly snoozed: boolean;
126 readonly settled: boolean;
127 readonly pinned: boolean;
128}): SidebarSection {
129 if (input.snoozed) return "snoozed";
130 if (input.settled) return "settled";
131 if (input.pinned) return "pinned";
132 return "active";
133}
134
135const SIDEBAR_MARKER_PREFIX = "sidebar-marker-";
136
137export type SidebarListMarker =
138 | "pinned-header"
139 | "active-placeholder"
140 | "settled-placeholder"
141 | "pinned-divider"
142 | "working-header"
143 | "snoozed-header"
144 | "settled-header";
145
146export function sidebarMarkerId(marker: SidebarListMarker): string {
147 return `${SIDEBAR_MARKER_PREFIX}${marker}`;
148}
149
150export type SidebarListItem =
151 | { readonly kind: "thread"; readonly key: string; readonly section: SidebarSection }
152 | { readonly kind: "marker"; readonly marker: SidebarListMarker };
153
154export function sidebarListItemId(item: SidebarListItem): string {
155 return item.kind === "thread" ? item.key : sidebarMarkerId(item.marker);
156}
157
158function sectionAtSidebarSlot(items: readonly SidebarListItem[], index: number): SidebarSection {
159 let section: SidebarSection = "pinned";
160 for (let i = 0; i < index && i < items.length; i += 1) {
161 const item = items[i]!;
162 if (item.kind !== "marker") continue;
163 if (item.marker === "pinned-divider") section = "active";
164 else if (item.marker === "working-header") section = "working";
165 else if (item.marker === "snoozed-header") section = "snoozed";
166 else if (item.marker === "settled-header") section = "settled";
167 }
168 return section;
169}
170
171export type SidebarDropTarget = {
172 readonly section: "pinned" | "active" | "settled";
173 readonly pinnedOrder: readonly string[];
174 readonly activeOrder: readonly string[];
175};
176
177export function resolveSidebarDropTarget(
178 items: readonly SidebarListItem[],
179 activeKey: string,
180 overId: string,
181): SidebarDropTarget | null {
182 const activeIndex = items.findIndex((item) => sidebarListItemId(item) === activeKey);
183 const overIndex = items.findIndex((item) => sidebarListItemId(item) === overId);
184 if (activeIndex === -1 || overIndex === -1 || items[activeIndex]?.kind !== "thread") return null;
185 const moved = items.filter((_, index) => index !== activeIndex);
186 moved.splice(overIndex, 0, items[activeIndex]!);
187 const section = sectionAtSidebarSlot(moved, overIndex);
188 if (section === "working" || section === "snoozed") return null;
189 const pinnedOrder: string[] = [];
190 const activeOrder: string[] = [];
191 let currentSection: SidebarSection = "pinned";
192 for (const item of moved) {
193 if (item.kind === "marker") {
194 if (item.marker === "pinned-divider") currentSection = "active";
195 else if (
196 item.marker === "working-header" ||
197 item.marker === "snoozed-header" ||
198 item.marker === "settled-header"
199 )
200 break;
201 } else if (currentSection === "pinned") pinnedOrder.push(item.key);
202 else activeOrder.push(item.key);
203 }
204 return { section, pinnedOrder, activeOrder };
205}
206
207export type SidebarThreadDropPlan =
208 | { readonly kind: "none" }
209 | {
210 readonly kind: "reorder-pinned";
211 readonly order: readonly string[];
212 readonly assignments: ReadonlyArray<{ readonly id: string; readonly orderKey: string }>;
213 }
214 | {
215 readonly kind: "pin";
216 readonly order: readonly string[];
217 readonly orderKey: string | undefined;
218 readonly extraAssignments: ReadonlyArray<{ readonly id: string; readonly orderKey: string }>;
219 }
220 | {
221 readonly kind: "move-active";
222 readonly order: readonly string[] | null;
223 readonly assignments: ReadonlyArray<{ readonly id: string; readonly orderKey: string }>;
224 readonly unpin: boolean;
225 readonly unsettle: boolean;
226 readonly unsnooze: boolean;
227 }
228 | { readonly kind: "settle" };
229
230export type SidebarDropVerb = "pin" | "unpin" | "settle" | "unsettle" | "wake";
231
232export function resolveSidebarDropVerb(
233 from: SidebarSection,
234 to: SidebarSection | null,
235): SidebarDropVerb | null {
236 if (to === null || to === from || to === "working" || to === "snoozed") return null;
237 if (to === "pinned") return "pin";
238 if (to === "settled") return "settle";
239 if (from === "pinned") return "unpin";
240 if (from === "settled") return "unsettle";
241 return "wake";
242}
243
244export function resolveSidebarSweepKeys(
245 orderedKeys: readonly string[],
246 originKey: string,
247 targetKey: string,
248 canApply: (key: string) => boolean,
249): string[] {
250 const origin = orderedKeys.indexOf(originKey);
251 const target = orderedKeys.indexOf(targetKey);
252 if (origin === -1 || target === -1) return [];
253 return orderedKeys.slice(Math.min(origin, target), Math.max(origin, target) + 1).filter(canApply);
254}
255
256export function sidebarThreadKeyAtY(list: HTMLElement, y: number): string | null {
257 const viewport = list.closest('[data-slot="scroll-area-viewport"]')?.getBoundingClientRect();
258 const visibleY = viewport ? Math.min(Math.max(y, viewport.top), viewport.bottom - 1) : y;
259 let key: string | null = null;
260 for (const row of list.querySelectorAll<HTMLElement>("li[data-thread-item]")) {
261 if (key !== null && row.getBoundingClientRect().top > visibleY) break;
262 key = row.dataset.threadItem ?? null;
263 }
264 return key;
265}
266
267export function planSidebarThreadDrop(input: {
268 readonly activeKey: string;
269 readonly activeSection: SidebarSection;
270 readonly activePinned?: boolean;
271 readonly activeSettled?: boolean;
272 readonly supportsSettlement?: boolean;
273 readonly target: SidebarDropTarget;
274 readonly pinnedOrder: readonly string[];
275 readonly pinnedKeysById: ReadonlyMap<string, string | null | undefined>;
276 readonly reorderableKeys?: ReadonlySet<string>;
277 readonly activeOrder: readonly string[];
278 readonly activeKeysById: ReadonlyMap<string, string | null | undefined>;
279 readonly activeReorderableKeys?: ReadonlySet<string>;
280 readonly activeTimeOrdered?: boolean;
281}): SidebarThreadDropPlan {
282 const {
283 activeKey,
284 activeSection,
285 activePinned = activeSection === "pinned",
286 activeSettled = activeSection === "settled",
287 target,
288 pinnedOrder,
289 pinnedKeysById,
290 reorderableKeys,
291 activeOrder,
292 activeKeysById,
293 activeReorderableKeys,
294 } = input;
295 if (input.supportsSettlement === false && (target.section === "settled" || activeSettled)) {
296 return { kind: "none" };
297 }
298 const arrange = (
299 order: readonly string[],
300 keysById: ReadonlyMap<string, string | null | undefined>,
301 writable: ReadonlySet<string> | undefined,
302 ) => {
303 if (!writable) return planPinnedReorder({ orderedIds: order, keysById, movedId: activeKey });
304 if (!writable.has(activeKey)) return null;
305 const assignments = planPinnedReorder({
306 orderedIds: order.filter((key) => writable.has(key) || keysById.get(key) != null),
307 keysById,
308 movedId: activeKey,
309 });
310 return assignments.every(({ id }) => writable.has(id)) ? assignments : null;
311 };
312 switch (target.section) {
313 case "active": {
314 if (input.activeTimeOrdered) {
315 return activeSection === "active"
316 ? { kind: "none" }
317 : {
318 kind: "move-active",
319 order: null,
320 assignments: [],
321 unpin: activePinned,
322 unsettle: activeSettled,
323 unsnooze: activeSection === "snoozed",
324 };
325 }
326 const order = target.activeOrder;
327 if (
328 activeSection === "active" &&
329 order.length === activeOrder.length &&
330 order.every((key, index) => key === activeOrder[index])
331 ) {
332 return { kind: "none" };
333 }
334 const assignments = arrange(order, activeKeysById, activeReorderableKeys);
335 if (assignments === null) return { kind: "none" };
336 return {
337 kind: "move-active",
338 order,
339 assignments,
340 unpin: activePinned,
341 unsettle: activeSettled,
342 unsnooze: activeSection === "snoozed",
343 };
344 }
345 case "settled":
346 return activeSection === "settled" ? { kind: "none" } : { kind: "settle" };
347 case "pinned": {
348 const order = target.pinnedOrder;
349 if (
350 activeSection === "pinned" &&
351 order.length === pinnedOrder.length &&
352 order.every((key, index) => key === pinnedOrder[index])
353 ) {
354 return { kind: "none" };
355 }
356 const assignments = arrange(order, pinnedKeysById, reorderableKeys);
357 if (assignments === null) return { kind: "none" };
358 if (activeSection === "pinned") {
359 return assignments.length === 0
360 ? { kind: "none" }
361 : { kind: "reorder-pinned", order, assignments };
362 }
363 return {
364 kind: "pin",
365 order,
366 orderKey: assignments.find((assignment) => assignment.id === activeKey)?.orderKey,
367 extraAssignments: activePinned
368 ? assignments
369 : assignments.filter((assignment) => assignment.id !== activeKey),
370 };
371 }
372 }
373}
374
375export function applySidebarThreadDrop<
376 T extends Pick<
377 SidebarThreadSummary,
378 | "pinnedAt"
379 | "pinOrderKey"
380 | "activeOrderKey"
381 | "snoozedAt"
382 | "snoozedUntil"
383 | "settledAt"
384 | "settledOverride"
385 | "unsettledAt"
386 >,
387>(thread: T, section: "pinned" | "active" | "settled", now: string, orderKey?: string): T {
388 const wasSettled = thread.settledOverride === "settled";
389 const awake = { ...thread, snoozedAt: null, snoozedUntil: null };
390 if (section === "settled") {
391 return {
392 ...awake,
393 pinnedAt: null,
394 pinOrderKey: null,
395 activeOrderKey: null,
396 settledOverride: "settled",
397 settledAt: wasSettled ? (thread.settledAt ?? now) : now,
398 unsettledAt: null,
399 };
400 }
401 const resumed = wasSettled
402 ? { ...awake, settledOverride: "active" as const, settledAt: null, unsettledAt: now }
403 : awake;
404 return {
405 ...resumed,
406 pinnedAt: section === "pinned" ? (thread.pinnedAt ?? now) : null,
407 pinOrderKey: section === "pinned" ? (orderKey ?? thread.pinOrderKey) : null,
408 ...(section === "active" && orderKey !== undefined ? { activeOrderKey: orderKey } : {}),
409 };
410}
411
412type SidebarProject = {
413 id: string;
414 title: string;
415 createdAt?: string | undefined;
416 updatedAt?: string | undefined;
417};
418
419type ScopedSidebarProject = SidebarProject & {
420 environmentId: string;
421};
422
423type ScopedSidebarThread = ThreadSortInput & {
424 environmentId: string;
425 projectId: string;
426 archivedAt: string | null;
427};
428
429type LogicalSidebarProject = SidebarProject & {
430 projectKey: string;
431 memberProjectRefs: readonly {
432 environmentId: string;
433 projectId: string;
434 }[];
435};
436
437export type ThreadTraversalDirection = "previous" | "next";
438
439/**
440 * Shared-worktree checks must exclude only successful deletions, never the
441 * whole batch.
442 */
443export async function deleteSelectedThreadEntries<
444 TEntry extends { readonly threadKey: string },
445>(input: {
446 entries: readonly TEntry[];
447 delete: (
448 entry: TEntry,
449 deletedThreadKeys: ReadonlySet<string>,
450 ) => Promise<AtomCommandResult<unknown, unknown> | null>;
451}) {
452 const deletedThreadKeys = new Set<string>();
453 let firstFailure: AsyncResult.Failure<unknown, unknown> | null = null;
454
455 for (const entry of input.entries) {
456 const result = await input.delete(entry, deletedThreadKeys);
457 if (result === null) continue;
458 if (result._tag === "Failure") {
459 if (isAtomCommandInterrupted(result)) break;
460 firstFailure ??= result;
461 continue;
462 }
463 deletedThreadKeys.add(entry.threadKey);
464 }
465
466 return { deletedThreadKeys, firstFailure };
467}
468
469export async function archiveSelectedThreadEntries<
470 TEntry extends { readonly threadKey: string },
471 TResult extends { readonly _tag: "Success" | "Failure" },
472>(input: {
473 entries: readonly TEntry[];
474 archive: (entry: TEntry, onArchived: () => void) => Promise<TResult>;
475}): Promise<{
476 archivedThreadKeys: readonly string[];
477 mutationFailure: Extract<TResult, { readonly _tag: "Failure" }> | null;
478 followupFailures: readonly Extract<TResult, { readonly _tag: "Failure" }>[];
479}> {
480 const archivedThreadKeys: string[] = [];
481 const followupFailures: Extract<TResult, { readonly _tag: "Failure" }>[] = [];
482
483 for (const entry of input.entries) {
484 let didArchive = false;
485 const result = await input.archive(entry, () => {
486 didArchive = true;
487 });
488 if (didArchive || result._tag === "Success") archivedThreadKeys.push(entry.threadKey);
489 if (result._tag === "Success") continue;
490 const failure = result as Extract<TResult, { readonly _tag: "Failure" }>;
491 if (didArchive) {
492 followupFailures.push(failure);
493 continue;
494 }
495 return { archivedThreadKeys, mutationFailure: failure, followupFailures };
496 }
497
498 return { archivedThreadKeys, mutationFailure: null, followupFailures };
499}
500
501export function buildMultiSelectThreadContextMenuItems(input: {
502 count: number;
503 hasRunningThread: boolean;
504}): readonly ContextMenuItem<"mark-unread" | "archive" | "delete">[] {
505 return [
506 { id: "mark-unread", label: `Mark unread (${input.count})` },
507 {
508 id: "archive",
509 label: `Archive (${input.count})`,
510 disabled: input.hasRunningThread,
511 },
512 { id: "delete", label: `Delete (${input.count})`, destructive: true },
513 ];
514}
515
516export function isSidebarSubagentThread(thread: Pick<SidebarThreadSummary, "lineage">): boolean {
517 return thread.lineage.relationshipToParent === "subagent";
518}
519
520export function filterSidebarV2VisibleThreads<
521 T extends Pick<SidebarThreadSummary, "archivedAt" | "lineage"> & {
522 environmentId: string;
523 projectId: string;
524 },
525>(threads: readonly T[], scopedProjectKeys: ReadonlySet<string> | null): T[] {
526 return threads.filter(
527 (thread) =>
528 thread.archivedAt === null &&
529 !isSidebarSubagentThread(thread) &&
530 (scopedProjectKeys === null ||
531 scopedProjectKeys.has(`${thread.environmentId}:${thread.projectId}`)),
532 );
533}
534
535export function getSidebarForkParentThreadId(
536 thread: Pick<SidebarThreadSummary, "forkedFrom" | "lineage">,
537) {
538 if (thread.lineage.relationshipToParent !== "fork") {
539 return null;
540 }
541 return thread.forkedFrom?.type === "run"
542 ? thread.forkedFrom.threadId
543 : thread.lineage.parentThreadId;
544}
545
546export function buildBulkTitleRegenerationContextMenuItem(input: {
547 supportedCount: number;
548 actionableCount: number;
549}): ContextMenuItem<"regenerate-title"> | null {
550 if (input.supportedCount === 0) return null;
551 if (input.actionableCount === 0) {
552 return {
553 id: "regenerate-title",
554 label: `Regenerating… (${input.supportedCount})`,
555 disabled: true,
556 };
557 }
558 return {
559 id: "regenerate-title",
560 label: `Regenerate titles (${input.actionableCount})`,
561 };
562}
563
564export function buildBulkUnpinContextMenuItem(input: {
565 pinnedCount: number;
566}): ContextMenuItem<"unpin"> | null {
567 if (input.pinnedCount === 0) return null;
568 return { id: "unpin", label: `Unpin (${input.pinnedCount})` };
569}
570
571export interface ThreadStatusPill {
572 label:
573 | "Working"
574 | "Connecting"
575 | "Completed"
576 | "Pending Approval"
577 | "Awaiting Input"
578 | "Waiting"
579 | "Plan Ready";
580 colorClass: string;
581 dotClass: string;
582 pulse: boolean;
583}
584
585const THREAD_STATUS_PRIORITY: Record<ThreadStatusPill["label"], number> = {
586 "Pending Approval": 5,
587 "Awaiting Input": 4,
588 Working: 3,
589 Connecting: 3,
590 Waiting: 2.5,
591 "Plan Ready": 2,
592 Completed: 1,
593};
594
595type ThreadStatusInput = Pick<
596 SidebarThreadSummary,
597 | "hasActionableProposedPlan"
598 | "hasPendingApprovals"
599 | "hasPendingUserInput"
600 | "pendingSubagentRequest"
601 | "interactionMode"
602 | "latestRun"
603 | "runtime"
604> & {
605 lastVisitedAt?: string | null | undefined;
606 pendingBackgroundTasks?: SidebarThreadSummary["pendingBackgroundTasks"] | undefined;
607};
608
609export interface ThreadJumpHintVisibilityController {
610 sync: (shouldShow: boolean) => void;
611 dispose: () => void;
612}
613
614export function resolveSidebarStageBadgeLabel(input: {
615 primaryServerVersion: string | null | undefined;
616 fallbackStageLabel: string;
617}): string {
618 return resolveServerBackedAppStageLabel(input);
619}
620
621export function createThreadJumpHintVisibilityController(input: {
622 delayMs: number;
623 onVisibilityChange: (visible: boolean) => void;
624 setTimeoutFn?: typeof globalThis.setTimeout;
625 clearTimeoutFn?: typeof globalThis.clearTimeout;
626}): ThreadJumpHintVisibilityController {
627 const setTimeoutFn = input.setTimeoutFn ?? globalThis.setTimeout;
628 const clearTimeoutFn = input.clearTimeoutFn ?? globalThis.clearTimeout;
629 let isVisible = false;
630 let timeoutId: NodeJS.Timeout | null = null;
631
632 const clearPendingShow = () => {
633 if (timeoutId === null) {
634 return;
635 }
636 clearTimeoutFn(timeoutId);
637 timeoutId = null;
638 };
639
640 return {
641 sync: (shouldShow) => {
642 if (!shouldShow) {
643 clearPendingShow();
644 if (isVisible) {
645 isVisible = false;
646 input.onVisibilityChange(false);
647 }
648 return;
649 }
650
651 if (isVisible || timeoutId !== null) {
652 return;
653 }
654
655 timeoutId = setTimeoutFn(() => {
656 timeoutId = null;
657 isVisible = true;
658 input.onVisibilityChange(true);
659 }, input.delayMs);
660 },
661 dispose: () => {
662 clearPendingShow();
663 },
664 };
665}
666
667export function useThreadJumpHintVisibility(): {
668 showThreadJumpHints: boolean;
669 updateThreadJumpHintsVisibility: (shouldShow: boolean) => void;
670} {
671 const [showThreadJumpHints, setShowThreadJumpHints] = React.useState(false);
672 const controllerRef = React.useRef<ThreadJumpHintVisibilityController | null>(null);
673
674 React.useEffect(() => {
675 const controller = createThreadJumpHintVisibilityController({
676 delayMs: THREAD_JUMP_HINT_SHOW_DELAY_MS,
677 onVisibilityChange: (visible) => {
678 setShowThreadJumpHints(visible);
679 },
680 setTimeoutFn: window.setTimeout.bind(window),
681 clearTimeoutFn: window.clearTimeout.bind(window),
682 });
683 controllerRef.current = controller;
684
685 return () => {
686 controller.dispose();
687 controllerRef.current = null;
688 };
689 }, []);
690
691 const updateThreadJumpHintsVisibility = React.useCallback((shouldShow: boolean) => {
692 controllerRef.current?.sync(shouldShow);
693 }, []);
694
695 return {
696 showThreadJumpHints,
697 updateThreadJumpHintsVisibility,
698 };
699}
700
701export function resolveThreadLastVisitedAt(
702 serverLastVisitedAt: string | null | undefined,
703 localLastVisitedAt: string | undefined,
704): string | undefined {
705 // When the server tracks visits it is authoritative — including explicit
706 // rewinds from mark-unread, which a newer browser-local watermark must not
707 // mask. The local value only carries servers without visited tracking.
708 if (serverLastVisitedAt === undefined) return localLastVisitedAt;
709 return serverLastVisitedAt ?? undefined;
710}
711
712export function hasUnseenCompletion(thread: ThreadStatusInput): boolean {
713 if (!thread.latestRun?.completedAt) return false;
714 const completedAt = Date.parse(thread.latestRun.completedAt);
715 if (Number.isNaN(completedAt)) return false;
716 if (!thread.lastVisitedAt) return false;
717
718 const lastVisitedAt = Date.parse(thread.lastVisitedAt);
719 if (Number.isNaN(lastVisitedAt)) return true;
720 return completedAt > lastVisitedAt;
721}
722
723export function shouldClearThreadSelectionOnMouseDown(target: HTMLElement | null): boolean {
724 if (target === null) return true;
725 return !target.closest(THREAD_SELECTION_SAFE_SELECTOR);
726}
727
728// A double-click dispatches two `click` events before `dblclick`: the first has
729// `detail === 1`, the second `detail === 2`. The second click must not run the
730// row's single-click navigation, otherwise double-click-to-rename would also
731// navigate. `MouseEvent.detail` is 0 for synthetic/keyboard activations, which
732// still count as a normal single activation.
733export function isTrailingDoubleClick(detail: number): boolean {
734 return detail > 1;
735}
736
737function nodeClosest(node: object | null, selector: string): unknown {
738 if (node === null || !("closest" in node) || typeof node.closest !== "function") return null;
739 return node.closest(selector);
740}
741
742export function isSidebarNestedLinkClick(target: EventTarget | null): boolean {
743 if (target == null || typeof target !== "object") return false;
744 if (nodeClosest(target, "a[href]") !== null) return true;
745 const parent =
746 "parentElement" in target &&
747 target.parentElement !== null &&
748 typeof target.parentElement === "object"
749 ? target.parentElement
750 : null;
751 return nodeClosest(parent, "a[href]") !== null;
752}
753
754export function shouldCreateNewThreadInCurrentProject(
755 shiftKey: boolean,
756 projectGroupCount: number,
757): boolean {
758 return shiftKey || projectGroupCount <= 1;
759}
760
761export function orderItemsByPreferredIds<TItem, TId>(input: {
762 items: readonly TItem[];
763 preferredIds: readonly TId[];
764 getId: (item: TItem) => TId;
765 getPreferenceIds?: (item: TItem) => readonly TId[];
766}): TItem[] {
767 const { getId, getPreferenceIds, items, preferredIds } = input;
768 if (preferredIds.length === 0) {
769 return [...items];
770 }
771
772 const indexesByPreferenceId = new Map<TId, number[]>();
773 for (const [index, item] of items.entries()) {
774 const preferenceIds = getPreferenceIds?.(item) ?? [getId(item)];
775 for (const preferenceId of new Set(preferenceIds)) {
776 const indexes = indexesByPreferenceId.get(preferenceId);
777 if (indexes) {
778 indexes.push(index);
779 } else {
780 indexesByPreferenceId.set(preferenceId, [index]);
781 }
782 }
783 }
784
785 const emittedIndexes = new Set<number>();
786 const ordered = preferredIds.flatMap((id) => {
787 const index = indexesByPreferenceId
788 .get(id)
789 ?.find((candidate) => !emittedIndexes.has(candidate));
790 if (index === undefined) {
791 return [];
792 }
793 emittedIndexes.add(index);
794 return [items[index]!];
795 });
796 const remaining = items.filter((_, index) => !emittedIndexes.has(index));
797 return [...ordered, ...remaining];
798}
799
800export function getSidebarThreadIdsToPrewarm<TThreadId>(
801 visibleThreadIds: readonly TThreadId[],
802 limit = SIDEBAR_THREAD_PREWARM_LIMIT,
803): TThreadId[] {
804 return visibleThreadIds.slice(0, Math.max(0, limit));
805}
806
807export function resolveAdjacentThreadId<T>(input: {
808 threadIds: readonly T[];
809 currentThreadId: T | null;
810 direction: ThreadTraversalDirection;
811}): T | null {
812 const { currentThreadId, direction, threadIds } = input;
813
814 if (threadIds.length === 0) {
815 return null;
816 }
817
818 if (currentThreadId === null) {
819 return direction === "previous" ? (threadIds.at(-1) ?? null) : (threadIds[0] ?? null);
820 }
821
822 const currentIndex = threadIds.indexOf(currentThreadId);
823 if (currentIndex === -1) {
824 return null;
825 }
826
827 if (direction === "previous") {
828 return currentIndex > 0 ? (threadIds[currentIndex - 1] ?? null) : null;
829 }
830
831 return currentIndex < threadIds.length - 1 ? (threadIds[currentIndex + 1] ?? null) : null;
832}
833
834export function isContextMenuPointerDown(input: {
835 button: number;
836 ctrlKey: boolean;
837 isMac: boolean;
838}): boolean {
839 if (input.button === 2) return true;
840 return input.isMac && input.button === 0 && input.ctrlKey;
841}
842
843export function resolveThreadRowClassName(input: {
844 isActive: boolean;
845 isSelected: boolean;
846}): string {
847 const baseClassName =
848 "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";
849
850 if (input.isSelected && input.isActive) {
851 return cn(
852 baseClassName,
853 "bg-sidebar-row-active text-sidebar-foreground font-medium hover:bg-sidebar-row-active hover:text-sidebar-foreground",
854 );
855 }
856
857 if (input.isSelected) {
858 return cn(
859 baseClassName,
860 "bg-sidebar-row-selected text-sidebar-foreground hover:bg-sidebar-row-active hover:text-sidebar-foreground",
861 );
862 }
863
864 if (input.isActive) {
865 return cn(
866 baseClassName,
867 "bg-sidebar-row-active text-sidebar-foreground font-medium hover:bg-sidebar-row-active hover:text-sidebar-foreground",
868 );
869 }
870
871 return cn(
872 baseClassName,
873 "text-sidebar-muted-foreground/80 hover:bg-sidebar-row-hover hover:text-sidebar-foreground",
874 );
875}
876
877export type SidebarThreadStatus =
878 | "approval"
879 | "input"
880 | "working"
881 | "waiting"
882 | "failed"
883 | "limited"
884 | "ready";
885
886export function shouldRecedeSidebarThread(input: {
887 status: SidebarThreadStatus;
888 isUnread: boolean;
889 isWoke: boolean;
890 isActive: boolean;
891 isSelected: boolean;
892}): boolean {
893 if (input.isActive || input.isSelected || input.status === "input") return false;
894 if (input.status === "working" || input.status === "waiting") return true;
895 if (input.status === "ready" || input.status === "approval") {
896 return !input.isUnread && !input.isWoke;
897 }
898 return false;
899}
900
901type SidebarThreadStatusInput = Pick<
902 SidebarThreadSummary,
903 "hasPendingApprovals" | "hasPendingUserInput" | "pendingSubagentRequest" | "runtime"
904>;
905
906export function resolveSidebarThreadStatus(thread: SidebarThreadStatusInput): SidebarThreadStatus {
907 if (thread.hasPendingApprovals || thread.pendingSubagentRequest === "approval") {
908 return "approval";
909 }
910 if (thread.hasPendingUserInput || thread.pendingSubagentRequest === "user_input") {
911 return "input";
912 }
913 if (
914 thread.runtime !== null &&
915 ["preparing", "queued", "starting", "running", "waiting"].includes(thread.runtime.status)
916 ) {
917 return "working";
918 }
919 if (thread.runtime?.status === "idle") {
920 return "waiting";
921 }
922 if (thread.runtime?.status === "failed") {
923 return thread.runtime.lastErrorClass === "usage_limit" ? "limited" : "failed";
924 }
925 return "ready";
926}
927
928export type SidebarV2TopStatusKind =
929 | "approval"
930 | "done"
931 | "failed"
932 | "limited"
933 | "input"
934 | "waiting"
935 | "woke"
936 | "working";
937
938export function resolveSidebarV2TopStatus(input: {
939 readonly status: SidebarThreadStatus;
940 readonly isUnread: boolean;
941 readonly isWoke: boolean;
942}): SidebarV2TopStatusKind | null {
943 if (input.status === "working") {
944 return "working";
945 }
946 if (input.status === "waiting") {
947 return "waiting";
948 }
949 if (input.status === "approval") {
950 return "approval";
951 }
952 if (input.status === "input") {
953 return "input";
954 }
955 if (input.status === "failed" || input.status === "limited") {
956 return input.status;
957 }
958 if (input.isWoke) {
959 return "woke";
960 }
961 return input.isUnread ? "done" : null;
962}
963
964export function shouldShowSidebarV2Duration(status: SidebarThreadStatus): boolean {
965 return status === "working";
966}
967
968export function firstValidTimestampMs(
969 ...candidates: ReadonlyArray<string | null | undefined>
970): number {
971 for (const candidate of candidates) {
972 if (candidate == null) continue;
973 const parsed = Date.parse(candidate);
974 if (!Number.isNaN(parsed)) return parsed;
975 }
976 return 0;
977}
978
979export { sortActiveThreadsByOrderKey as sortThreadsForSidebar } from "@t3tools/client-runtime/state/thread-sort";
980export {
981 isThreadWorking as isSidebarThreadWorking,
982 sortInboxThreadsByReturn,
983 sortWorkingThreadsBySend,
984} from "@t3tools/client-runtime/state/thread-inbox";
985
986export { pinOrderKeyBetween } from "@t3tools/client-runtime/state/thread-sort";
987export { sortPinnedThreadsByOrderKey as sortPinnedThreadsForSidebar } from "@t3tools/client-runtime/state/thread-sort";
988
989const EMPTY_CONTENT_MATCH_KEYS: ReadonlySet<string> = new Set<string>();
990
991export function searchSidebarThreads<
992 T extends {
993 readonly environmentId: EnvironmentId;
994 readonly id: ThreadId;
995 readonly title: string;
996 } & Parameters<typeof threadPullRequestSearchTerms>[0],
997>(
998 threads: readonly T[],
999 query: string,
1000 contentMatchKeys: ReadonlySet<string> = EMPTY_CONTENT_MATCH_KEYS,
1001): T[] {
1002 const normalizedQuery = query.trim().toLowerCase();
1003 if (normalizedQuery.length === 0) return [];
1004 const titleMatches: T[] = [];
1005 const contentMatches: T[] = [];
1006 for (const thread of threads) {
1007 const matchesTitle = [thread.title, ...threadPullRequestSearchTerms(thread)].some((term) =>
1008 term.toLowerCase().includes(normalizedQuery),
1009 );
1010 if (matchesTitle) {
1011 titleMatches.push(thread);
1012 } else if (
1013 contentMatchKeys.size > 0 &&
1014 contentMatchKeys.has(
1015 threadSearchMatchKey({ environmentId: thread.environmentId, threadId: thread.id }),
1016 )
1017 ) {
1018 contentMatches.push(thread);
1019 }
1020 }
1021 return [...titleMatches, ...contentMatches];
1022}
1023
1024export function pullRequestMatchesSearchQuery(
1025 pullRequest: Parameters<typeof threadPullRequestSearchTerms>[0],
1026 query: string,
1027): boolean {
1028 const normalizedQuery = normalizeSearchText(query);
1029 if (normalizedQuery.length === 0) return false;
1030 const haystack = normalizeSearchText(threadPullRequestSearchTerms(pullRequest).join(" "));
1031 return normalizedQuery.split(" ").every((token) => haystack.includes(token));
1032}
1033
1034export function filterSidebarProjectScopeItems<TItem extends { readonly value: string }>(input: {
1035 items: readonly TItem[];
1036 query: string;
1037 matches: (item: TItem, query: string) => boolean;
1038}): readonly TItem[] {
1039 const query = input.query.trim();
1040 if (query.length === 0) return input.items;
1041 return input.items.filter((item) => item.value !== "all" && input.matches(item, query));
1042}
1043
1044export interface SidebarProjectScopeMenuState {
1045 readonly open: boolean;
1046 readonly query: string;
1047}
1048
1049export type SidebarProjectScopeMenuAction =
1050 | { readonly type: "query-changed"; readonly query: string }
1051 | { readonly type: "open-changed"; readonly open: boolean }
1052 | { readonly type: "project-settings-opened" };
1053
1054export function reduceSidebarProjectScopeMenuState(
1055 state: SidebarProjectScopeMenuState,
1056 action: SidebarProjectScopeMenuAction,
1057): SidebarProjectScopeMenuState {
1058 switch (action.type) {
1059 case "query-changed":
1060 return { ...state, query: action.query };
1061 case "open-changed":
1062 return { open: action.open, query: "" };
1063 case "project-settings-opened":
1064 return { open: false, query: "" };
1065 }
1066}
1067
1068export function resolveWorkingStartedAt(
1069 thread: Pick<SidebarThreadSummary, "latestRun" | "runtime">,
1070): string | null {
1071 return resolveThreadWorkingStartedAt(thread);
1072}
1073
1074export function formatWorkingDurationLabel(elapsedMs: number): string {
1075 const seconds = Number.isFinite(elapsedMs) ? Math.max(0, Math.floor(elapsedMs / 1000)) : 0;
1076 if (seconds < 60) return `${seconds}s`;
1077 const minutes = Math.floor(seconds / 60);
1078 if (minutes < 60) return `${minutes}m`;
1079 return `${Math.floor(minutes / 60)}h ${minutes % 60}m`;
1080}
1081
1082export function resolveThreadStatusPill(input: {
1083 thread: ThreadStatusInput;
1084}): ThreadStatusPill | null {
1085 const { thread } = input;
1086
1087 if (thread.hasPendingApprovals || thread.pendingSubagentRequest === "approval") {
1088 return {
1089 label: "Pending Approval",
1090 colorClass: "text-amber-600 dark:text-amber-300/90",
1091 dotClass: "bg-amber-500 dark:bg-amber-300/90",
1092 pulse: false,
1093 };
1094 }
1095
1096 if (thread.hasPendingUserInput || thread.pendingSubagentRequest === "user_input") {
1097 return {
1098 label: "Awaiting Input",
1099 colorClass: "text-indigo-600 dark:text-indigo-300/90",
1100 dotClass: "bg-indigo-500 dark:bg-indigo-300/90",
1101 pulse: false,
1102 };
1103 }
1104
1105 if (thread.runtime?.status === "running" || thread.runtime?.status === "waiting") {
1106 return {
1107 label: "Working",
1108 colorClass: "text-sky-600 dark:text-sky-300/80",
1109 dotClass: "bg-sky-500 dark:bg-sky-300/80",
1110 pulse: true,
1111 };
1112 }
1113
1114 if (
1115 thread.runtime?.status === "preparing" ||
1116 thread.runtime?.status === "starting" ||
1117 thread.runtime?.status === "queued"
1118 ) {
1119 return {
1120 label: "Connecting",
1121 colorClass: "text-sky-600 dark:text-sky-300/80",
1122 dotClass: "bg-sky-500 dark:bg-sky-300/80",
1123 pulse: true,
1124 };
1125 }
1126
1127 if (backgroundWorkHoldsCompletion(thread.pendingBackgroundTasks ?? [])) {
1128 return {
1129 label: "Waiting",
1130 colorClass: "text-sidebar-muted-foreground",
1131 dotClass: "bg-sidebar-muted-foreground",
1132 pulse: false,
1133 };
1134 }
1135
1136 const hasPlanReadyPrompt =
1137 !thread.hasPendingUserInput &&
1138 thread.interactionMode === "plan" &&
1139 isLatestRunSettled(thread.latestRun, thread.runtime) &&
1140 thread.hasActionableProposedPlan;
1141 if (hasPlanReadyPrompt) {
1142 return {
1143 label: "Plan Ready",
1144 colorClass: "text-violet-600 dark:text-violet-300/90",
1145 dotClass: "bg-violet-500 dark:bg-violet-300/90",
1146 pulse: false,
1147 };
1148 }
1149
1150 if (hasUnseenCompletion(thread)) {
1151 return {
1152 label: "Completed",
1153 colorClass: "text-emerald-600 dark:text-emerald-300/90",
1154 dotClass: "bg-emerald-500 dark:bg-emerald-300/90",
1155 pulse: false,
1156 };
1157 }
1158
1159 return null;
1160}
1161
1162export function resolveProjectStatusIndicator(
1163 statuses: ReadonlyArray<ThreadStatusPill | null>,
1164): ThreadStatusPill | null {
1165 let highestPriorityStatus: ThreadStatusPill | null = null;
1166
1167 for (const status of statuses) {
1168 if (status === null) continue;
1169 if (
1170 highestPriorityStatus === null ||
1171 THREAD_STATUS_PRIORITY[status.label] > THREAD_STATUS_PRIORITY[highestPriorityStatus.label]
1172 ) {
1173 highestPriorityStatus = status;
1174 }
1175 }
1176
1177 return highestPriorityStatus;
1178}
1179
1180export function getFallbackThreadIdAfterDelete<
1181 T extends Pick<Thread, "id" | "projectId" | "createdAt" | "updatedAt"> & ThreadSortInput,
1182>(input: {
1183 threads: readonly T[];
1184 deletedThreadId: T["id"];
1185 sortOrder: SidebarThreadSortOrder;
1186 deletedThreadIds?: ReadonlySet<T["id"]>;
1187}): T["id"] | null {
1188 const { deletedThreadId, deletedThreadIds, sortOrder, threads } = input;
1189 const deletedThread = threads.find((thread) => thread.id === deletedThreadId);
1190 if (!deletedThread) {
1191 return null;
1192 }
1193
1194 return (
1195 sortThreads(
1196 threads.filter(
1197 (thread) =>
1198 thread.projectId === deletedThread.projectId &&
1199 thread.id !== deletedThreadId &&
1200 !deletedThreadIds?.has(thread.id),
1201 ),
1202 sortOrder,
1203 )[0]?.id ?? null
1204 );
1205}
1206export function getProjectSortTimestamp(
1207 project: SidebarProject,
1208 projectThreads: readonly ThreadSortInput[],
1209 sortOrder: Exclude<SidebarProjectSortOrder, "manual">,
1210): number {
1211 if (projectThreads.length > 0) {
1212 return projectThreads.reduce(
1213 (latest, thread) => Math.max(latest, getThreadSortTimestamp(thread, sortOrder)),
1214 Number.NEGATIVE_INFINITY,
1215 );
1216 }
1217
1218 if (sortOrder === "created_at") {
1219 return toSortableTimestamp(project.createdAt) ?? Number.NEGATIVE_INFINITY;
1220 }
1221 return toSortableTimestamp(project.updatedAt ?? project.createdAt) ?? Number.NEGATIVE_INFINITY;
1222}
1223
1224function sortProjectsByActivity<TProject extends SidebarProject>(
1225 projects: readonly TProject[],
1226 sortOrder: SidebarProjectSortOrder,
1227 getProjectThreads: (project: TProject) => readonly ThreadSortInput[],
1228 compareTies: (left: TProject, right: TProject) => number,
1229): TProject[] {
1230 if (sortOrder === "manual") {
1231 return [...projects];
1232 }
1233
1234 // Each project's timestamp walks all of its threads, so compute it once
1235 // per project instead of once per comparison.
1236 return projects
1237 .map((project) => ({
1238 project,
1239 timestamp: getProjectSortTimestamp(project, getProjectThreads(project), sortOrder),
1240 }))
1241 .sort((left, right) => {
1242 const byTimestamp =
1243 right.timestamp === left.timestamp ? 0 : right.timestamp > left.timestamp ? 1 : -1;
1244 return byTimestamp || compareTies(left.project, right.project);
1245 })
1246 .map(({ project }) => project);
1247}
1248
1249export function sortProjectsForSidebar<
1250 TProject extends SidebarProject,
1251 TThread extends Pick<Thread, "projectId" | "createdAt" | "updatedAt"> & ThreadSortInput,
1252>(
1253 projects: readonly TProject[],
1254 threads: readonly TThread[],
1255 sortOrder: SidebarProjectSortOrder,
1256): TProject[] {
1257 const threadsByProjectId = new Map<string, TThread[]>();
1258 for (const thread of threads) {
1259 const existing = threadsByProjectId.get(thread.projectId) ?? [];
1260 existing.push(thread);
1261 threadsByProjectId.set(thread.projectId, existing);
1262 }
1263
1264 return sortProjectsByActivity(
1265 projects,
1266 sortOrder,
1267 (project) => threadsByProjectId.get(project.id) ?? [],
1268 (left, right) => left.title.localeCompare(right.title) || left.id.localeCompare(right.id),
1269 );
1270}
1271
1272export function sortLogicalProjectsForSidebar<
1273 TProject extends LogicalSidebarProject,
1274 TThread extends ScopedSidebarThread,
1275>(
1276 projects: readonly TProject[],
1277 threads: readonly TThread[],
1278 sortOrder: SidebarProjectSortOrder,
1279): TProject[] {
1280 const groupKeyByProjectRef = new Map(
1281 projects.flatMap((project) =>
1282 project.memberProjectRefs.map(
1283 (projectRef) =>
1284 [`${projectRef.environmentId}\0${projectRef.projectId}`, project.projectKey] as const,
1285 ),
1286 ),
1287 );
1288 const threadsByProjectKey = new Map<string, TThread[]>();
1289 for (const thread of threads) {
1290 if (thread.archivedAt !== null) continue;
1291 const projectKey = groupKeyByProjectRef.get(`${thread.environmentId}\0${thread.projectId}`);
1292 if (!projectKey) continue;
1293 const existing = threadsByProjectKey.get(projectKey);
1294 if (existing) {
1295 existing.push(thread);
1296 } else {
1297 threadsByProjectKey.set(projectKey, [thread]);
1298 }
1299 }
1300
1301 return sortProjectsByActivity(
1302 projects,
1303 sortOrder,
1304 (project) => threadsByProjectKey.get(project.projectKey) ?? [],
1305 (left, right) =>
1306 left.title.localeCompare(right.title) || left.projectKey.localeCompare(right.projectKey),
1307 );
1308}
1309
1310export function sortSidebarV2ProjectGroups<
1311 TProject extends LogicalSidebarProject,
1312 TThread extends ScopedSidebarThread & Pick<SidebarThreadSummary, "lineage">,
1313>(
1314 projects: readonly TProject[],
1315 threads: readonly TThread[],
1316 sortOrder: SidebarProjectSortOrder,
1317): TProject[] {
1318 return sortLogicalProjectsForSidebar(
1319 projects,
1320 filterSidebarV2VisibleThreads(threads, null),
1321 sortOrder,
1322 );
1323}
1324
1325export function sortScopedProjectsForSidebar<
1326 TProject extends ScopedSidebarProject,
1327 TThread extends ScopedSidebarThread,
1328>(
1329 projects: readonly TProject[],
1330 threads: readonly TThread[],
1331 sortOrder: SidebarProjectSortOrder,
1332): TProject[] {
1333 const scopedKey = (environmentId: string, projectId: string) =>
1334 `${environmentId}\u0000${projectId}`;
1335 const threadsByProject = new Map<string, TThread[]>();
1336 for (const thread of threads) {
1337 if (thread.archivedAt !== null) {
1338 continue;
1339 }
1340 const key = scopedKey(thread.environmentId, thread.projectId);
1341 const existing = threadsByProject.get(key) ?? [];
1342 existing.push(thread);
1343 threadsByProject.set(key, existing);
1344 }
1345
1346 return sortProjectsByActivity(
1347 projects,
1348 sortOrder,
1349 (project) => threadsByProject.get(scopedKey(project.environmentId, project.id)) ?? [],
1350 (left, right) =>
1351 left.title.localeCompare(right.title) ||
1352 left.environmentId.localeCompare(right.environmentId) ||
1353 left.id.localeCompare(right.id),
1354 );
1355}