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