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

Sidebar.logic.ts

1,007 lines32.4 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";
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 };
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 ];
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 };
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;
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;
172​
173export function resolveSidebarStageBadgeLabel(input: {
174 primaryServerVersion: string | null | undefined;
175 fallbackStageLabel: string;
176}): string {
177 return resolveServerBackedAppStageLabel(input);
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 };
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 };
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;
270​
271export function shouldClearThreadSelectionOnMouseDown(target: HTMLElement | null): boolean {
272 if (target === null) return true;
273 return !target.closest(THREAD_SELECTION_SAFE_SELECTOR);
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;
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);
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;
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;
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];
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 );
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));
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;
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 );
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;
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 );
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";
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;
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;
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;
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 );
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));
585​
586export function filterSidebarProjectScopeItems<TItem extends { readonly value: string }>(input: {
587 items: readonly TItem[];
588 activeScopeKey: string | null;
589 query: string;
590 matches: (item: TItem, query: string) => boolean;
591}): readonly TItem[] {
592 const projectItems = input.items.filter((item) => item.value !== "all");
593 const query = input.query.trim();
594 if (query.length > 0) {
595 return projectItems.filter((item) => input.matches(item, query));
596 }
597 return input.activeScopeKey === null ? projectItems : input.items;
599​
600export interface SidebarProjectScopeMenuState {
601 readonly open: boolean;
602 readonly query: string;
604​
605export type SidebarProjectScopeMenuAction =
606 | { readonly type: "query-changed"; readonly query: string }
607 | { readonly type: "open-changed"; readonly open: boolean }
608 | { readonly type: "project-settings-opened" };
609​
610export function reduceSidebarProjectScopeMenuState(
611 state: SidebarProjectScopeMenuState,
612 action: SidebarProjectScopeMenuAction,
613): SidebarProjectScopeMenuState {
614 switch (action.type) {
615 case "query-changed":
616 return { ...state, query: action.query };
617 case "open-changed":
618 return { open: action.open, query: "" };
619 case "project-settings-opened":
620 return { open: false, query: "" };
621 }
623​
624type SettledTimestampInput = Pick<
625 SidebarThreadSummary,
626 "settledAt" | "latestUserMessageAt" | "latestTurn" | "updatedAt"
627>;
628​
629/** The timestamp a settled row sorts and labels by: settledAt when stamped
630 (explicit settles), otherwise last activity — the same candidates
631 threadLastActivityAt feeds the auto-settle window (user message plus all
632 latestTurn stamps), so a thread whose last activity was a turn completion
633 doesn't sort by an older message time. updatedAt is the final net. */
634export function resolveSettledTimestamp(thread: SettledTimestampInput): string | null {
635 const settledAt = firstValidTimestamp(thread.settledAt);
636 if (settledAt !== null) return settledAt;
637 let latest: string | null = null;
638 let latestMs = Number.NEGATIVE_INFINITY;
639 for (const candidate of [
640 thread.latestUserMessageAt,
641 thread.latestTurn?.requestedAt,
642 thread.latestTurn?.startedAt,
643 thread.latestTurn?.completedAt,
644 ]) {
645 if (candidate == null) continue;
646 const parsed = Date.parse(candidate);
647 if (!Number.isNaN(parsed) && parsed > latestMs) {
648 latest = candidate;
649 latestMs = parsed;
650 }
651 }
652 return latest ?? firstValidTimestamp(thread.updatedAt);
654​
655// Settled rows are history, so they order by when the work ENDED, not when
656// the thread was created or last touched.
657export function sortSettledThreadsForSidebar<
658 T extends SettledTimestampInput & { readonly id: string },
659>(threads: readonly T[]): T[] {
660 const timestampMs = (thread: T) => {
661 const timestamp = resolveSettledTimestamp(thread);
662 return timestamp === null ? 0 : Date.parse(timestamp);
663 };
664 return [...threads].toSorted(
665 (left, right) => timestampMs(right) - timestampMs(left) || left.id.localeCompare(right.id),
666 );
668​
669/** The timestamp a working thread's elapsed label counts from: the running
670 turn's start (request time until adoption), falling back to the session's
671 last transition when the turn projection lags behind. Malformed
672 timestamps fall through to the next candidate, not just missing ones. */
673export function resolveWorkingStartedAt(
674 thread: Pick<SidebarThreadSummary, "latestTurn" | "session">,
675): string | null {
676 const turn = thread.latestTurn;
677 if (turn && turn.completedAt === null) {
678 return firstValidTimestamp(turn.startedAt, turn.requestedAt, thread.session?.updatedAt);
679 }
680 return firstValidTimestamp(thread.session?.updatedAt);
682​
683export function formatWorkingDurationLabel(elapsedMs: number): string {
684 const seconds = Number.isFinite(elapsedMs) ? Math.max(0, Math.floor(elapsedMs / 1000)) : 0;
685 if (seconds < 60) return `${seconds}s`;
686 const minutes = Math.floor(seconds / 60);
687 if (minutes < 60) return `${minutes}m`;
688 return `${Math.floor(minutes / 60)}h ${minutes % 60}m`;
690​
691export function resolveThreadStatusPill(input: {
692 thread: ThreadStatusInput;
693}): ThreadStatusPill | null {
694 const { thread } = input;
695​
696 if (thread.hasPendingApprovals) {
697 return {
698 label: "Pending Approval",
699 colorClass: "text-amber-600 dark:text-amber-300/90",
700 dotClass: "bg-amber-500 dark:bg-amber-300/90",
701 pulse: false,
702 };
703 }
704​
705 if (thread.hasPendingUserInput) {
706 return {
707 label: "Awaiting Input",
708 colorClass: "text-indigo-600 dark:text-indigo-300/90",
709 dotClass: "bg-indigo-500 dark:bg-indigo-300/90",
710 pulse: false,
711 };
712 }
713​
714 if (thread.session?.status === "running") {
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.session?.status === "starting") {
724 return {
725 label: "Connecting",
726 colorClass: "text-sky-600 dark:text-sky-300/80",
727 dotClass: "bg-sky-500 dark:bg-sky-300/80",
728 pulse: true,
729 };
730 }
731​
732 // An actionable plan prompt outranks lingering background work: it needs
733 // the user's decision, while liveness merely reports (review finding).
734 const hasPlanReadyPrompt =
735 !thread.hasPendingUserInput &&
736 thread.interactionMode === "plan" &&
737 isLatestTurnSettled(thread.latestTurn, thread.session) &&
738 thread.hasActionableProposedPlan;
739 if (hasPlanReadyPrompt) {
740 return {
741 label: "Plan Ready",
742 colorClass: "text-violet-600 dark:text-violet-300/90",
743 dotClass: "bg-violet-500 dark:bg-violet-300/90",
744 pulse: false,
745 };
746 }
747​
748 // The turn can settle while native background work runs on. Subagent and
749 // workflow fleets read as plain Working; Monitoring is reserved for watch
750 // loops (a parent agent babysitting a PR, tailing checks) with no other
751 // live work. Same recede treatment as Working per inbox-zero.
752 if (thread.backgroundLiveness === "working") {
753 return {
754 label: "Working",
755 colorClass: "text-sky-600 dark:text-sky-300/80",
756 dotClass: "bg-sky-500 dark:bg-sky-300/80",
757 pulse: true,
758 };
759 }
760​
761 if (thread.backgroundLiveness === "monitoring") {
762 return {
763 label: "Monitoring",
764 colorClass: "text-sky-600 dark:text-sky-300/80",
765 dotClass: "bg-sky-500 dark:bg-sky-300/80",
766 pulse: false,
767 };
768 }
769​
770 if (hasUnseenCompletion(thread)) {
771 return {
772 label: "Completed",
773 colorClass: "text-emerald-600 dark:text-emerald-300/90",
774 dotClass: "bg-emerald-500 dark:bg-emerald-300/90",
775 pulse: false,
776 };
777 }
778​
779 return null;
781​
782export function resolveProjectStatusIndicator(
783 statuses: ReadonlyArray<ThreadStatusPill | null>,
784): ThreadStatusPill | null {
785 let highestPriorityStatus: ThreadStatusPill | null = null;
786​
787 for (const status of statuses) {
788 if (status === null) continue;
789 if (
790 highestPriorityStatus === null ||
791 THREAD_STATUS_PRIORITY[status.label] > THREAD_STATUS_PRIORITY[highestPriorityStatus.label]
792 ) {
793 highestPriorityStatus = status;
794 }
795 }
796​
797 return highestPriorityStatus;
799​
800export function getVisibleThreadsForProject<T extends Pick<Thread, "id">>(input: {
801 threads: readonly T[];
802 activeThreadId: T["id"] | undefined;
803 isThreadListExpanded: boolean;
804 previewLimit: number;
805}): {
806 hasHiddenThreads: boolean;
807 visibleThreads: T[];
808 hiddenThreads: T[];
809} {
810 const { activeThreadId, isThreadListExpanded, previewLimit, threads } = input;
811 const hasHiddenThreads = threads.length > previewLimit;
812​
813 if (!hasHiddenThreads || isThreadListExpanded) {
814 return {
815 hasHiddenThreads,
816 hiddenThreads: [],
817 visibleThreads: [...threads],
818 };
819 }
820​
821 const previewThreads = threads.slice(0, previewLimit);
822 if (!activeThreadId || previewThreads.some((thread) => thread.id === activeThreadId)) {
823 return {
824 hasHiddenThreads: true,
825 hiddenThreads: threads.slice(previewLimit),
826 visibleThreads: previewThreads,
827 };
828 }
829​
830 const activeThread = threads.find((thread) => thread.id === activeThreadId);
831 if (!activeThread) {
832 return {
833 hasHiddenThreads: true,
834 hiddenThreads: threads.slice(previewLimit),
835 visibleThreads: previewThreads,
836 };
837 }
838​
839 const visibleThreadIds = new Set([...previewThreads, activeThread].map((thread) => thread.id));
840​
841 return {
842 hasHiddenThreads: true,
843 hiddenThreads: threads.filter((thread) => !visibleThreadIds.has(thread.id)),
844 visibleThreads: threads.filter((thread) => visibleThreadIds.has(thread.id)),
845 };
847​
848export function getFallbackThreadIdAfterDelete<
849 T extends Pick<Thread, "id" | "projectId" | "createdAt" | "updatedAt"> & ThreadSortInput,
850>(input: {
851 threads: readonly T[];
852 deletedThreadId: T["id"];
853 sortOrder: SidebarThreadSortOrder;
854 deletedThreadIds?: ReadonlySet<T["id"]>;
855}): T["id"] | null {
856 const { deletedThreadId, deletedThreadIds, sortOrder, threads } = input;
857 const deletedThread = threads.find((thread) => thread.id === deletedThreadId);
858 if (!deletedThread) {
859 return null;
860 }
861​
862 return (
863 sortThreads(
864 threads.filter(
865 (thread) =>
866 thread.projectId === deletedThread.projectId &&
867 thread.id !== deletedThreadId &&
868 !deletedThreadIds?.has(thread.id),
869 ),
870 sortOrder,
871 )[0]?.id ?? null
872 );
874export function getProjectSortTimestamp(
875 project: SidebarProject,
876 projectThreads: readonly ThreadSortInput[],
877 sortOrder: Exclude<SidebarProjectSortOrder, "manual">,
878): number {
879 if (projectThreads.length > 0) {
880 return projectThreads.reduce(
881 (latest, thread) => Math.max(latest, getThreadSortTimestamp(thread, sortOrder)),
882 Number.NEGATIVE_INFINITY,
883 );
884 }
885​
886 if (sortOrder === "created_at") {
887 return toSortableTimestamp(project.createdAt) ?? Number.NEGATIVE_INFINITY;
888 }
889 return toSortableTimestamp(project.updatedAt ?? project.createdAt) ?? Number.NEGATIVE_INFINITY;
891​
892function sortProjectsByActivity<TProject extends SidebarProject>(
893 projects: readonly TProject[],
894 sortOrder: SidebarProjectSortOrder,
895 getProjectThreads: (project: TProject) => readonly ThreadSortInput[],
896 compareTies: (left: TProject, right: TProject) => number,
897): TProject[] {
898 if (sortOrder === "manual") {
899 return [...projects];
900 }
901​
902 return [...projects].toSorted((left, right) => {
903 const rightTimestamp = getProjectSortTimestamp(right, getProjectThreads(right), sortOrder);
904 const leftTimestamp = getProjectSortTimestamp(left, getProjectThreads(left), sortOrder);
905 const byTimestamp =
906 rightTimestamp === leftTimestamp ? 0 : rightTimestamp > leftTimestamp ? 1 : -1;
907 return byTimestamp || compareTies(left, right);
908 });
910​
911export function sortProjectsForSidebar<
912 TProject extends SidebarProject,
913 TThread extends Pick<Thread, "projectId" | "createdAt" | "updatedAt"> & ThreadSortInput,
914>(
915 projects: readonly TProject[],
916 threads: readonly TThread[],
917 sortOrder: SidebarProjectSortOrder,
918): TProject[] {
919 const threadsByProjectId = new Map<string, TThread[]>();
920 for (const thread of threads) {
921 const existing = threadsByProjectId.get(thread.projectId) ?? [];
922 existing.push(thread);
923 threadsByProjectId.set(thread.projectId, existing);
924 }
925​
926 return sortProjectsByActivity(
927 projects,
928 sortOrder,
929 (project) => threadsByProjectId.get(project.id) ?? [],
930 (left, right) => left.title.localeCompare(right.title) || left.id.localeCompare(right.id),
931 );
933​
934export function sortLogicalProjectsForSidebar<
935 TProject extends LogicalSidebarProject,
936 TThread extends ScopedSidebarThread,
937>(
938 projects: readonly TProject[],
939 threads: readonly TThread[],
940 sortOrder: SidebarProjectSortOrder,
941): TProject[] {
942 const groupKeyByProjectRef = new Map(
943 projects.flatMap((project) =>
944 project.memberProjectRefs.map(
945 (projectRef) =>
946 [`${projectRef.environmentId}\0${projectRef.projectId}`, project.projectKey] as const,
947 ),
948 ),
949 );
950 const threadsByProjectKey = new Map<string, TThread[]>();
951 for (const thread of threads) {
952 if (thread.archivedAt !== null) continue;
953 const projectKey = groupKeyByProjectRef.get(`${thread.environmentId}\0${thread.projectId}`);
954 if (!projectKey) continue;
955 const existing = threadsByProjectKey.get(projectKey);
956 if (existing) {
957 existing.push(thread);
958 } else {
959 threadsByProjectKey.set(projectKey, [thread]);
960 }
961 }
962​
963 return sortProjectsByActivity(
964 projects,
965 sortOrder,
966 (project) => threadsByProjectKey.get(project.projectKey) ?? [],
967 (left, right) =>
968 left.title.localeCompare(right.title) || left.projectKey.localeCompare(right.projectKey),
969 );
971​
972/**
973 * Sorts the cross-environment project collection used by landing surfaces.
974 * Project ids are only unique within an environment, and archived threads
975 * must not make a project appear recently active.
976 */
977export function sortScopedProjectsForSidebar<
978 TProject extends ScopedSidebarProject,
979 TThread extends ScopedSidebarThread,
980>(
981 projects: readonly TProject[],
982 threads: readonly TThread[],
983 sortOrder: SidebarProjectSortOrder,
984): TProject[] {
985 const scopedKey = (environmentId: string, projectId: string) =>
986 `${environmentId}\u0000${projectId}`;
987 const threadsByProject = new Map<string, TThread[]>();
988 for (const thread of threads) {
989 if (thread.archivedAt !== null) {
990 continue;
991 }
992 const key = scopedKey(thread.environmentId, thread.projectId);
993 const existing = threadsByProject.get(key) ?? [];
994 existing.push(thread);
995 threadsByProject.set(key, existing);
996 }
997​
998 return sortProjectsByActivity(
999 projects,
1000 sortOrder,
1001 (project) => threadsByProject.get(scopedKey(project.environmentId, project.id)) ?? [],
1002 (left, right) =>
1003 left.title.localeCompare(right.title) ||
1004 left.environmentId.localeCompare(right.environmentId) ||
1005 left.id.localeCompare(right.id),
1006 );