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

Sidebar.logic.ts

1,163 lines37.2 KB

1import * as React from "react";
2import { defaultAnimateLayoutChanges, type AnimateLayoutChanges } from "@dnd-kit/sortable";
3import type { ContextMenuItem } from "@t3tools/contracts";
4import type { SidebarProjectSortOrder, SidebarThreadSortOrder } from "@t3tools/contracts/settings";
5import {
6 activeThreadAnchorTimestampMs,
7 getThreadSortTimestamp,
8 resolveSettledThreadTimestamp,
9 sortThreads,
10 toSortableTimestamp,
11 type SettledThreadTimestampInput,
12 type ThreadSortInput,
13} from "../lib/threadSort";
14import type { SidebarThreadSummary, Thread } from "../types";
15import type { ThreadRouteTarget } from "../threadRoutes";
16import { cn } from "../lib/utils";
17import { isLatestRunSettled } from "../session-logic";
18import { resolveServerBackedAppStageLabel } from "../branding.logic";
19​
20export const THREAD_SELECTION_SAFE_SELECTOR = "[data-thread-item], [data-thread-selection-safe]";
21export const THREAD_JUMP_HINT_SHOW_DELAY_MS = 200;
22// Visible sidebar rows are prewarmed into the thread-detail cache so opening a
23// nearby thread usually reuses an already-hot subscription. Each prewarmed
24// thread holds a live, fully hydrated detail subscription (all messages and
25// activities, growing as agents work) for as long as the row stays visible,
26// so this limit is a direct renderer-heap and server-load multiplier — keep
27// it small; cold opens still render instantly from the cached snapshot.
28export const SIDEBAR_THREAD_PREWARM_LIMIT = 3;
29// A small buffer keeps the next few rows warm without leasing every row that
30// content-visibility leaves mounted below the scroll viewport.
31export const SIDEBAR_ROW_SUBSCRIPTION_OVERSCAN_PX = 160;
32​
33export function useSidebarRowSubscriptionLease(isActive: boolean): {
34 readonly leaseLiveStatus: boolean;
35 readonly rowRef: React.Dispatch<React.SetStateAction<HTMLElement | null>>;
36} {
37 const [row, setRow] = React.useState<HTMLElement | null>(null);
38 const [isNearViewport, setIsNearViewport] = React.useState(isActive);
39​
40 React.useEffect(() => {
41 if (isActive) {
42 setIsNearViewport(true);
43 return;
44 }
45 if (row === null) return;
46 if (typeof IntersectionObserver === "undefined") {
47 setIsNearViewport(true);
48 return;
49 }
50​
51 const scrollRoot = row.closest<HTMLElement>('[data-slot="scroll-area-viewport"]');
52 const observer = new IntersectionObserver(
53 ([entry]) => setIsNearViewport(entry?.isIntersecting === true),
54 {
55 root: scrollRoot,
56 rootMargin: `${SIDEBAR_ROW_SUBSCRIPTION_OVERSCAN_PX}px 0px`,
57 },
58 );
59 observer.observe(row);
60 return () => observer.disconnect();
61 }, [isActive, row]);
62​
63 return {
64 leaseLiveStatus: isActive || isNearViewport,
65 rowRef: setRow,
66 };
68​
69// A row keeps the last live value it rendered so a released lease never
70// blanks its badge. The value is bound to `key`, so a different worktree or
71// linked pull request cannot reuse the previous one.
72export function useRetainedValue<T>(key: string | null, value: T | null): T | null {
73 const retained = React.useRef<{ readonly key: string; readonly value: T } | null>(null);
74 if (key !== null && value !== null) {
75 retained.current = { key, value };
76 }
77 if (value !== null) return value;
78 return key !== null && retained.current?.key === key ? retained.current.value : null;
80​
81// The list already reaches its destination through sortable transforms while
82// the pointer is down. dnd-kit's default also animates the committed DOM order
83// after release, replaying the same movement across every affected row.
84export const animatePinnedLayoutChanges: AnimateLayoutChanges = (args) =>
85 args.isSorting ? defaultAnimateLayoutChanges(args) : false;
86​
87type SidebarProject = {
88 id: string;
89 title: string;
90 createdAt?: string | undefined;
91 updatedAt?: string | undefined;
92};
93​
94type ScopedSidebarProject = SidebarProject & {
95 environmentId: string;
96};
97​
98type ScopedSidebarThread = ThreadSortInput & {
99 environmentId: string;
100 projectId: string;
101 archivedAt: string | null;
102};
103​
104type LogicalSidebarProject = SidebarProject & {
105 projectKey: string;
106 memberProjectRefs: readonly {
107 environmentId: string;
108 projectId: string;
109 }[];
110};
111​
112export type ThreadTraversalDirection = "previous" | "next";
113​
114export async function archiveSelectedThreadEntries<
115 TEntry extends { readonly threadKey: string },
116 TResult extends { readonly _tag: "Success" | "Failure" },
117>(input: {
118 entries: readonly TEntry[];
119 archive: (entry: TEntry, onArchived: () => void) => Promise<TResult>;
120}): Promise<{
121 archivedThreadKeys: readonly string[];
122 mutationFailure: Extract<TResult, { readonly _tag: "Failure" }> | null;
123 followupFailures: readonly Extract<TResult, { readonly _tag: "Failure" }>[];
124}> {
125 const archivedThreadKeys: string[] = [];
126 const followupFailures: Extract<TResult, { readonly _tag: "Failure" }>[] = [];
127​
128 for (const entry of input.entries) {
129 let didArchive = false;
130 const result = await input.archive(entry, () => {
131 didArchive = true;
132 });
133 if (didArchive || result._tag === "Success") archivedThreadKeys.push(entry.threadKey);
134 if (result._tag === "Success") continue;
135 const failure = result as Extract<TResult, { readonly _tag: "Failure" }>;
136 if (didArchive) {
137 followupFailures.push(failure);
138 continue;
139 }
140 return { archivedThreadKeys, mutationFailure: failure, followupFailures };
141 }
142​
143 return { archivedThreadKeys, mutationFailure: null, followupFailures };
145​
146export function buildMultiSelectThreadContextMenuItems(input: {
147 count: number;
148 hasRunningThread: boolean;
149}): readonly ContextMenuItem<"mark-unread" | "archive" | "delete">[] {
150 return [
151 { id: "mark-unread", label: `Mark unread (${input.count})` },
152 {
153 id: "archive",
154 label: `Archive (${input.count})`,
155 disabled: input.hasRunningThread,
156 },
157 { id: "delete", label: `Delete (${input.count})`, destructive: true },
158 ];
160​
161export function isSidebarSubagentThread(thread: Pick<SidebarThreadSummary, "lineage">): boolean {
162 return thread.lineage.relationshipToParent === "subagent";
164​
165export function filterSidebarV2VisibleThreads<
166 T extends Pick<SidebarThreadSummary, "archivedAt" | "lineage"> & {
167 environmentId: string;
168 projectId: string;
169 },
170>(threads: readonly T[], scopedProjectKeys: ReadonlySet<string> | null): T[] {
171 return threads.filter(
172 (thread) =>
173 thread.archivedAt === null &&
174 !isSidebarSubagentThread(thread) &&
175 (scopedProjectKeys === null ||
176 scopedProjectKeys.has(`${thread.environmentId}:${thread.projectId}`)),
177 );
179​
180export function getSidebarForkParentThreadId(
181 thread: Pick<SidebarThreadSummary, "forkedFrom" | "lineage">,
182) {
183 if (thread.lineage.relationshipToParent !== "fork") {
184 return null;
185 }
186 return thread.forkedFrom?.type === "run"
187 ? thread.forkedFrom.threadId
188 : thread.lineage.parentThreadId;
190​
191export function buildBulkTitleRegenerationContextMenuItem(input: {
192 supportedCount: number;
193 actionableCount: number;
194}): ContextMenuItem<"regenerate-title"> | null {
195 if (input.supportedCount === 0) return null;
196 if (input.actionableCount === 0) {
197 return {
198 id: "regenerate-title",
199 label: `Regenerating… (${input.supportedCount})`,
200 disabled: true,
201 };
202 }
203 return {
204 id: "regenerate-title",
205 label: `Regenerate titles (${input.actionableCount})`,
206 };
208​
209/**
210 * Bulk unpin follows the same "count only what the action will touch" rule
211 * as title regeneration: on a mixed selection the label counts the pinned
212 * rows alone, and the item disappears when nothing selected is pinned.
213 */
214export function buildBulkUnpinContextMenuItem(input: {
215 pinnedCount: number;
216}): ContextMenuItem<"unpin"> | null {
217 if (input.pinnedCount === 0) return null;
218 return { id: "unpin", label: `Unpin (${input.pinnedCount})` };
220​
221export interface ThreadStatusPill {
222 label:
223 | "Working"
224 | "Connecting"
225 | "Completed"
226 | "Pending Approval"
227 | "Awaiting Input"
228 | "Waiting"
229 | "Plan Ready";
230 colorClass: string;
231 dotClass: string;
232 pulse: boolean;
234​
235const THREAD_STATUS_PRIORITY: Record<ThreadStatusPill["label"], number> = {
236 "Pending Approval": 5,
237 "Awaiting Input": 4,
238 Working: 3,
239 Connecting: 3,
240 Waiting: 2.5,
241 "Plan Ready": 2,
242 Completed: 1,
243};
244​
245type ThreadStatusInput = Pick<
246 SidebarThreadSummary,
247 | "hasActionableProposedPlan"
248 | "hasPendingApprovals"
249 | "hasPendingUserInput"
250 | "interactionMode"
251 | "latestRun"
252 | "runtime"
253> & {
254 lastVisitedAt?: string | null | undefined;
255 pendingBackgroundTasks?: SidebarThreadSummary["pendingBackgroundTasks"] | undefined;
256};
257​
258export interface ThreadJumpHintVisibilityController {
259 sync: (shouldShow: boolean) => void;
260 dispose: () => void;
262​
263export function resolveSidebarStageBadgeLabel(input: {
264 primaryServerVersion: string | null | undefined;
265 fallbackStageLabel: string;
266}): string {
267 return resolveServerBackedAppStageLabel(input);
269​
270export function createThreadJumpHintVisibilityController(input: {
271 delayMs: number;
272 onVisibilityChange: (visible: boolean) => void;
273 setTimeoutFn?: typeof globalThis.setTimeout;
274 clearTimeoutFn?: typeof globalThis.clearTimeout;
275}): ThreadJumpHintVisibilityController {
276 const setTimeoutFn = input.setTimeoutFn ?? globalThis.setTimeout;
277 const clearTimeoutFn = input.clearTimeoutFn ?? globalThis.clearTimeout;
278 let isVisible = false;
279 let timeoutId: NodeJS.Timeout | null = null;
280​
281 const clearPendingShow = () => {
282 if (timeoutId === null) {
283 return;
284 }
285 clearTimeoutFn(timeoutId);
286 timeoutId = null;
287 };
288​
289 return {
290 sync: (shouldShow) => {
291 if (!shouldShow) {
292 clearPendingShow();
293 if (isVisible) {
294 isVisible = false;
295 input.onVisibilityChange(false);
296 }
297 return;
298 }
299​
300 if (isVisible || timeoutId !== null) {
301 return;
302 }
303​
304 timeoutId = setTimeoutFn(() => {
305 timeoutId = null;
306 isVisible = true;
307 input.onVisibilityChange(true);
308 }, input.delayMs);
309 },
310 dispose: () => {
311 clearPendingShow();
312 },
313 };
315​
316export function useThreadJumpHintVisibility(): {
317 showThreadJumpHints: boolean;
318 updateThreadJumpHintsVisibility: (shouldShow: boolean) => void;
319} {
320 const [showThreadJumpHints, setShowThreadJumpHints] = React.useState(false);
321 const controllerRef = React.useRef<ThreadJumpHintVisibilityController | null>(null);
322​
323 React.useEffect(() => {
324 const controller = createThreadJumpHintVisibilityController({
325 delayMs: THREAD_JUMP_HINT_SHOW_DELAY_MS,
326 onVisibilityChange: (visible) => {
327 setShowThreadJumpHints(visible);
328 },
329 setTimeoutFn: window.setTimeout.bind(window),
330 clearTimeoutFn: window.clearTimeout.bind(window),
331 });
332 controllerRef.current = controller;
333​
334 return () => {
335 controller.dispose();
336 controllerRef.current = null;
337 };
338 }, []);
339​
340 const updateThreadJumpHintsVisibility = React.useCallback((shouldShow: boolean) => {
341 controllerRef.current?.sync(shouldShow);
342 }, []);
343​
344 return {
345 showThreadJumpHints,
346 updateThreadJumpHintsVisibility,
347 };
349​
350/**
351 * Effective visited watermark for a thread. Servers with visited tracking
352 * project `lastVisitedAt` on the shell and are authoritative — that value is
353 * shared across every device connected to the environment. Pre-tracking
354 * servers omit the field, and the browser's locally persisted watermark keeps
355 * working as before.
356 */
357export function resolveThreadLastVisitedAt(
358 serverLastVisitedAt: string | null | undefined,
359 localLastVisitedAt: string | undefined,
360): string | undefined {
361 // When the server tracks visits it is authoritative — including explicit
362 // rewinds from mark-unread, which a newer browser-local watermark must not
363 // mask. The local value only carries servers without visited tracking.
364 if (serverLastVisitedAt === undefined) return localLastVisitedAt;
365 return serverLastVisitedAt ?? undefined;
367​
368export function hasUnseenCompletion(thread: ThreadStatusInput): boolean {
369 if (!thread.latestRun?.completedAt) return false;
370 const completedAt = Date.parse(thread.latestRun.completedAt);
371 if (Number.isNaN(completedAt)) return false;
372 if (!thread.lastVisitedAt) return false;
373​
374 const lastVisitedAt = Date.parse(thread.lastVisitedAt);
375 if (Number.isNaN(lastVisitedAt)) return true;
376 return completedAt > lastVisitedAt;
378​
379export function shouldClearThreadSelectionOnMouseDown(target: HTMLElement | null): boolean {
380 if (target === null) return true;
381 return !target.closest(THREAD_SELECTION_SAFE_SELECTOR);
383​
384// A double-click dispatches two `click` events before `dblclick`: the first has
385// `detail === 1`, the second `detail === 2`. The second click must not run the
386// row's single-click navigation, otherwise double-click-to-rename would also
387// navigate. `MouseEvent.detail` is 0 for synthetic/keyboard activations, which
388// still count as a normal single activation.
389export function isTrailingDoubleClick(detail: number): boolean {
390 return detail > 1;
392​
393function nodeClosest(node: object | null, selector: string): unknown {
394 if (node === null || !("closest" in node) || typeof node.closest !== "function") return null;
395 return node.closest(selector);
397​
398/** Clicks on a nested link keep the link's meaning. The row must not treat them as multi-select. */
399export function isSidebarNestedLinkClick(target: EventTarget | null): boolean {
400 if (target == null || typeof target !== "object") return false;
401 if (nodeClosest(target, "a[href]") !== null) return true;
402 const parent =
403 "parentElement" in target &&
404 target.parentElement !== null &&
405 typeof target.parentElement === "object"
406 ? target.parentElement
407 : null;
408 return nodeClosest(parent, "a[href]") !== null;
410​
411// Shift+click on the new thread button creates directly in the current
412// project, skipping the command palette's project picker. With a single
413// project there is nothing to pick, so a plain click already creates
414// immediately and the modifier changes nothing.
415export function shouldCreateNewThreadInCurrentProject(
416 shiftKey: boolean,
417 projectGroupCount: number,
418): boolean {
419 return shiftKey || projectGroupCount <= 1;
421​
422export function orderItemsByPreferredIds<TItem, TId>(input: {
423 items: readonly TItem[];
424 preferredIds: readonly TId[];
425 getId: (item: TItem) => TId;
426 getPreferenceIds?: (item: TItem) => readonly TId[];
427}): TItem[] {
428 const { getId, getPreferenceIds, items, preferredIds } = input;
429 if (preferredIds.length === 0) {
430 return [...items];
431 }
432​
433 const indexesByPreferenceId = new Map<TId, number[]>();
434 for (const [index, item] of items.entries()) {
435 const preferenceIds = getPreferenceIds?.(item) ?? [getId(item)];
436 for (const preferenceId of new Set(preferenceIds)) {
437 const indexes = indexesByPreferenceId.get(preferenceId);
438 if (indexes) {
439 indexes.push(index);
440 } else {
441 indexesByPreferenceId.set(preferenceId, [index]);
442 }
443 }
444 }
445​
446 const emittedIndexes = new Set<number>();
447 const ordered = preferredIds.flatMap((id) => {
448 const index = indexesByPreferenceId
449 .get(id)
450 ?.find((candidate) => !emittedIndexes.has(candidate));
451 if (index === undefined) {
452 return [];
453 }
454 emittedIndexes.add(index);
455 return [items[index]!];
456 });
457 const remaining = items.filter((_, index) => !emittedIndexes.has(index));
458 return [...ordered, ...remaining];
460​
461export function getVisibleSidebarThreadIds<TThreadId>(
462 renderedProjects: readonly {
463 shouldShowThreadPanel?: boolean;
464 renderedThreadIds: readonly TThreadId[];
465 }[],
466): TThreadId[] {
467 return renderedProjects.flatMap((renderedProject) =>
468 renderedProject.shouldShowThreadPanel === false ? [] : renderedProject.renderedThreadIds,
469 );
471​
472export function getSidebarThreadIdsToPrewarm<TThreadId>(
473 visibleThreadIds: readonly TThreadId[],
474 limit = SIDEBAR_THREAD_PREWARM_LIMIT,
475): TThreadId[] {
476 return visibleThreadIds.slice(0, Math.max(0, limit));
478​
479export function resolveAdjacentThreadId<T>(input: {
480 threadIds: readonly T[];
481 currentThreadId: T | null;
482 direction: ThreadTraversalDirection;
483}): T | null {
484 const { currentThreadId, direction, threadIds } = input;
485​
486 if (threadIds.length === 0) {
487 return null;
488 }
489​
490 if (currentThreadId === null) {
491 return direction === "previous" ? (threadIds.at(-1) ?? null) : (threadIds[0] ?? null);
492 }
493​
494 const currentIndex = threadIds.indexOf(currentThreadId);
495 if (currentIndex === -1) {
496 return null;
497 }
498​
499 if (direction === "previous") {
500 return currentIndex > 0 ? (threadIds[currentIndex - 1] ?? null) : null;
501 }
502​
503 return currentIndex < threadIds.length - 1 ? (threadIds[currentIndex + 1] ?? null) : null;
505​
506export function shouldNavigateAfterProjectRemoval(input: {
507 routeTarget: ThreadRouteTarget | null;
508 projectThreads: readonly {
509 environmentId: string;
510 id: string;
511 }[];
512 projectDraftId: string | null;
513}): boolean {
514 const { projectDraftId, projectThreads, routeTarget } = input;
515 if (routeTarget?.kind === "draft") {
516 return projectDraftId === routeTarget.draftId;
517 }
518 if (routeTarget?.kind !== "server") {
519 return false;
520 }
521 return projectThreads.some(
522 (thread) =>
523 thread.environmentId === routeTarget.threadRef.environmentId &&
524 thread.id === routeTarget.threadRef.threadId,
525 );
527​
528export function isContextMenuPointerDown(input: {
529 button: number;
530 ctrlKey: boolean;
531 isMac: boolean;
532}): boolean {
533 if (input.button === 2) return true;
534 return input.isMac && input.button === 0 && input.ctrlKey;
536​
537export function resolveThreadRowClassName(input: {
538 isActive: boolean;
539 isSelected: boolean;
540}): string {
541 const baseClassName =
542 "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";
543​
544 if (input.isSelected && input.isActive) {
545 return cn(
546 baseClassName,
547 "bg-sidebar-row-active text-sidebar-foreground font-medium hover:bg-sidebar-row-active hover:text-sidebar-foreground",
548 );
549 }
550​
551 if (input.isSelected) {
552 return cn(
553 baseClassName,
554 "bg-sidebar-row-selected text-sidebar-foreground hover:bg-sidebar-row-active hover:text-sidebar-foreground",
555 );
556 }
557​
558 if (input.isActive) {
559 return cn(
560 baseClassName,
561 "bg-sidebar-row-active text-sidebar-foreground font-medium hover:bg-sidebar-row-active hover:text-sidebar-foreground",
562 );
563 }
564​
565 return cn(
566 baseClassName,
567 "text-sidebar-muted-foreground/80 hover:bg-sidebar-row-hover hover:text-sidebar-foreground",
568 );
570​
571// ── Sidebar v2 status model ─────────────────────────────────────────
572// Six visual states, three colors: color is reserved for "act now"
573// (approval), "in motion" (working), and "broken" (failed). Ready is the
574// unlabeled resting state — the agent stopped and is waiting on the user,
575// whether it finished, asked a question, or proposed a plan. Waiting
576// (runtime status "idle") is the agent stopped with background tasks still
577// open: not the user's turn yet, so it renders grey like working, not as a
578// false Done.
579// Unread completion is tracked separately: it describes whether a ready
580// thread needs attention, not what the thread is currently doing.
581export type SidebarThreadStatus = "approval" | "input" | "working" | "waiting" | "failed" | "ready";
582​
583export function shouldRecedeSidebarThread(input: {
584 status: SidebarThreadStatus;
585 isUnread: boolean;
586 isWoke: boolean;
587 isActive: boolean;
588 isSelected: boolean;
589}): boolean {
590 if (input.isActive || input.isSelected) return false;
591 if (input.status === "working" || input.status === "waiting") return true;
592 if (input.status === "ready" || input.status === "approval" || input.status === "input") {
593 return !input.isUnread && !input.isWoke;
594 }
595 return false;
597​
598type SidebarThreadStatusInput = Pick<
599 SidebarThreadSummary,
600 "hasPendingApprovals" | "hasPendingUserInput" | "runtime"
601>;
602​
603export function resolveSidebarThreadStatus(thread: SidebarThreadStatusInput): SidebarThreadStatus {
604 if (thread.hasPendingApprovals) {
605 return "approval";
606 }
607 if (thread.hasPendingUserInput) {
608 return "input";
609 }
610 if (
611 thread.runtime !== null &&
612 ["preparing", "queued", "starting", "running", "waiting"].includes(thread.runtime.status)
613 ) {
614 return "working";
615 }
616 if (thread.runtime?.status === "idle") {
617 return "waiting";
618 }
619 if (thread.runtime?.status === "failed") {
620 return "failed";
621 }
622 return "ready";
624​
625export type SidebarV2TopStatusKind =
626 | "approval"
627 | "done"
628 | "failed"
629 | "input"
630 | "waiting"
631 | "woke"
632 | "working";
633​
634export function resolveSidebarV2TopStatus(input: {
635 readonly status: SidebarThreadStatus;
636 readonly isUnread: boolean;
637 readonly isWoke: boolean;
638}): SidebarV2TopStatusKind | null {
639 if (input.status === "working") {
640 return "working";
641 }
642 if (input.status === "waiting") {
643 return "waiting";
644 }
645 if (input.status === "approval") {
646 return "approval";
647 }
648 if (input.status === "input") {
649 return "input";
650 }
651 if (input.status === "failed") {
652 return "failed";
653 }
654 if (input.isWoke) {
655 return "woke";
656 }
657 return input.isUnread ? "done" : null;
659​
660export function shouldShowSidebarV2Duration(status: SidebarThreadStatus): boolean {
661 return status === "working";
663​
664/** NaN-safe Date.parse for sort comparators: a malformed timestamp must not
665 poison the whole ordering, so it sinks to the epoch instead. */
666export function parseTimestampMs(isoDate: string): number {
667 const parsed = Date.parse(isoDate);
668 return Number.isNaN(parsed) ? 0 : parsed;
670​
671/** First VALID timestamp wins: `a ?? b` falls through on null, but a present-
672 yet-malformed string must also fall through to the next candidate rather
673 than sink the row to the epoch. */
674export function firstValidTimestampMs(
675 ...candidates: ReadonlyArray<string | null | undefined>
676): number {
677 for (const candidate of candidates) {
678 if (candidate == null) continue;
679 const parsed = Date.parse(candidate);
680 if (!Number.isNaN(parsed)) return parsed;
681 }
682 return 0;
684​
685/** String twin of firstValidTimestampMs for callers that need the ISO string
686 (display labels, tick anchors) rather than epoch ms. */
687export function firstValidTimestamp(
688 ...candidates: ReadonlyArray<string | null | undefined>
689): string | null {
690 for (const candidate of candidates) {
691 if (candidate == null) continue;
692 if (!Number.isNaN(Date.parse(candidate))) return candidate;
693 }
694 return null;
696​
697// Sidebar sort: static order, newest anchor on top. Activity NEVER reorders
698// the list — a row holds its position between lifecycle transitions, so the
699// screen only moves when a thread enters or leaves the active list. The
700// anchor is creation time until an un-settle re-anchors it (see
701// activeThreadAnchorTimestampMs), so an un-settled thread surfaces at the
702// top instead of sinking back to its creation-order slot. Status (including
703// pending approval) is carried by each card's edge strip, not by position.
704export function sortThreadsForSidebar<
705 T extends {
706 readonly id: string;
707 readonly createdAt: string;
708 readonly unsettledAt?: string | null | undefined;
709 },
710>(threads: readonly T[]): T[] {
711 return [...threads].toSorted(
712 (left, right) =>
713 activeThreadAnchorTimestampMs(right) - activeThreadAnchorTimestampMs(left) ||
714 left.id.localeCompare(right.id),
715 );
717​
718// Pinned-reorder key math and the keyed sort live in client-runtime
719// (state/thread-sort) so web and mobile compute identical pinned orders.
720export {
721 generateSpreadPinOrderKeys,
722 pinOrderKeyBetween,
723 planPinnedReorder,
724} from "@t3tools/client-runtime/state/thread-sort";
725export { sortPinnedThreadsByOrderKey as sortPinnedThreadsForSidebar } from "@t3tools/client-runtime/state/thread-sort";
726​
727/**
728 * Search the already-ordered sidebar thread collection by title only.
729 * Keeping the input order means lifecycle ordering (active, snoozed, settled)
730 * remains stable while the user narrows the list.
731 */
732export function searchSidebarThreadsByTitle<T extends { readonly title: string }>(
733 threads: readonly T[],
734 query: string,
735): T[] {
736 const normalizedQuery = query.trim().toLowerCase();
737 if (normalizedQuery.length === 0) return [];
738 return threads.filter((thread) => thread.title.toLowerCase().includes(normalizedQuery));
740​
741export function filterSidebarProjectScopeItems<TItem extends { readonly value: string }>(input: {
742 items: readonly TItem[];
743 activeScopeKey: string | null;
744 query: string;
745 matches: (item: TItem, query: string) => boolean;
746}): readonly TItem[] {
747 const projectItems = input.items.filter((item) => item.value !== "all");
748 const query = input.query.trim();
749 if (query.length > 0) {
750 return projectItems.filter((item) => input.matches(item, query));
751 }
752 return input.activeScopeKey === null ? projectItems : input.items;
754​
755export interface SidebarProjectScopeMenuState {
756 readonly open: boolean;
757 readonly query: string;
759​
760export type SidebarProjectScopeMenuAction =
761 | { readonly type: "query-changed"; readonly query: string }
762 | { readonly type: "open-changed"; readonly open: boolean }
763 | { readonly type: "project-settings-opened" };
764​
765export function reduceSidebarProjectScopeMenuState(
766 state: SidebarProjectScopeMenuState,
767 action: SidebarProjectScopeMenuAction,
768): SidebarProjectScopeMenuState {
769 switch (action.type) {
770 case "query-changed":
771 return { ...state, query: action.query };
772 case "open-changed":
773 return { open: action.open, query: "" };
774 case "project-settings-opened":
775 return { open: false, query: "" };
776 }
778​
779type SettledTimestampInput = Pick<
780 SidebarThreadSummary,
781 "settledAt" | "latestUserMessageAt" | "latestRun" | "updatedAt"
782>;
783​
784/** The timestamp a settled row sorts and labels by: settledAt when stamped,
785 otherwise the latest message or turn stamp. updatedAt is the final net. */
786export function resolveSettledTimestamp(thread: SettledTimestampInput): string | null {
787 const settledAt = firstValidTimestamp(thread.settledAt);
788 if (settledAt !== null) return settledAt;
789 let latest: string | null = null;
790 let latestMs = Number.NEGATIVE_INFINITY;
791 for (const candidate of [
792 thread.latestUserMessageAt,
793 thread.latestRun?.requestedAt,
794 thread.latestRun?.startedAt,
795 thread.latestRun?.completedAt,
796 ]) {
797 if (candidate == null) continue;
798 const parsed = Date.parse(candidate);
799 if (!Number.isNaN(parsed) && parsed > latestMs) {
800 latest = candidate;
801 latestMs = parsed;
802 }
803 }
804 return latest ?? firstValidTimestamp(thread.updatedAt);
806​
807// Settled rows are history, so they order by when the work ENDED, not when
808// the thread was created or last touched.
809export function sortSettledThreadsForSidebar<
810 T extends SettledThreadTimestampInput & { readonly id: string },
811>(threads: readonly T[]): T[] {
812 const timestampMs = (thread: T) => {
813 const timestamp = resolveSettledThreadTimestamp(thread);
814 return timestamp === null ? 0 : Date.parse(timestamp);
815 };
816 return [...threads].toSorted(
817 (left, right) => timestampMs(right) - timestampMs(left) || left.id.localeCompare(right.id),
818 );
820​
821/** The timestamp a working thread's elapsed label counts from: the running
822 turn's start (request time until adoption), falling back to the session's
823 last transition when the turn projection lags behind. Malformed
824 timestamps fall through to the next candidate, not just missing ones. */
825export function resolveWorkingStartedAt(
826 thread: Pick<SidebarThreadSummary, "latestRun" | "runtime">,
827): string | null {
828 const run = thread.latestRun;
829 if (run && run.completedAt === null) {
830 return firstValidTimestamp(run.startedAt, run.requestedAt, thread.runtime?.updatedAt);
831 }
832 return firstValidTimestamp(thread.runtime?.updatedAt);
834​
835export function formatWorkingDurationLabel(elapsedMs: number): string {
836 const seconds = Number.isFinite(elapsedMs) ? Math.max(0, Math.floor(elapsedMs / 1000)) : 0;
837 if (seconds < 60) return `${seconds}s`;
838 const minutes = Math.floor(seconds / 60);
839 if (minutes < 60) return `${minutes}m`;
840 return `${Math.floor(minutes / 60)}h ${minutes % 60}m`;
842​
843export function resolveThreadStatusPill(input: {
844 thread: ThreadStatusInput;
845}): ThreadStatusPill | null {
846 const { thread } = input;
847​
848 if (thread.hasPendingApprovals) {
849 return {
850 label: "Pending Approval",
851 colorClass: "text-amber-600 dark:text-amber-300/90",
852 dotClass: "bg-amber-500 dark:bg-amber-300/90",
853 pulse: false,
854 };
855 }
856​
857 if (thread.hasPendingUserInput) {
858 return {
859 label: "Awaiting Input",
860 colorClass: "text-indigo-600 dark:text-indigo-300/90",
861 dotClass: "bg-indigo-500 dark:bg-indigo-300/90",
862 pulse: false,
863 };
864 }
865​
866 if (thread.runtime?.status === "running" || thread.runtime?.status === "waiting") {
867 return {
868 label: "Working",
869 colorClass: "text-sky-600 dark:text-sky-300/80",
870 dotClass: "bg-sky-500 dark:bg-sky-300/80",
871 pulse: true,
872 };
873 }
874​
875 if (
876 thread.runtime?.status === "preparing" ||
877 thread.runtime?.status === "starting" ||
878 thread.runtime?.status === "queued"
879 ) {
880 return {
881 label: "Connecting",
882 colorClass: "text-sky-600 dark:text-sky-300/80",
883 dotClass: "bg-sky-500 dark:bg-sky-300/80",
884 pulse: true,
885 };
886 }
887​
888 if ((thread.pendingBackgroundTasks?.length ?? 0) > 0) {
889 return {
890 label: "Waiting",
891 colorClass: "text-sidebar-muted-foreground",
892 dotClass: "bg-sidebar-muted-foreground",
893 pulse: false,
894 };
895 }
896​
897 const hasPlanReadyPrompt =
898 !thread.hasPendingUserInput &&
899 thread.interactionMode === "plan" &&
900 isLatestRunSettled(thread.latestRun, thread.runtime) &&
901 thread.hasActionableProposedPlan;
902 if (hasPlanReadyPrompt) {
903 return {
904 label: "Plan Ready",
905 colorClass: "text-violet-600 dark:text-violet-300/90",
906 dotClass: "bg-violet-500 dark:bg-violet-300/90",
907 pulse: false,
908 };
909 }
910​
911 if (hasUnseenCompletion(thread)) {
912 return {
913 label: "Completed",
914 colorClass: "text-emerald-600 dark:text-emerald-300/90",
915 dotClass: "bg-emerald-500 dark:bg-emerald-300/90",
916 pulse: false,
917 };
918 }
919​
920 return null;
922​
923export function resolveProjectStatusIndicator(
924 statuses: ReadonlyArray<ThreadStatusPill | null>,
925): ThreadStatusPill | null {
926 let highestPriorityStatus: ThreadStatusPill | null = null;
927​
928 for (const status of statuses) {
929 if (status === null) continue;
930 if (
931 highestPriorityStatus === null ||
932 THREAD_STATUS_PRIORITY[status.label] > THREAD_STATUS_PRIORITY[highestPriorityStatus.label]
933 ) {
934 highestPriorityStatus = status;
935 }
936 }
937​
938 return highestPriorityStatus;
940​
941export function getVisibleThreadsForProject<T extends Pick<Thread, "id">>(input: {
942 threads: readonly T[];
943 activeThreadId: T["id"] | undefined;
944 isThreadListExpanded: boolean;
945 previewLimit: number;
946}): {
947 hasHiddenThreads: boolean;
948 visibleThreads: T[];
949 hiddenThreads: T[];
950} {
951 const { activeThreadId, isThreadListExpanded, previewLimit, threads } = input;
952 const hasHiddenThreads = threads.length > previewLimit;
953​
954 if (!hasHiddenThreads || isThreadListExpanded) {
955 return {
956 hasHiddenThreads,
957 hiddenThreads: [],
958 visibleThreads: [...threads],
959 };
960 }
961​
962 const previewThreads = threads.slice(0, previewLimit);
963 if (!activeThreadId || previewThreads.some((thread) => thread.id === activeThreadId)) {
964 return {
965 hasHiddenThreads: true,
966 hiddenThreads: threads.slice(previewLimit),
967 visibleThreads: previewThreads,
968 };
969 }
970​
971 const activeThread = threads.find((thread) => thread.id === activeThreadId);
972 if (!activeThread) {
973 return {
974 hasHiddenThreads: true,
975 hiddenThreads: threads.slice(previewLimit),
976 visibleThreads: previewThreads,
977 };
978 }
979​
980 const visibleThreadIds = new Set([...previewThreads, activeThread].map((thread) => thread.id));
981​
982 return {
983 hasHiddenThreads: true,
984 hiddenThreads: threads.filter((thread) => !visibleThreadIds.has(thread.id)),
985 visibleThreads: threads.filter((thread) => visibleThreadIds.has(thread.id)),
986 };
988​
989export function getFallbackThreadIdAfterDelete<
990 T extends Pick<Thread, "id" | "projectId" | "createdAt" | "updatedAt"> & ThreadSortInput,
991>(input: {
992 threads: readonly T[];
993 deletedThreadId: T["id"];
994 sortOrder: SidebarThreadSortOrder;
995 deletedThreadIds?: ReadonlySet<T["id"]>;
996}): T["id"] | null {
997 const { deletedThreadId, deletedThreadIds, sortOrder, threads } = input;
998 const deletedThread = threads.find((thread) => thread.id === deletedThreadId);
999 if (!deletedThread) {
1000 return null;
1002​
1003 return (
1004 sortThreads(
1005 threads.filter(
1006 (thread) =>
1007 thread.projectId === deletedThread.projectId &&
1008 thread.id !== deletedThreadId &&
1009 !deletedThreadIds?.has(thread.id),
1010 ),
1011 sortOrder,
1012 )[0]?.id ?? null
1013 );
1015export function getProjectSortTimestamp(
1016 project: SidebarProject,
1017 projectThreads: readonly ThreadSortInput[],
1018 sortOrder: Exclude<SidebarProjectSortOrder, "manual">,
1019): number {
1020 if (projectThreads.length > 0) {
1021 return projectThreads.reduce(
1022 (latest, thread) => Math.max(latest, getThreadSortTimestamp(thread, sortOrder)),
1023 Number.NEGATIVE_INFINITY,
1024 );
1026​
1027 if (sortOrder === "created_at") {
1028 return toSortableTimestamp(project.createdAt) ?? Number.NEGATIVE_INFINITY;
1030 return toSortableTimestamp(project.updatedAt ?? project.createdAt) ?? Number.NEGATIVE_INFINITY;
1032​
1033function sortProjectsByActivity<TProject extends SidebarProject>(
1034 projects: readonly TProject[],
1035 sortOrder: SidebarProjectSortOrder,
1036 getProjectThreads: (project: TProject) => readonly ThreadSortInput[],
1037 compareTies: (left: TProject, right: TProject) => number,
1038): TProject[] {
1039 if (sortOrder === "manual") {
1040 return [...projects];
1042​
1043 return [...projects].toSorted((left, right) => {
1044 const rightTimestamp = getProjectSortTimestamp(right, getProjectThreads(right), sortOrder);
1045 const leftTimestamp = getProjectSortTimestamp(left, getProjectThreads(left), sortOrder);
1046 const byTimestamp =
1047 rightTimestamp === leftTimestamp ? 0 : rightTimestamp > leftTimestamp ? 1 : -1;
1048 return byTimestamp || compareTies(left, right);
1049 });
1051​
1052export function sortProjectsForSidebar<
1053 TProject extends SidebarProject,
1054 TThread extends Pick<Thread, "projectId" | "createdAt" | "updatedAt"> & ThreadSortInput,
1056 projects: readonly TProject[],
1057 threads: readonly TThread[],
1058 sortOrder: SidebarProjectSortOrder,
1059): TProject[] {
1060 const threadsByProjectId = new Map<string, TThread[]>();
1061 for (const thread of threads) {
1062 const existing = threadsByProjectId.get(thread.projectId) ?? [];
1063 existing.push(thread);
1064 threadsByProjectId.set(thread.projectId, existing);
1066​
1067 return sortProjectsByActivity(
1068 projects,
1069 sortOrder,
1070 (project) => threadsByProjectId.get(project.id) ?? [],
1071 (left, right) => left.title.localeCompare(right.title) || left.id.localeCompare(right.id),
1072 );
1074​
1075export function sortLogicalProjectsForSidebar<
1076 TProject extends LogicalSidebarProject,
1077 TThread extends ScopedSidebarThread,
1079 projects: readonly TProject[],
1080 threads: readonly TThread[],
1081 sortOrder: SidebarProjectSortOrder,
1082): TProject[] {
1083 const groupKeyByProjectRef = new Map(
1084 projects.flatMap((project) =>
1085 project.memberProjectRefs.map(
1086 (projectRef) =>
1087 [`${projectRef.environmentId}\0${projectRef.projectId}`, project.projectKey] as const,
1088 ),
1089 ),
1090 );
1091 const threadsByProjectKey = new Map<string, TThread[]>();
1092 for (const thread of threads) {
1093 if (thread.archivedAt !== null) continue;
1094 const projectKey = groupKeyByProjectRef.get(`${thread.environmentId}\0${thread.projectId}`);
1095 if (!projectKey) continue;
1096 const existing = threadsByProjectKey.get(projectKey);
1097 if (existing) {
1098 existing.push(thread);
1099 } else {
1100 threadsByProjectKey.set(projectKey, [thread]);
1103​
1104 return sortProjectsByActivity(
1105 projects,
1106 sortOrder,
1107 (project) => threadsByProjectKey.get(project.projectKey) ?? [],
1108 (left, right) =>
1109 left.title.localeCompare(right.title) || left.projectKey.localeCompare(right.projectKey),
1110 );
1112​
1113export function sortSidebarV2ProjectGroups<
1114 TProject extends LogicalSidebarProject,
1115 TThread extends ScopedSidebarThread & Pick<SidebarThreadSummary, "lineage">,
1117 projects: readonly TProject[],
1118 threads: readonly TThread[],
1119 sortOrder: SidebarProjectSortOrder,
1120): TProject[] {
1121 return sortLogicalProjectsForSidebar(
1122 projects,
1123 filterSidebarV2VisibleThreads(threads, null),
1124 sortOrder,
1125 );
1127​
1128/**
1129 * Sorts the cross-environment project collection used by landing surfaces.
1130 * Project ids are only unique within an environment, and archived threads
1131 * must not make a project appear recently active.
1132 */
1133export function sortScopedProjectsForSidebar<
1134 TProject extends ScopedSidebarProject,
1135 TThread extends ScopedSidebarThread,
1137 projects: readonly TProject[],
1138 threads: readonly TThread[],
1139 sortOrder: SidebarProjectSortOrder,
1140): TProject[] {
1141 const scopedKey = (environmentId: string, projectId: string) =>
1142 `${environmentId}\u0000${projectId}`;
1143 const threadsByProject = new Map<string, TThread[]>();
1144 for (const thread of threads) {
1145 if (thread.archivedAt !== null) {
1146 continue;
1148 const key = scopedKey(thread.environmentId, thread.projectId);
1149 const existing = threadsByProject.get(key) ?? [];
1150 existing.push(thread);
1151 threadsByProject.set(key, existing);
1153​
1154 return sortProjectsByActivity(
1155 projects,
1156 sortOrder,
1157 (project) => threadsByProject.get(scopedKey(project.environmentId, project.id)) ?? [],
1158 (left, right) =>
1159 left.title.localeCompare(right.title) ||
1160 left.environmentId.localeCompare(right.environmentId) ||
1161 left.id.localeCompare(right.id),
1162 );