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