Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

Sidebar.logic.ts

1,349 lines42.7 KB

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