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

Sidebar.logic.ts

1,233 lines41.0 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​
200/** What dropping in `to` does to a thread lifted from `from`, for the badge
201 on the lifted row. Null while reordering inside one section and for the
202 snoozed shelf, which cannot be a drop target. */
203export type SidebarDropVerb = "pin" | "unpin" | "settle" | "unsettle" | "wake";
204​
205export function resolveSidebarDropVerb(
206 from: SidebarSection,
207 to: SidebarSection | null,
208): SidebarDropVerb | null {
209 if (to === null || to === from || to === "snoozed") return null;
210 if (to === "pinned") return "pin";
211 if (to === "settled") return "settle";
212 if (from === "pinned") return "unpin";
213 if (from === "settled") return "unsettle";
214 return "wake";
216​
217export function planSidebarThreadDrop(input: {
218 readonly activeKey: string;
219 readonly activeSection: SidebarSection;
220 /** Snoozed threads can retain pinning and settlement beneath the shelf. */
221 readonly activePinned?: boolean;
222 readonly activeSettled?: boolean;
223 readonly supportsSettlement?: boolean;
224 readonly target: SidebarDropTarget;
225 /** All pinned keys in displayed order before the drop. */
226 readonly pinnedOrder: readonly string[];
227 readonly pinnedKeysById: ReadonlyMap<string, string | null | undefined>;
228 readonly reorderableKeys?: ReadonlySet<string>;
229 readonly activeOrder: readonly string[];
230 readonly activeKeysById: ReadonlyMap<string, string | null | undefined>;
231 readonly activeReorderableKeys?: ReadonlySet<string>;
232}): SidebarThreadDropPlan {
233 const {
234 activeKey,
235 activeSection,
236 activePinned = activeSection === "pinned",
237 activeSettled = activeSection === "settled",
238 target,
239 pinnedOrder,
240 pinnedKeysById,
241 reorderableKeys,
242 activeOrder,
243 activeKeysById,
244 activeReorderableKeys,
245 } = input;
246 if (input.supportsSettlement === false && (target.section === "settled" || activeSettled)) {
247 return { kind: "none" };
248 }
249 switch (target.section) {
250 case "active": {
251 const order = target.activeOrder;
252 if (
253 activeSection === "active" &&
254 order.length === activeOrder.length &&
255 order.every((key, index) => key === activeOrder[index])
256 ) {
257 return { kind: "none" };
258 }
259 const assignments = planPinnedReorder({
260 orderedIds: order,
261 keysById: activeKeysById,
262 movedId: activeKey,
263 });
264 if (activeReorderableKeys && assignments.some(({ id }) => !activeReorderableKeys.has(id))) {
265 return { kind: "none" };
266 }
267 return {
268 kind: "move-active",
269 order,
270 assignments,
271 unpin: activePinned,
272 unsettle: activeSettled,
273 unsnooze: activeSection === "snoozed",
274 };
275 }
276 case "settled":
277 return activeSection === "settled" ? { kind: "none" } : { kind: "settle" };
278 case "pinned": {
279 const order = target.pinnedOrder;
280 // Dropped back where it started: nothing to write.
281 if (
282 activeSection === "pinned" &&
283 order.length === pinnedOrder.length &&
284 order.every((key, index) => key === pinnedOrder[index])
285 ) {
286 return { kind: "none" };
287 }
288 const assignments = planPinnedReorder({
289 orderedIds: order,
290 keysById: pinnedKeysById,
291 movedId: activeKey,
292 });
293 if (reorderableKeys && assignments.some(({ id }) => !reorderableKeys.has(id))) {
294 return { kind: "none" };
295 }
296 if (activeSection === "pinned") {
297 return assignments.length === 0
298 ? { kind: "none" }
299 : { kind: "reorder-pinned", order, assignments };
300 }
301 return {
302 kind: "pin",
303 order,
304 orderKey: assignments.find((assignment) => assignment.id === activeKey)?.orderKey,
305 extraAssignments: activePinned
306 ? assignments
307 : assignments.filter((assignment) => assignment.id !== activeKey),
308 };
309 }
310 }
312​
313/** Project a drop's lifecycle fields before sorting its destination. Reusing
314 the server's re-entry rules keeps the preview in place when events arrive. */
315export function applySidebarThreadDrop<
316 T extends Pick<
317 SidebarThreadSummary,
318 | "pinnedAt"
319 | "pinOrderKey"
320 | "activeOrderKey"
321 | "snoozedAt"
322 | "snoozedUntil"
323 | "settledAt"
324 | "settledOverride"
325 | "unsettledAt"
326 >,
327>(thread: T, section: "pinned" | "active" | "settled", now: string, orderKey?: string): T {
328 const wasSettled = thread.settledOverride === "settled";
329 const awake = { ...thread, snoozedAt: null, snoozedUntil: null };
330 if (section === "settled") {
331 return {
332 ...awake,
333 pinnedAt: null,
334 pinOrderKey: null,
335 activeOrderKey: null,
336 settledOverride: "settled",
337 settledAt: wasSettled ? (thread.settledAt ?? now) : now,
338 unsettledAt: null,
339 };
340 }
341 const resumed = wasSettled
342 ? { ...awake, settledOverride: "active" as const, settledAt: null, unsettledAt: now }
343 : awake;
344 return {
345 ...resumed,
346 pinnedAt: section === "pinned" ? (thread.pinnedAt ?? now) : null,
347 pinOrderKey: section === "pinned" ? (orderKey ?? thread.pinOrderKey) : null,
348 ...(section === "active" && orderKey !== undefined ? { activeOrderKey: orderKey } : {}),
349 };
351​
352type SidebarProject = {
353 id: string;
354 title: string;
355 createdAt?: string | undefined;
356 updatedAt?: string | undefined;
357};
358​
359type ScopedSidebarProject = SidebarProject & {
360 environmentId: string;
361};
362​
363type ScopedSidebarThread = ThreadSortInput & {
364 environmentId: string;
365 projectId: string;
366 archivedAt: string | null;
367};
368​
369type LogicalSidebarProject = SidebarProject & {
370 projectKey: string;
371 memberProjectRefs: readonly {
372 environmentId: string;
373 projectId: string;
374 }[];
375};
376​
377export type ThreadTraversalDirection = "previous" | "next";
378​
379/**
380 * Shared-worktree checks must exclude only successful deletions, never the
381 * whole batch. A null result skips an entry that the caller can no longer find.
382 */
383export async function deleteSelectedThreadEntries<
384 TEntry extends { readonly threadKey: string },
385>(input: {
386 entries: readonly TEntry[];
387 delete: (
388 entry: TEntry,
389 deletedThreadKeys: ReadonlySet<string>,
390 ) => Promise<AtomCommandResult<unknown, unknown> | null>;
391}) {
392 const deletedThreadKeys = new Set<string>();
393 let firstFailure: AsyncResult.Failure<unknown, unknown> | null = null;
394​
395 for (const entry of input.entries) {
396 const result = await input.delete(entry, deletedThreadKeys);
397 if (result === null) continue;
398 if (result._tag === "Failure") {
399 if (isAtomCommandInterrupted(result)) break;
400 firstFailure ??= result;
401 continue;
402 }
403 deletedThreadKeys.add(entry.threadKey);
404 }
405​
406 return { deletedThreadKeys, firstFailure };
408​
409export async function archiveSelectedThreadEntries<
410 TEntry extends { readonly threadKey: string },
411 TResult extends { readonly _tag: "Success" | "Failure" },
412>(input: {
413 entries: readonly TEntry[];
414 archive: (entry: TEntry, onArchived: () => void) => Promise<TResult>;
415}): Promise<{
416 archivedThreadKeys: readonly string[];
417 mutationFailure: Extract<TResult, { readonly _tag: "Failure" }> | null;
418 followupFailures: readonly Extract<TResult, { readonly _tag: "Failure" }>[];
419}> {
420 const archivedThreadKeys: string[] = [];
421 const followupFailures: Extract<TResult, { readonly _tag: "Failure" }>[] = [];
422​
423 for (const entry of input.entries) {
424 let didArchive = false;
425 const result = await input.archive(entry, () => {
426 didArchive = true;
427 });
428 if (didArchive || result._tag === "Success") {
429 archivedThreadKeys.push(entry.threadKey);
430 }
431 if (result._tag === "Success") continue;
432 const failure = result as Extract<TResult, { readonly _tag: "Failure" }>;
433 if (didArchive) {
434 followupFailures.push(failure);
435 continue;
436 }
437 return { archivedThreadKeys, mutationFailure: failure, followupFailures };
438 }
439​
440 return { archivedThreadKeys, mutationFailure: null, followupFailures };
442​
443export function buildMultiSelectThreadContextMenuItems(input: {
444 count: number;
445 hasRunningThread: boolean;
446}): readonly ContextMenuItem<"mark-unread" | "archive" | "delete">[] {
447 return [
448 { id: "mark-unread", label: `Mark unread (${input.count})` },
449 {
450 id: "archive",
451 label: `Archive (${input.count})`,
452 disabled: input.hasRunningThread,
453 },
454 { id: "delete", label: `Delete (${input.count})`, destructive: true },
455 ];
457​
458export function buildBulkTitleRegenerationContextMenuItem(input: {
459 supportedCount: number;
460 actionableCount: number;
461}): ContextMenuItem<"regenerate-title"> | null {
462 if (input.supportedCount === 0) return null;
463 if (input.actionableCount === 0) {
464 return {
465 id: "regenerate-title",
466 label: `Regenerating… (${input.supportedCount})`,
467 disabled: true,
468 };
469 }
470 return {
471 id: "regenerate-title",
472 label: `Regenerate titles (${input.actionableCount})`,
473 };
475​
476/**
477 * Bulk unpin follows the same "count only what the action will touch" rule
478 * as title regeneration: on a mixed selection the label counts the pinned
479 * rows alone, and the item disappears when nothing selected is pinned.
480 */
481export function buildBulkUnpinContextMenuItem(input: {
482 pinnedCount: number;
483}): ContextMenuItem<"unpin"> | null {
484 if (input.pinnedCount === 0) return null;
485 return { id: "unpin", label: `Unpin (${input.pinnedCount})` };
487​
488export interface ThreadStatusPill {
489 label:
490 | "Working"
491 | "Monitoring"
492 | "Connecting"
493 | "Completed"
494 | "Pending Approval"
495 | "Awaiting Input"
496 | "Plan Ready";
497 colorClass: string;
498 dotClass: string;
499 pulse: boolean;
501​
502// Rollup order mirrors the per-thread resolver exactly: attention states,
503// then active work, then the actionable plan prompt, then passive
504// monitoring. A Monitoring sibling must never hide a Plan Ready thread.
505const THREAD_STATUS_PRIORITY: Record<ThreadStatusPill["label"], number> = {
506 "Pending Approval": 6,
507 "Awaiting Input": 5,
508 Working: 4,
509 Connecting: 4,
510 "Plan Ready": 3,
511 Monitoring: 2,
512 Completed: 1,
513};
514​
515type ThreadStatusInput = Pick<
516 SidebarThreadSummary,
517 | "hasActionableProposedPlan"
518 | "hasPendingApprovals"
519 | "hasPendingUserInput"
520 | "interactionMode"
521 | "latestTurn"
522 | "session"
523 | "backgroundLiveness"
524> & {
525 lastVisitedAt?: string | undefined;
526};
527​
528export interface ThreadJumpHintVisibilityController {
529 sync: (shouldShow: boolean) => void;
530 dispose: () => void;
532​
533export function createThreadJumpHintVisibilityController(input: {
534 delayMs: number;
535 onVisibilityChange: (visible: boolean) => void;
536 setTimeoutFn?: typeof globalThis.setTimeout;
537 clearTimeoutFn?: typeof globalThis.clearTimeout;
538}): ThreadJumpHintVisibilityController {
539 const setTimeoutFn = input.setTimeoutFn ?? globalThis.setTimeout;
540 const clearTimeoutFn = input.clearTimeoutFn ?? globalThis.clearTimeout;
541 let isVisible = false;
542 let timeoutId: NodeJS.Timeout | null = null;
543​
544 const clearPendingShow = () => {
545 if (timeoutId === null) {
546 return;
547 }
548 clearTimeoutFn(timeoutId);
549 timeoutId = null;
550 };
551​
552 return {
553 sync: (shouldShow) => {
554 if (!shouldShow) {
555 clearPendingShow();
556 if (isVisible) {
557 isVisible = false;
558 input.onVisibilityChange(false);
559 }
560 return;
561 }
562​
563 if (isVisible || timeoutId !== null) {
564 return;
565 }
566​
567 timeoutId = setTimeoutFn(() => {
568 timeoutId = null;
569 isVisible = true;
570 input.onVisibilityChange(true);
571 }, input.delayMs);
572 },
573 dispose: () => {
574 clearPendingShow();
575 },
576 };
578​
579export function useThreadJumpHintVisibility(): {
580 showThreadJumpHints: boolean;
581 updateThreadJumpHintsVisibility: (shouldShow: boolean) => void;
582} {
583 const [showThreadJumpHints, setShowThreadJumpHints] = React.useState(false);
584 const controllerRef = React.useRef<ThreadJumpHintVisibilityController | null>(null);
585​
586 React.useEffect(() => {
587 const controller = createThreadJumpHintVisibilityController({
588 delayMs: THREAD_JUMP_HINT_SHOW_DELAY_MS,
589 onVisibilityChange: (visible) => {
590 setShowThreadJumpHints(visible);
591 },
592 setTimeoutFn: window.setTimeout.bind(window),
593 clearTimeoutFn: window.clearTimeout.bind(window),
594 });
595 controllerRef.current = controller;
596​
597 return () => {
598 controller.dispose();
599 controllerRef.current = null;
600 };
601 }, []);
602​
603 const updateThreadJumpHintsVisibility = React.useCallback((shouldShow: boolean) => {
604 controllerRef.current?.sync(shouldShow);
605 }, []);
606​
607 return {
608 showThreadJumpHints,
609 updateThreadJumpHintsVisibility,
610 };
612​
613export function hasUnseenCompletion(thread: ThreadStatusInput): boolean {
614 if (!thread.latestTurn?.completedAt) return false;
615 const completedAt = Date.parse(thread.latestTurn.completedAt);
616 if (Number.isNaN(completedAt)) return false;
617 if (!thread.lastVisitedAt) return false;
618​
619 const lastVisitedAt = Date.parse(thread.lastVisitedAt);
620 if (Number.isNaN(lastVisitedAt)) return true;
621 return completedAt > lastVisitedAt;
623​
624export function shouldClearThreadSelectionOnMouseDown(target: HTMLElement | null): boolean {
625 if (target === null) return true;
626 return !target.closest(THREAD_SELECTION_SAFE_SELECTOR);
628​
629// A double-click dispatches two `click` events before `dblclick`: the first has
630// `detail === 1`, the second `detail === 2`. The second click must not run the
631// row's single-click navigation, otherwise double-click-to-rename would also
632// navigate. `MouseEvent.detail` is 0 for synthetic/keyboard activations, which
633// still count as a normal single activation.
634export function isTrailingDoubleClick(detail: number): boolean {
635 return detail > 1;
637​
638function nodeClosest(node: object | null, selector: string): unknown {
639 if (node === null || !("closest" in node) || typeof node.closest !== "function") return null;
640 return node.closest(selector);
642​
643/** Clicks on a nested link keep the link's meaning. The row must not treat them as multi-select. */
644export function isSidebarNestedLinkClick(target: EventTarget | null): boolean {
645 if (target == null || typeof target !== "object") return false;
646 if (nodeClosest(target, "a[href]") !== null) return true;
647 const parent =
648 "parentElement" in target &&
649 target.parentElement !== null &&
650 typeof target.parentElement === "object"
651 ? target.parentElement
652 : null;
653 return nodeClosest(parent, "a[href]") !== null;
655​
656// Shift+click on the new thread button creates directly in the current
657// project, skipping the command palette's project picker. With a single
658// project there is nothing to pick, so a plain click already creates
659// immediately and the modifier changes nothing.
660export function shouldCreateNewThreadInCurrentProject(
661 shiftKey: boolean,
662 projectGroupCount: number,
663): boolean {
664 return shiftKey || projectGroupCount <= 1;
666​
667export function orderItemsByPreferredIds<TItem, TId>(input: {
668 items: readonly TItem[];
669 preferredIds: readonly TId[];
670 getId: (item: TItem) => TId;
671 getPreferenceIds?: (item: TItem) => readonly TId[];
672}): TItem[] {
673 const { getId, getPreferenceIds, items, preferredIds } = input;
674 if (preferredIds.length === 0) {
675 return [...items];
676 }
677​
678 const indexesByPreferenceId = new Map<TId, number[]>();
679 for (const [index, item] of items.entries()) {
680 const preferenceIds = getPreferenceIds?.(item) ?? [getId(item)];
681 for (const preferenceId of new Set(preferenceIds)) {
682 const indexes = indexesByPreferenceId.get(preferenceId);
683 if (indexes) {
684 indexes.push(index);
685 } else {
686 indexesByPreferenceId.set(preferenceId, [index]);
687 }
688 }
689 }
690​
691 const emittedIndexes = new Set<number>();
692 const ordered = preferredIds.flatMap((id) => {
693 const index = indexesByPreferenceId
694 .get(id)
695 ?.find((candidate) => !emittedIndexes.has(candidate));
696 if (index === undefined) {
697 return [];
698 }
699 emittedIndexes.add(index);
700 return [items[index]!];
701 });
702 const remaining = items.filter((_, index) => !emittedIndexes.has(index));
703 return [...ordered, ...remaining];
705​
706export function getSidebarThreadIdsToPrewarm<TThreadId>(
707 visibleThreadIds: readonly TThreadId[],
708 limit = SIDEBAR_THREAD_PREWARM_LIMIT,
709): TThreadId[] {
710 return visibleThreadIds.slice(0, Math.max(0, limit));
712​
713export function resolveAdjacentThreadId<T>(input: {
714 threadIds: readonly T[];
715 currentThreadId: T | null;
716 direction: ThreadTraversalDirection;
717}): T | null {
718 const { currentThreadId, direction, threadIds } = input;
719​
720 if (threadIds.length === 0) {
721 return null;
722 }
723​
724 if (currentThreadId === null) {
725 return direction === "previous" ? (threadIds.at(-1) ?? null) : (threadIds[0] ?? null);
726 }
727​
728 const currentIndex = threadIds.indexOf(currentThreadId);
729 if (currentIndex === -1) {
730 return null;
731 }
732​
733 if (direction === "previous") {
734 return currentIndex > 0 ? (threadIds[currentIndex - 1] ?? null) : null;
735 }
736​
737 return currentIndex < threadIds.length - 1 ? (threadIds[currentIndex + 1] ?? null) : null;
739​
740export function isContextMenuPointerDown(input: {
741 button: number;
742 ctrlKey: boolean;
743 isMac: boolean;
744}): boolean {
745 if (input.button === 2) return true;
746 return input.isMac && input.button === 0 && input.ctrlKey;
748​
749export function resolveThreadRowClassName(input: {
750 isActive: boolean;
751 isSelected: boolean;
752}): string {
753 const baseClassName =
754 "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";
755​
756 if (input.isSelected && input.isActive) {
757 return cn(
758 baseClassName,
759 "bg-sidebar-row-active text-sidebar-foreground font-medium hover:bg-sidebar-row-active hover:text-sidebar-foreground",
760 );
761 }
762​
763 if (input.isSelected) {
764 return cn(
765 baseClassName,
766 "bg-sidebar-row-selected text-sidebar-foreground hover:bg-sidebar-row-active hover:text-sidebar-foreground",
767 );
768 }
769​
770 if (input.isActive) {
771 return cn(
772 baseClassName,
773 "bg-sidebar-row-active text-sidebar-foreground font-medium hover:bg-sidebar-row-active hover:text-sidebar-foreground",
774 );
775 }
776​
777 return cn(
778 baseClassName,
779 "text-sidebar-muted-foreground/80 hover:bg-sidebar-row-hover hover:text-sidebar-foreground",
780 );
782​
783// ── Sidebar thread status model ─────────────────────────────────────
784// Five visual states, three colors: color is reserved for "act now"
785// (approval), "in motion" (working), and "broken" (failed). Ready is the
786// unlabeled resting state — the agent stopped and is waiting on the user,
787// whether it finished, asked a question, or proposed a plan.
788// Unread completion is tracked separately: it describes whether a ready
789// thread needs attention, not what the thread is currently doing.
790export type SidebarThreadStatus =
791 | "approval"
792 | "input"
793 | "working"
794 | "monitoring"
795 | "failed"
796 | "ready";
797​
798export function shouldRecedeSidebarThread(input: {
799 status: SidebarThreadStatus;
800 isUnread: boolean;
801 isWoke: boolean;
802 isActive: boolean;
803 isSelected: boolean;
804}): boolean {
805 if (input.isActive || input.isSelected) return false;
806 if (input.status === "working" || input.status === "monitoring") return true;
807 if (input.status === "ready" || input.status === "approval" || input.status === "input") {
808 return !input.isUnread && !input.isWoke;
809 }
810 return false;
812​
813type SidebarThreadStatusInput = Pick<
814 SidebarThreadSummary,
815 "hasPendingApprovals" | "hasPendingUserInput" | "session" | "backgroundLiveness"
816>;
817​
818export function resolveSidebarThreadStatus(thread: SidebarThreadStatusInput): SidebarThreadStatus {
819 if (thread.hasPendingApprovals) {
820 return "approval";
821 }
822 if (thread.hasPendingUserInput) {
823 return "input";
824 }
825 if (thread.session?.status === "running" || thread.session?.status === "starting") {
826 return "working";
827 }
828 // A failed session outranks lingering background liveness: the user must
829 // see the failure, not a stale Working (review finding).
830 if (thread.session?.status === "error") {
831 return "failed";
832 }
833 // Background work outlives the turn: fleets read as working; monitoring
834 // only when watch loops are the sole live work.
835 if (thread.backgroundLiveness === "working") {
836 return "working";
837 }
838 if (thread.backgroundLiveness === "monitoring") {
839 return "monitoring";
840 }
841 return "ready";
843​
844/** First VALID timestamp wins: `a ?? b` falls through on null, but a present-
845 yet-malformed string must also fall through to the next candidate rather
846 than sink the row to the epoch. */
847export function firstValidTimestampMs(
848 ...candidates: ReadonlyArray<string | null | undefined>
849): number {
850 for (const candidate of candidates) {
851 if (candidate == null) continue;
852 const parsed = Date.parse(candidate);
853 if (!Number.isNaN(parsed)) return parsed;
854 }
855 return 0;
857​
858/** String twin of firstValidTimestampMs for callers that need the ISO string
859 (display labels, tick anchors) rather than epoch ms. */
860function firstValidTimestamp(
861 ...candidates: ReadonlyArray<string | null | undefined>
862): string | null {
863 for (const candidate of candidates) {
864 if (candidate == null) continue;
865 if (!Number.isNaN(Date.parse(candidate))) return candidate;
866 }
867 return null;
869​
870export { sortActiveThreadsByOrderKey as sortThreadsForSidebar } from "@t3tools/client-runtime/state/thread-sort";
871​
872// Pinned-reorder key math and the keyed sort live in client-runtime
873// (state/thread-sort) so web and mobile compute identical pinned orders.
874export { pinOrderKeyBetween, planPinnedReorder } from "@t3tools/client-runtime/state/thread-sort";
875export { sortPinnedThreadsByOrderKey as sortPinnedThreadsForSidebar } from "@t3tools/client-runtime/state/thread-sort";
876​
877/**
878 * Search the already-ordered sidebar thread collection by title only.
879 * Keeping the input order means lifecycle ordering (active, snoozed, settled)
880 * remains stable while the user narrows the list.
881 */
882export function searchSidebarThreadsByTitle<T extends { readonly title: string }>(
883 threads: readonly T[],
884 query: string,
885): T[] {
886 const normalizedQuery = query.trim().toLowerCase();
887 if (normalizedQuery.length === 0) return [];
888 return threads.filter((thread) => thread.title.toLowerCase().includes(normalizedQuery));
890​
891export function filterSidebarProjectScopeItems<TItem extends { readonly value: string }>(input: {
892 items: readonly TItem[];
893 activeScopeKey: string | null;
894 query: string;
895 matches: (item: TItem, query: string) => boolean;
896}): readonly TItem[] {
897 const projectItems = input.items.filter((item) => item.value !== "all");
898 const query = input.query.trim();
899 if (query.length > 0) {
900 return projectItems.filter((item) => input.matches(item, query));
901 }
902 return input.activeScopeKey === null ? projectItems : input.items;
904​
905export interface SidebarProjectScopeMenuState {
906 readonly open: boolean;
907 readonly query: string;
909​
910export type SidebarProjectScopeMenuAction =
911 | { readonly type: "query-changed"; readonly query: string }
912 | { readonly type: "open-changed"; readonly open: boolean }
913 | { readonly type: "project-settings-opened" };
914​
915export function reduceSidebarProjectScopeMenuState(
916 state: SidebarProjectScopeMenuState,
917 action: SidebarProjectScopeMenuAction,
918): SidebarProjectScopeMenuState {
919 switch (action.type) {
920 case "query-changed":
921 return { ...state, query: action.query };
922 case "open-changed":
923 return { open: action.open, query: "" };
924 case "project-settings-opened":
925 return { open: false, query: "" };
926 }
928​
929// Settled rows are history, so they order by when the work ENDED, not when
930// the thread was created or last touched.
931export function sortSettledThreadsForSidebar<
932 T extends SettledThreadTimestampInput & { readonly id: string },
933>(threads: readonly T[]): T[] {
934 const timestampMs = (thread: T) => {
935 const timestamp = resolveSettledThreadTimestamp(thread);
936 return timestamp === null ? 0 : Date.parse(timestamp);
937 };
938 return [...threads].toSorted(
939 (left, right) => timestampMs(right) - timestampMs(left) || left.id.localeCompare(right.id),
940 );
942​
943/** The timestamp a working thread's elapsed label counts from: the running
944 turn's start (request time until adoption), falling back to the session's
945 last transition when the turn projection lags behind. Malformed
946 timestamps fall through to the next candidate, not just missing ones. */
947export function resolveWorkingStartedAt(
948 thread: Pick<SidebarThreadSummary, "latestTurn" | "session">,
949): string | null {
950 const turn = thread.latestTurn;
951 if (turn && turn.completedAt === null) {
952 return firstValidTimestamp(turn.startedAt, turn.requestedAt, thread.session?.updatedAt);
953 }
954 return firstValidTimestamp(thread.session?.updatedAt);
956​
957export function formatWorkingDurationLabel(elapsedMs: number): string {
958 const seconds = Number.isFinite(elapsedMs) ? Math.max(0, Math.floor(elapsedMs / 1000)) : 0;
959 if (seconds < 60) return `${seconds}s`;
960 const minutes = Math.floor(seconds / 60);
961 if (minutes < 60) return `${minutes}m`;
962 return `${Math.floor(minutes / 60)}h ${minutes % 60}m`;
964​
965export function resolveThreadStatusPill(input: {
966 thread: ThreadStatusInput;
967}): ThreadStatusPill | null {
968 const { thread } = input;
969​
970 if (thread.hasPendingApprovals) {
971 return {
972 label: "Pending Approval",
973 colorClass: "text-amber-600 dark:text-amber-300/90",
974 dotClass: "bg-amber-500 dark:bg-amber-300/90",
975 pulse: false,
976 };
977 }
978​
979 if (thread.hasPendingUserInput) {
980 return {
981 label: "Awaiting Input",
982 colorClass: "text-indigo-600 dark:text-indigo-300/90",
983 dotClass: "bg-indigo-500 dark:bg-indigo-300/90",
984 pulse: false,
985 };
986 }
987​
988 if (thread.session?.status === "running") {
989 return {
990 label: "Working",
991 colorClass: "text-sky-600 dark:text-sky-300/80",
992 dotClass: "bg-sky-500 dark:bg-sky-300/80",
993 pulse: true,
994 };
995 }
996​
997 if (thread.session?.status === "starting") {
998 return {
999 label: "Connecting",
1000 colorClass: "text-sky-600 dark:text-sky-300/80",
1001 dotClass: "bg-sky-500 dark:bg-sky-300/80",
1002 pulse: true,
1003 };
1005​
1006 // An actionable plan prompt outranks lingering background work: it needs
1007 // the user's decision, while liveness merely reports (review finding).
1008 const hasPlanReadyPrompt =
1009 !thread.hasPendingUserInput &&
1010 thread.interactionMode === "plan" &&
1011 isLatestTurnSettled(thread.latestTurn, thread.session) &&
1012 thread.hasActionableProposedPlan;
1013 if (hasPlanReadyPrompt) {
1014 return {
1015 label: "Plan Ready",
1016 colorClass: "text-violet-600 dark:text-violet-300/90",
1017 dotClass: "bg-violet-500 dark:bg-violet-300/90",
1018 pulse: false,
1019 };
1021​
1022 // The turn can settle while native background work runs on. Subagent and
1023 // workflow fleets read as plain Working; Monitoring is reserved for watch
1024 // loops (a parent agent babysitting a PR, tailing checks) with no other
1025 // live work. Same recede treatment as Working per inbox-zero.
1026 if (thread.backgroundLiveness === "working") {
1027 return {
1028 label: "Working",
1029 colorClass: "text-sky-600 dark:text-sky-300/80",
1030 dotClass: "bg-sky-500 dark:bg-sky-300/80",
1031 pulse: true,
1032 };
1034​
1035 if (thread.backgroundLiveness === "monitoring") {
1036 return {
1037 label: "Monitoring",
1038 colorClass: "text-sky-600 dark:text-sky-300/80",
1039 dotClass: "bg-sky-500 dark:bg-sky-300/80",
1040 pulse: false,
1041 };
1043​
1044 if (hasUnseenCompletion(thread)) {
1045 return {
1046 label: "Completed",
1047 colorClass: "text-emerald-600 dark:text-emerald-300/90",
1048 dotClass: "bg-emerald-500 dark:bg-emerald-300/90",
1049 pulse: false,
1050 };
1052​
1053 return null;
1055​
1056export function resolveProjectStatusIndicator(
1057 statuses: ReadonlyArray<ThreadStatusPill | null>,
1058): ThreadStatusPill | null {
1059 let highestPriorityStatus: ThreadStatusPill | null = null;
1060​
1061 for (const status of statuses) {
1062 if (status === null) continue;
1063 if (
1064 highestPriorityStatus === null ||
1065 THREAD_STATUS_PRIORITY[status.label] > THREAD_STATUS_PRIORITY[highestPriorityStatus.label]
1066 ) {
1067 highestPriorityStatus = status;
1070​
1071 return highestPriorityStatus;
1073​
1074export function getFallbackThreadIdAfterDelete<
1075 T extends Pick<Thread, "id" | "projectId" | "createdAt" | "updatedAt"> & ThreadSortInput,
1076>(input: {
1077 threads: readonly T[];
1078 deletedThreadId: T["id"];
1079 sortOrder: SidebarThreadSortOrder;
1080 deletedThreadIds?: ReadonlySet<T["id"]>;
1081}): T["id"] | null {
1082 const { deletedThreadId, deletedThreadIds, sortOrder, threads } = input;
1083 const deletedThread = threads.find((thread) => thread.id === deletedThreadId);
1084 if (!deletedThread) {
1085 return null;
1087​
1088 return (
1089 sortThreads(
1090 threads.filter(
1091 (thread) =>
1092 thread.projectId === deletedThread.projectId &&
1093 thread.id !== deletedThreadId &&
1094 !deletedThreadIds?.has(thread.id),
1095 ),
1096 sortOrder,
1097 )[0]?.id ?? null
1098 );
1100export function getProjectSortTimestamp(
1101 project: SidebarProject,
1102 projectThreads: readonly ThreadSortInput[],
1103 sortOrder: Exclude<SidebarProjectSortOrder, "manual">,
1104): number {
1105 if (projectThreads.length > 0) {
1106 return projectThreads.reduce(
1107 (latest, thread) => Math.max(latest, getThreadSortTimestamp(thread, sortOrder)),
1108 Number.NEGATIVE_INFINITY,
1109 );
1111​
1112 if (sortOrder === "created_at") {
1113 return toSortableTimestamp(project.createdAt) ?? Number.NEGATIVE_INFINITY;
1115 return toSortableTimestamp(project.updatedAt ?? project.createdAt) ?? Number.NEGATIVE_INFINITY;
1117​
1118function sortProjectsByActivity<TProject extends SidebarProject>(
1119 projects: readonly TProject[],
1120 sortOrder: SidebarProjectSortOrder,
1121 getProjectThreads: (project: TProject) => readonly ThreadSortInput[],
1122 compareTies: (left: TProject, right: TProject) => number,
1123): TProject[] {
1124 if (sortOrder === "manual") {
1125 return [...projects];
1127​
1128 return [...projects].toSorted((left, right) => {
1129 const rightTimestamp = getProjectSortTimestamp(right, getProjectThreads(right), sortOrder);
1130 const leftTimestamp = getProjectSortTimestamp(left, getProjectThreads(left), sortOrder);
1131 const byTimestamp =
1132 rightTimestamp === leftTimestamp ? 0 : rightTimestamp > leftTimestamp ? 1 : -1;
1133 return byTimestamp || compareTies(left, right);
1134 });
1136​
1137export function sortProjectsForSidebar<
1138 TProject extends SidebarProject,
1139 TThread extends Pick<Thread, "projectId" | "createdAt" | "updatedAt"> & ThreadSortInput,
1141 projects: readonly TProject[],
1142 threads: readonly TThread[],
1143 sortOrder: SidebarProjectSortOrder,
1144): TProject[] {
1145 const threadsByProjectId = new Map<string, TThread[]>();
1146 for (const thread of threads) {
1147 const existing = threadsByProjectId.get(thread.projectId) ?? [];
1148 existing.push(thread);
1149 threadsByProjectId.set(thread.projectId, existing);
1151​
1152 return sortProjectsByActivity(
1153 projects,
1154 sortOrder,
1155 (project) => threadsByProjectId.get(project.id) ?? [],
1156 (left, right) => left.title.localeCompare(right.title) || left.id.localeCompare(right.id),
1157 );
1159​
1160export function sortLogicalProjectsForSidebar<
1161 TProject extends LogicalSidebarProject,
1162 TThread extends ScopedSidebarThread,
1164 projects: readonly TProject[],
1165 threads: readonly TThread[],
1166 sortOrder: SidebarProjectSortOrder,
1167): TProject[] {
1168 const groupKeyByProjectRef = new Map(
1169 projects.flatMap((project) =>
1170 project.memberProjectRefs.map(
1171 (projectRef) =>
1172 [`${projectRef.environmentId}\0${projectRef.projectId}`, project.projectKey] as const,
1173 ),
1174 ),
1175 );
1176 const threadsByProjectKey = new Map<string, TThread[]>();
1177 for (const thread of threads) {
1178 if (thread.archivedAt !== null) continue;
1179 const projectKey = groupKeyByProjectRef.get(`${thread.environmentId}\0${thread.projectId}`);
1180 if (!projectKey) continue;
1181 const existing = threadsByProjectKey.get(projectKey);
1182 if (existing) {
1183 existing.push(thread);
1184 } else {
1185 threadsByProjectKey.set(projectKey, [thread]);
1188​
1189 return sortProjectsByActivity(
1190 projects,
1191 sortOrder,
1192 (project) => threadsByProjectKey.get(project.projectKey) ?? [],
1193 (left, right) =>
1194 left.title.localeCompare(right.title) || left.projectKey.localeCompare(right.projectKey),
1195 );
1197​
1198/**
1199 * Sorts the cross-environment project collection used by landing surfaces.
1200 * Project ids are only unique within an environment, and archived threads
1201 * must not make a project appear recently active.
1202 */
1203export function sortScopedProjectsForSidebar<
1204 TProject extends ScopedSidebarProject,
1205 TThread extends ScopedSidebarThread,
1207 projects: readonly TProject[],
1208 threads: readonly TThread[],
1209 sortOrder: SidebarProjectSortOrder,
1210): TProject[] {
1211 const scopedKey = (environmentId: string, projectId: string) =>
1212 `${environmentId}\u0000${projectId}`;
1213 const threadsByProject = new Map<string, TThread[]>();
1214 for (const thread of threads) {
1215 if (thread.archivedAt !== null) {
1216 continue;
1218 const key = scopedKey(thread.environmentId, thread.projectId);
1219 const existing = threadsByProject.get(key) ?? [];
1220 existing.push(thread);
1221 threadsByProject.set(key, existing);
1223​
1224 return sortProjectsByActivity(
1225 projects,
1226 sortOrder,
1227 (project) => threadsByProject.get(scopedKey(project.environmentId, project.id)) ?? [],
1228 (left, right) =>
1229 left.title.localeCompare(right.title) ||
1230 left.environmentId.localeCompare(right.environmentId) ||
1231 left.id.localeCompare(right.id),
1232 );