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