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