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