Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

Sidebar.logic.ts

996 lines32.0 KB

1import * as React from "react";
2import { defaultAnimateLayoutChanges, type AnimateLayoutChanges } from "@dnd-kit/sortable";
3import type { ContextMenuItem } from "@t3tools/contracts";
4import type { SidebarProjectSortOrder, SidebarThreadSortOrder } from "@t3tools/contracts/settings";
5import {
6 activeThreadAnchorTimestampMs,
7 getThreadSortTimestamp,
8 sortThreads,
9 toSortableTimestamp,
10 type ThreadSortInput,
11} from "../lib/threadSort";
12import type { SidebarThreadSummary, Thread } from "../types";
13import type { ThreadRouteTarget } from "../threadRoutes";
14import { cn } from "../lib/utils";
15import { isLatestTurnSettled } from "../session-logic";
16​
17export const THREAD_SELECTION_SAFE_SELECTOR = "[data-thread-item], [data-thread-selection-safe]";
18export const THREAD_JUMP_HINT_SHOW_DELAY_MS = 200;
19// Visible sidebar rows are prewarmed into the thread-detail cache so opening a
20// nearby thread usually reuses an already-hot subscription. Each prewarmed
21// thread holds a live, fully hydrated detail subscription (all messages and
22// activities, growing as agents work) for as long as the row stays visible,
23// so this limit is a direct renderer-heap and server-load multiplier — keep
24// it small; cold opens still render instantly from the cached snapshot.
25export const SIDEBAR_THREAD_PREWARM_LIMIT = 3;
26​
27// The list already reaches its destination through sortable transforms while
28// the pointer is down. dnd-kit's default also animates the committed DOM order
29// after release, replaying the same movement across every affected row.
30export const animatePinnedLayoutChanges: AnimateLayoutChanges = (args) =>
31 args.isSorting ? defaultAnimateLayoutChanges(args) : false;
32​
33type SidebarProject = {
34 id: string;
35 title: string;
36 createdAt?: string | undefined;
37 updatedAt?: string | undefined;
38};
39​
40type ScopedSidebarProject = SidebarProject & {
41 environmentId: string;
42};
43​
44type ScopedSidebarThread = ThreadSortInput & {
45 environmentId: string;
46 projectId: string;
47 archivedAt: string | null;
48};
49​
50type LogicalSidebarProject = SidebarProject & {
51 projectKey: string;
52 memberProjectRefs: readonly {
53 environmentId: string;
54 projectId: string;
55 }[];
56};
57​
58export type ThreadTraversalDirection = "previous" | "next";
59​
60export async function archiveSelectedThreadEntries<
61 TEntry extends { readonly threadKey: string },
62 TResult extends { readonly _tag: "Success" | "Failure" },
63>(input: {
64 entries: readonly TEntry[];
65 archive: (entry: TEntry, onArchived: () => void) => Promise<TResult>;
66}): Promise<{
67 archivedThreadKeys: readonly string[];
68 mutationFailure: Extract<TResult, { readonly _tag: "Failure" }> | null;
69 followupFailures: readonly Extract<TResult, { readonly _tag: "Failure" }>[];
70}> {
71 const archivedThreadKeys: string[] = [];
72 const followupFailures: Extract<TResult, { readonly _tag: "Failure" }>[] = [];
73​
74 for (const entry of input.entries) {
75 let didArchive = false;
76 const result = await input.archive(entry, () => {
77 didArchive = true;
78 });
79 if (didArchive || result._tag === "Success") {
80 archivedThreadKeys.push(entry.threadKey);
81 }
82 if (result._tag === "Success") continue;
83 const failure = result as Extract<TResult, { readonly _tag: "Failure" }>;
84 if (didArchive) {
85 followupFailures.push(failure);
86 continue;
87 }
88 return { archivedThreadKeys, mutationFailure: failure, followupFailures };
89 }
90​
91 return { archivedThreadKeys, mutationFailure: null, followupFailures };
93​
94export function buildMultiSelectThreadContextMenuItems(input: {
95 count: number;
96 hasRunningThread: boolean;
97}): readonly ContextMenuItem<"mark-unread" | "archive" | "delete">[] {
98 return [
99 { id: "mark-unread", label: `Mark unread (${input.count})` },
100 {
101 id: "archive",
102 label: `Archive (${input.count})`,
103 disabled: input.hasRunningThread,
104 },
105 { id: "delete", label: `Delete (${input.count})`, destructive: true },
106 ];
108​
109export function buildBulkTitleRegenerationContextMenuItem(input: {
110 supportedCount: number;
111 actionableCount: number;
112}): ContextMenuItem<"regenerate-title"> | null {
113 if (input.supportedCount === 0) return null;
114 if (input.actionableCount === 0) {
115 return {
116 id: "regenerate-title",
117 label: `Regenerating… (${input.supportedCount})`,
118 disabled: true,
119 };
120 }
121 return {
122 id: "regenerate-title",
123 label: `Regenerate titles (${input.actionableCount})`,
124 };
126​
127export interface ThreadStatusPill {
128 label:
129 | "Working"
130 | "Monitoring"
131 | "Connecting"
132 | "Completed"
133 | "Pending Approval"
134 | "Awaiting Input"
135 | "Plan Ready";
136 colorClass: string;
137 dotClass: string;
138 pulse: boolean;
140​
141// Rollup order mirrors the per-thread resolver exactly: attention states,
142// then active work, then the actionable plan prompt, then passive
143// monitoring. A Monitoring sibling must never hide a Plan Ready thread.
144const THREAD_STATUS_PRIORITY: Record<ThreadStatusPill["label"], number> = {
145 "Pending Approval": 6,
146 "Awaiting Input": 5,
147 Working: 4,
148 Connecting: 4,
149 "Plan Ready": 3,
150 Monitoring: 2,
151 Completed: 1,
152};
153​
154type ThreadStatusInput = Pick<
155 SidebarThreadSummary,
156 | "hasActionableProposedPlan"
157 | "hasPendingApprovals"
158 | "hasPendingUserInput"
159 | "interactionMode"
160 | "latestTurn"
161 | "session"
162 | "backgroundLiveness"
163> & {
164 lastVisitedAt?: string | undefined;
165};
166​
167export interface ThreadJumpHintVisibilityController {
168 sync: (shouldShow: boolean) => void;
169 dispose: () => void;
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 };
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 };
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;
262​
263export function shouldClearThreadSelectionOnMouseDown(target: HTMLElement | null): boolean {
264 if (target === null) return true;
265 return !target.closest(THREAD_SELECTION_SAFE_SELECTOR);
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;
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);
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;
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;
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];
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 );
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));
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;
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 );
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;
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 );
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";
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;
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;
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;
533​
534// Sidebar sort: static order, newest anchor on top. Activity NEVER reorders
535// the list — a row holds its position between lifecycle transitions, so the
536// screen only moves when a thread enters or leaves the active list. The
537// anchor is creation time until an un-settle re-anchors it (see
538// activeThreadAnchorTimestampMs), so an un-settled thread surfaces at the
539// top instead of sinking back to its creation-order slot. Status (including
540// pending approval) is carried by each card's edge strip, not by position.
541export function sortThreadsForSidebar<
542 T extends {
543 readonly id: string;
544 readonly createdAt: string;
545 readonly unsettledAt?: string | null | undefined;
546 },
547>(threads: readonly T[]): T[] {
548 return [...threads].toSorted(
549 (left, right) =>
550 activeThreadAnchorTimestampMs(right) - activeThreadAnchorTimestampMs(left) ||
551 left.id.localeCompare(right.id),
552 );
554​
555// Pinned-reorder key math and the keyed sort live in client-runtime
556// (state/thread-sort) so web and mobile compute identical pinned orders.
557export {
558 generateSpreadPinOrderKeys,
559 pinOrderKeyBetween,
560 planPinnedReorder,
561} from "@t3tools/client-runtime/state/thread-sort";
562export { sortPinnedThreadsByOrderKey as sortPinnedThreadsForSidebar } from "@t3tools/client-runtime/state/thread-sort";
563​
564/**
565 * Search the already-ordered sidebar thread collection by title only.
566 * Keeping the input order means lifecycle ordering (active, snoozed, settled)
567 * remains stable while the user narrows the list.
568 */
569export function searchSidebarThreadsByTitle<T extends { readonly title: string }>(
570 threads: readonly T[],
571 query: string,
572): T[] {
573 const normalizedQuery = query.trim().toLowerCase();
574 if (normalizedQuery.length === 0) return [];
575 return threads.filter((thread) => thread.title.toLowerCase().includes(normalizedQuery));
577​
578export function filterSidebarProjectScopeItems<TItem extends { readonly value: string }>(input: {
579 items: readonly TItem[];
580 activeScopeKey: string | null;
581 query: string;
582 matches: (item: TItem, query: string) => boolean;
583}): readonly TItem[] {
584 const projectItems = input.items.filter((item) => item.value !== "all");
585 const query = input.query.trim();
586 if (query.length > 0) {
587 return projectItems.filter((item) => input.matches(item, query));
588 }
589 return input.activeScopeKey === null ? projectItems : input.items;
591​
592export interface SidebarProjectScopeMenuState {
593 readonly open: boolean;
594 readonly query: string;
596​
597export type SidebarProjectScopeMenuAction =
598 | { readonly type: "query-changed"; readonly query: string }
599 | { readonly type: "open-changed"; readonly open: boolean }
600 | { readonly type: "project-settings-opened" };
601​
602export function reduceSidebarProjectScopeMenuState(
603 state: SidebarProjectScopeMenuState,
604 action: SidebarProjectScopeMenuAction,
605): SidebarProjectScopeMenuState {
606 switch (action.type) {
607 case "query-changed":
608 return { ...state, query: action.query };
609 case "open-changed":
610 return { open: action.open, query: "" };
611 case "project-settings-opened":
612 return { open: false, query: "" };
613 }
615​
616type SettledTimestampInput = Pick<
617 SidebarThreadSummary,
618 "settledAt" | "latestUserMessageAt" | "latestTurn" | "updatedAt"
619>;
620​
621/** The timestamp a settled row sorts and labels by: settledAt when stamped,
622 otherwise the latest message or turn stamp. updatedAt is the final net. */
623export function resolveSettledTimestamp(thread: SettledTimestampInput): string | null {
624 const settledAt = firstValidTimestamp(thread.settledAt);
625 if (settledAt !== null) return settledAt;
626 let latest: string | null = null;
627 let latestMs = Number.NEGATIVE_INFINITY;
628 for (const candidate of [
629 thread.latestUserMessageAt,
630 thread.latestTurn?.requestedAt,
631 thread.latestTurn?.startedAt,
632 thread.latestTurn?.completedAt,
633 ]) {
634 if (candidate == null) continue;
635 const parsed = Date.parse(candidate);
636 if (!Number.isNaN(parsed) && parsed > latestMs) {
637 latest = candidate;
638 latestMs = parsed;
639 }
640 }
641 return latest ?? firstValidTimestamp(thread.updatedAt);
643​
644// Settled rows are history, so they order by when the work ENDED, not when
645// the thread was created or last touched.
646export function sortSettledThreadsForSidebar<
647 T extends SettledTimestampInput & { readonly id: string },
648>(threads: readonly T[]): T[] {
649 const timestampMs = (thread: T) => {
650 const timestamp = resolveSettledTimestamp(thread);
651 return timestamp === null ? 0 : Date.parse(timestamp);
652 };
653 return [...threads].toSorted(
654 (left, right) => timestampMs(right) - timestampMs(left) || left.id.localeCompare(right.id),
655 );
657​
658/** The timestamp a working thread's elapsed label counts from: the running
659 turn's start (request time until adoption), falling back to the session's
660 last transition when the turn projection lags behind. Malformed
661 timestamps fall through to the next candidate, not just missing ones. */
662export function resolveWorkingStartedAt(
663 thread: Pick<SidebarThreadSummary, "latestTurn" | "session">,
664): string | null {
665 const turn = thread.latestTurn;
666 if (turn && turn.completedAt === null) {
667 return firstValidTimestamp(turn.startedAt, turn.requestedAt, thread.session?.updatedAt);
668 }
669 return firstValidTimestamp(thread.session?.updatedAt);
671​
672export function formatWorkingDurationLabel(elapsedMs: number): string {
673 const seconds = Number.isFinite(elapsedMs) ? Math.max(0, Math.floor(elapsedMs / 1000)) : 0;
674 if (seconds < 60) return `${seconds}s`;
675 const minutes = Math.floor(seconds / 60);
676 if (minutes < 60) return `${minutes}m`;
677 return `${Math.floor(minutes / 60)}h ${minutes % 60}m`;
679​
680export function resolveThreadStatusPill(input: {
681 thread: ThreadStatusInput;
682}): ThreadStatusPill | null {
683 const { thread } = input;
684​
685 if (thread.hasPendingApprovals) {
686 return {
687 label: "Pending Approval",
688 colorClass: "text-amber-600 dark:text-amber-300/90",
689 dotClass: "bg-amber-500 dark:bg-amber-300/90",
690 pulse: false,
691 };
692 }
693​
694 if (thread.hasPendingUserInput) {
695 return {
696 label: "Awaiting Input",
697 colorClass: "text-indigo-600 dark:text-indigo-300/90",
698 dotClass: "bg-indigo-500 dark:bg-indigo-300/90",
699 pulse: false,
700 };
701 }
702​
703 if (thread.session?.status === "running") {
704 return {
705 label: "Working",
706 colorClass: "text-sky-600 dark:text-sky-300/80",
707 dotClass: "bg-sky-500 dark:bg-sky-300/80",
708 pulse: true,
709 };
710 }
711​
712 if (thread.session?.status === "starting") {
713 return {
714 label: "Connecting",
715 colorClass: "text-sky-600 dark:text-sky-300/80",
716 dotClass: "bg-sky-500 dark:bg-sky-300/80",
717 pulse: true,
718 };
719 }
720​
721 // An actionable plan prompt outranks lingering background work: it needs
722 // the user's decision, while liveness merely reports (review finding).
723 const hasPlanReadyPrompt =
724 !thread.hasPendingUserInput &&
725 thread.interactionMode === "plan" &&
726 isLatestTurnSettled(thread.latestTurn, thread.session) &&
727 thread.hasActionableProposedPlan;
728 if (hasPlanReadyPrompt) {
729 return {
730 label: "Plan Ready",
731 colorClass: "text-violet-600 dark:text-violet-300/90",
732 dotClass: "bg-violet-500 dark:bg-violet-300/90",
733 pulse: false,
734 };
735 }
736​
737 // The turn can settle while native background work runs on. Subagent and
738 // workflow fleets read as plain Working; Monitoring is reserved for watch
739 // loops (a parent agent babysitting a PR, tailing checks) with no other
740 // live work. Same recede treatment as Working per inbox-zero.
741 if (thread.backgroundLiveness === "working") {
742 return {
743 label: "Working",
744 colorClass: "text-sky-600 dark:text-sky-300/80",
745 dotClass: "bg-sky-500 dark:bg-sky-300/80",
746 pulse: true,
747 };
748 }
749​
750 if (thread.backgroundLiveness === "monitoring") {
751 return {
752 label: "Monitoring",
753 colorClass: "text-sky-600 dark:text-sky-300/80",
754 dotClass: "bg-sky-500 dark:bg-sky-300/80",
755 pulse: false,
756 };
757 }
758​
759 if (hasUnseenCompletion(thread)) {
760 return {
761 label: "Completed",
762 colorClass: "text-emerald-600 dark:text-emerald-300/90",
763 dotClass: "bg-emerald-500 dark:bg-emerald-300/90",
764 pulse: false,
765 };
766 }
767​
768 return null;
770​
771export function resolveProjectStatusIndicator(
772 statuses: ReadonlyArray<ThreadStatusPill | null>,
773): ThreadStatusPill | null {
774 let highestPriorityStatus: ThreadStatusPill | null = null;
775​
776 for (const status of statuses) {
777 if (status === null) continue;
778 if (
779 highestPriorityStatus === null ||
780 THREAD_STATUS_PRIORITY[status.label] > THREAD_STATUS_PRIORITY[highestPriorityStatus.label]
781 ) {
782 highestPriorityStatus = status;
783 }
784 }
785​
786 return highestPriorityStatus;
788​
789export function getVisibleThreadsForProject<T extends Pick<Thread, "id">>(input: {
790 threads: readonly T[];
791 activeThreadId: T["id"] | undefined;
792 isThreadListExpanded: boolean;
793 previewLimit: number;
794}): {
795 hasHiddenThreads: boolean;
796 visibleThreads: T[];
797 hiddenThreads: T[];
798} {
799 const { activeThreadId, isThreadListExpanded, previewLimit, threads } = input;
800 const hasHiddenThreads = threads.length > previewLimit;
801​
802 if (!hasHiddenThreads || isThreadListExpanded) {
803 return {
804 hasHiddenThreads,
805 hiddenThreads: [],
806 visibleThreads: [...threads],
807 };
808 }
809​
810 const previewThreads = threads.slice(0, previewLimit);
811 if (!activeThreadId || previewThreads.some((thread) => thread.id === activeThreadId)) {
812 return {
813 hasHiddenThreads: true,
814 hiddenThreads: threads.slice(previewLimit),
815 visibleThreads: previewThreads,
816 };
817 }
818​
819 const activeThread = threads.find((thread) => thread.id === activeThreadId);
820 if (!activeThread) {
821 return {
822 hasHiddenThreads: true,
823 hiddenThreads: threads.slice(previewLimit),
824 visibleThreads: previewThreads,
825 };
826 }
827​
828 const visibleThreadIds = new Set([...previewThreads, activeThread].map((thread) => thread.id));
829​
830 return {
831 hasHiddenThreads: true,
832 hiddenThreads: threads.filter((thread) => !visibleThreadIds.has(thread.id)),
833 visibleThreads: threads.filter((thread) => visibleThreadIds.has(thread.id)),
834 };
836​
837export function getFallbackThreadIdAfterDelete<
838 T extends Pick<Thread, "id" | "projectId" | "createdAt" | "updatedAt"> & ThreadSortInput,
839>(input: {
840 threads: readonly T[];
841 deletedThreadId: T["id"];
842 sortOrder: SidebarThreadSortOrder;
843 deletedThreadIds?: ReadonlySet<T["id"]>;
844}): T["id"] | null {
845 const { deletedThreadId, deletedThreadIds, sortOrder, threads } = input;
846 const deletedThread = threads.find((thread) => thread.id === deletedThreadId);
847 if (!deletedThread) {
848 return null;
849 }
850​
851 return (
852 sortThreads(
853 threads.filter(
854 (thread) =>
855 thread.projectId === deletedThread.projectId &&
856 thread.id !== deletedThreadId &&
857 !deletedThreadIds?.has(thread.id),
858 ),
859 sortOrder,
860 )[0]?.id ?? null
861 );
863export function getProjectSortTimestamp(
864 project: SidebarProject,
865 projectThreads: readonly ThreadSortInput[],
866 sortOrder: Exclude<SidebarProjectSortOrder, "manual">,
867): number {
868 if (projectThreads.length > 0) {
869 return projectThreads.reduce(
870 (latest, thread) => Math.max(latest, getThreadSortTimestamp(thread, sortOrder)),
871 Number.NEGATIVE_INFINITY,
872 );
873 }
874​
875 if (sortOrder === "created_at") {
876 return toSortableTimestamp(project.createdAt) ?? Number.NEGATIVE_INFINITY;
877 }
878 return toSortableTimestamp(project.updatedAt ?? project.createdAt) ?? Number.NEGATIVE_INFINITY;
880​
881function sortProjectsByActivity<TProject extends SidebarProject>(
882 projects: readonly TProject[],
883 sortOrder: SidebarProjectSortOrder,
884 getProjectThreads: (project: TProject) => readonly ThreadSortInput[],
885 compareTies: (left: TProject, right: TProject) => number,
886): TProject[] {
887 if (sortOrder === "manual") {
888 return [...projects];
889 }
890​
891 return [...projects].toSorted((left, right) => {
892 const rightTimestamp = getProjectSortTimestamp(right, getProjectThreads(right), sortOrder);
893 const leftTimestamp = getProjectSortTimestamp(left, getProjectThreads(left), sortOrder);
894 const byTimestamp =
895 rightTimestamp === leftTimestamp ? 0 : rightTimestamp > leftTimestamp ? 1 : -1;
896 return byTimestamp || compareTies(left, right);
897 });
899​
900export function sortProjectsForSidebar<
901 TProject extends SidebarProject,
902 TThread extends Pick<Thread, "projectId" | "createdAt" | "updatedAt"> & ThreadSortInput,
903>(
904 projects: readonly TProject[],
905 threads: readonly TThread[],
906 sortOrder: SidebarProjectSortOrder,
907): TProject[] {
908 const threadsByProjectId = new Map<string, TThread[]>();
909 for (const thread of threads) {
910 const existing = threadsByProjectId.get(thread.projectId) ?? [];
911 existing.push(thread);
912 threadsByProjectId.set(thread.projectId, existing);
913 }
914​
915 return sortProjectsByActivity(
916 projects,
917 sortOrder,
918 (project) => threadsByProjectId.get(project.id) ?? [],
919 (left, right) => left.title.localeCompare(right.title) || left.id.localeCompare(right.id),
920 );
922​
923export function sortLogicalProjectsForSidebar<
924 TProject extends LogicalSidebarProject,
925 TThread extends ScopedSidebarThread,
926>(
927 projects: readonly TProject[],
928 threads: readonly TThread[],
929 sortOrder: SidebarProjectSortOrder,
930): TProject[] {
931 const groupKeyByProjectRef = new Map(
932 projects.flatMap((project) =>
933 project.memberProjectRefs.map(
934 (projectRef) =>
935 [`${projectRef.environmentId}\0${projectRef.projectId}`, project.projectKey] as const,
936 ),
937 ),
938 );
939 const threadsByProjectKey = new Map<string, TThread[]>();
940 for (const thread of threads) {
941 if (thread.archivedAt !== null) continue;
942 const projectKey = groupKeyByProjectRef.get(`${thread.environmentId}\0${thread.projectId}`);
943 if (!projectKey) continue;
944 const existing = threadsByProjectKey.get(projectKey);
945 if (existing) {
946 existing.push(thread);
947 } else {
948 threadsByProjectKey.set(projectKey, [thread]);
949 }
950 }
951​
952 return sortProjectsByActivity(
953 projects,
954 sortOrder,
955 (project) => threadsByProjectKey.get(project.projectKey) ?? [],
956 (left, right) =>
957 left.title.localeCompare(right.title) || left.projectKey.localeCompare(right.projectKey),
958 );
960​
961/**
962 * Sorts the cross-environment project collection used by landing surfaces.
963 * Project ids are only unique within an environment, and archived threads
964 * must not make a project appear recently active.
965 */
966export function sortScopedProjectsForSidebar<
967 TProject extends ScopedSidebarProject,
968 TThread extends ScopedSidebarThread,
969>(
970 projects: readonly TProject[],
971 threads: readonly TThread[],
972 sortOrder: SidebarProjectSortOrder,
973): TProject[] {
974 const scopedKey = (environmentId: string, projectId: string) =>
975 `${environmentId}\u0000${projectId}`;
976 const threadsByProject = new Map<string, TThread[]>();
977 for (const thread of threads) {
978 if (thread.archivedAt !== null) {
979 continue;
980 }
981 const key = scopedKey(thread.environmentId, thread.projectId);
982 const existing = threadsByProject.get(key) ?? [];
983 existing.push(thread);
984 threadsByProject.set(key, existing);
985 }
986​
987 return sortProjectsByActivity(
988 projects,
989 sortOrder,
990 (project) => threadsByProject.get(scopedKey(project.environmentId, project.id)) ?? [],
991 (left, right) =>
992 left.title.localeCompare(right.title) ||
993 left.environmentId.localeCompare(right.environmentId) ||
994 left.id.localeCompare(right.id),
995 );