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

Sidebar.logic.ts

1,216 lines40.3 KB

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