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