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