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

Sidebar.logic.ts

961 lines30.9 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 getThreadSortTimestamp,
7 sortThreads,
8 toSortableTimestamp,
9 type ThreadSortInput,
10} from "../lib/threadSort";
11import type { SidebarThreadSummary, Thread } from "../types";
12import type { ThreadRouteTarget } from "../threadRoutes";
13import { cn } from "../lib/utils";
14import { isLatestTurnSettled } from "../session-logic";
15import { resolveServerBackedAppStageLabel } from "../branding.logic";
16​
17export const THREAD_SELECTION_SAFE_SELECTOR = "[data-thread-item], [data-thread-selection-safe]";
18export const THREAD_JUMP_HINT_SHOW_DELAY_MS = 100;
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 resolveSidebarStageBadgeLabel(input: {
173 primaryServerVersion: string | null | undefined;
174 fallbackStageLabel: string;
175}): string {
176 return resolveServerBackedAppStageLabel(input);
178​
179export function createThreadJumpHintVisibilityController(input: {
180 delayMs: number;
181 onVisibilityChange: (visible: boolean) => void;
182 setTimeoutFn?: typeof globalThis.setTimeout;
183 clearTimeoutFn?: typeof globalThis.clearTimeout;
184}): ThreadJumpHintVisibilityController {
185 const setTimeoutFn = input.setTimeoutFn ?? globalThis.setTimeout;
186 const clearTimeoutFn = input.clearTimeoutFn ?? globalThis.clearTimeout;
187 let isVisible = false;
188 let timeoutId: NodeJS.Timeout | null = null;
189​
190 const clearPendingShow = () => {
191 if (timeoutId === null) {
192 return;
193 }
194 clearTimeoutFn(timeoutId);
195 timeoutId = null;
196 };
197​
198 return {
199 sync: (shouldShow) => {
200 if (!shouldShow) {
201 clearPendingShow();
202 if (isVisible) {
203 isVisible = false;
204 input.onVisibilityChange(false);
205 }
206 return;
207 }
208​
209 if (isVisible || timeoutId !== null) {
210 return;
211 }
212​
213 timeoutId = setTimeoutFn(() => {
214 timeoutId = null;
215 isVisible = true;
216 input.onVisibilityChange(true);
217 }, input.delayMs);
218 },
219 dispose: () => {
220 clearPendingShow();
221 },
222 };
224​
225export function useThreadJumpHintVisibility(): {
226 showThreadJumpHints: boolean;
227 updateThreadJumpHintsVisibility: (shouldShow: boolean) => void;
228} {
229 const [showThreadJumpHints, setShowThreadJumpHints] = React.useState(false);
230 const controllerRef = React.useRef<ThreadJumpHintVisibilityController | null>(null);
231​
232 React.useEffect(() => {
233 const controller = createThreadJumpHintVisibilityController({
234 delayMs: THREAD_JUMP_HINT_SHOW_DELAY_MS,
235 onVisibilityChange: (visible) => {
236 setShowThreadJumpHints(visible);
237 },
238 setTimeoutFn: window.setTimeout.bind(window),
239 clearTimeoutFn: window.clearTimeout.bind(window),
240 });
241 controllerRef.current = controller;
242​
243 return () => {
244 controller.dispose();
245 controllerRef.current = null;
246 };
247 }, []);
248​
249 const updateThreadJumpHintsVisibility = React.useCallback((shouldShow: boolean) => {
250 controllerRef.current?.sync(shouldShow);
251 }, []);
252​
253 return {
254 showThreadJumpHints,
255 updateThreadJumpHintsVisibility,
256 };
258​
259export function hasUnseenCompletion(thread: ThreadStatusInput): boolean {
260 if (!thread.latestTurn?.completedAt) return false;
261 const completedAt = Date.parse(thread.latestTurn.completedAt);
262 if (Number.isNaN(completedAt)) return false;
263 if (!thread.lastVisitedAt) return false;
264​
265 const lastVisitedAt = Date.parse(thread.lastVisitedAt);
266 if (Number.isNaN(lastVisitedAt)) return true;
267 return completedAt > lastVisitedAt;
269​
270export function shouldClearThreadSelectionOnMouseDown(target: HTMLElement | null): boolean {
271 if (target === null) return true;
272 return !target.closest(THREAD_SELECTION_SAFE_SELECTOR);
274​
275// A double-click dispatches two `click` events before `dblclick`: the first has
276// `detail === 1`, the second `detail === 2`. The second click must not run the
277// row's single-click navigation, otherwise double-click-to-rename would also
278// navigate. `MouseEvent.detail` is 0 for synthetic/keyboard activations, which
279// still count as a normal single activation.
280export function isTrailingDoubleClick(detail: number): boolean {
281 return detail > 1;
283​
284function nodeClosest(node: object | null, selector: string): unknown {
285 if (node === null || !("closest" in node) || typeof node.closest !== "function") return null;
286 return node.closest(selector);
288​
289/** Clicks on a nested link keep the link's meaning. The row must not treat them as multi-select. */
290export function isSidebarNestedLinkClick(target: EventTarget | null): boolean {
291 if (target == null || typeof target !== "object") return false;
292 if (nodeClosest(target, "a[href]") !== null) return true;
293 const parent =
294 "parentElement" in target &&
295 target.parentElement !== null &&
296 typeof target.parentElement === "object"
297 ? target.parentElement
298 : null;
299 return nodeClosest(parent, "a[href]") !== null;
301​
302// Shift+click on the new thread button creates directly in the current
303// project, skipping the command palette's project picker. With a single
304// project there is nothing to pick, so a plain click already creates
305// immediately and the modifier changes nothing.
306export function shouldCreateNewThreadInCurrentProject(
307 shiftKey: boolean,
308 projectGroupCount: number,
309): boolean {
310 return shiftKey || projectGroupCount <= 1;
312​
313export function orderItemsByPreferredIds<TItem, TId>(input: {
314 items: readonly TItem[];
315 preferredIds: readonly TId[];
316 getId: (item: TItem) => TId;
317 getPreferenceIds?: (item: TItem) => readonly TId[];
318}): TItem[] {
319 const { getId, getPreferenceIds, items, preferredIds } = input;
320 if (preferredIds.length === 0) {
321 return [...items];
322 }
323​
324 const indexesByPreferenceId = new Map<TId, number[]>();
325 for (const [index, item] of items.entries()) {
326 const preferenceIds = getPreferenceIds?.(item) ?? [getId(item)];
327 for (const preferenceId of new Set(preferenceIds)) {
328 const indexes = indexesByPreferenceId.get(preferenceId);
329 if (indexes) {
330 indexes.push(index);
331 } else {
332 indexesByPreferenceId.set(preferenceId, [index]);
333 }
334 }
335 }
336​
337 const emittedIndexes = new Set<number>();
338 const ordered = preferredIds.flatMap((id) => {
339 const index = indexesByPreferenceId
340 .get(id)
341 ?.find((candidate) => !emittedIndexes.has(candidate));
342 if (index === undefined) {
343 return [];
344 }
345 emittedIndexes.add(index);
346 return [items[index]!];
347 });
348 const remaining = items.filter((_, index) => !emittedIndexes.has(index));
349 return [...ordered, ...remaining];
351​
352export function getVisibleSidebarThreadIds<TThreadId>(
353 renderedProjects: readonly {
354 shouldShowThreadPanel?: boolean;
355 renderedThreadIds: readonly TThreadId[];
356 }[],
357): TThreadId[] {
358 return renderedProjects.flatMap((renderedProject) =>
359 renderedProject.shouldShowThreadPanel === false ? [] : renderedProject.renderedThreadIds,
360 );
362​
363export function getSidebarThreadIdsToPrewarm<TThreadId>(
364 visibleThreadIds: readonly TThreadId[],
365 limit = SIDEBAR_THREAD_PREWARM_LIMIT,
366): TThreadId[] {
367 return visibleThreadIds.slice(0, Math.max(0, limit));
369​
370export function resolveAdjacentThreadId<T>(input: {
371 threadIds: readonly T[];
372 currentThreadId: T | null;
373 direction: ThreadTraversalDirection;
374}): T | null {
375 const { currentThreadId, direction, threadIds } = input;
376​
377 if (threadIds.length === 0) {
378 return null;
379 }
380​
381 if (currentThreadId === null) {
382 return direction === "previous" ? (threadIds.at(-1) ?? null) : (threadIds[0] ?? null);
383 }
384​
385 const currentIndex = threadIds.indexOf(currentThreadId);
386 if (currentIndex === -1) {
387 return null;
388 }
389​
390 if (direction === "previous") {
391 return currentIndex > 0 ? (threadIds[currentIndex - 1] ?? null) : null;
392 }
393​
394 return currentIndex < threadIds.length - 1 ? (threadIds[currentIndex + 1] ?? null) : null;
396​
397export function shouldNavigateAfterProjectRemoval(input: {
398 routeTarget: ThreadRouteTarget | null;
399 projectThreads: readonly {
400 environmentId: string;
401 id: string;
402 }[];
403 projectDraftId: string | null;
404}): boolean {
405 const { projectDraftId, projectThreads, routeTarget } = input;
406 if (routeTarget?.kind === "draft") {
407 return projectDraftId === routeTarget.draftId;
408 }
409 if (routeTarget?.kind !== "server") {
410 return false;
411 }
412 return projectThreads.some(
413 (thread) =>
414 thread.environmentId === routeTarget.threadRef.environmentId &&
415 thread.id === routeTarget.threadRef.threadId,
416 );
418​
419export function isContextMenuPointerDown(input: {
420 button: number;
421 ctrlKey: boolean;
422 isMac: boolean;
423}): boolean {
424 if (input.button === 2) return true;
425 return input.isMac && input.button === 0 && input.ctrlKey;
427​
428export function resolveThreadRowClassName(input: {
429 isActive: boolean;
430 isSelected: boolean;
431}): string {
432 const baseClassName =
433 "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";
434​
435 if (input.isSelected && input.isActive) {
436 return cn(
437 baseClassName,
438 "bg-sidebar-row-active text-sidebar-foreground font-medium hover:bg-sidebar-row-active hover:text-sidebar-foreground",
439 );
440 }
441​
442 if (input.isSelected) {
443 return cn(
444 baseClassName,
445 "bg-sidebar-row-selected text-sidebar-foreground hover:bg-sidebar-row-active hover:text-sidebar-foreground",
446 );
447 }
448​
449 if (input.isActive) {
450 return cn(
451 baseClassName,
452 "bg-sidebar-row-active text-sidebar-foreground font-medium hover:bg-sidebar-row-active hover:text-sidebar-foreground",
453 );
454 }
455​
456 return cn(
457 baseClassName,
458 "text-sidebar-muted-foreground/80 hover:bg-sidebar-row-hover hover:text-sidebar-foreground",
459 );
461​
462// ── Sidebar thread status model ─────────────────────────────────────
463// Five visual states, three colors: color is reserved for "act now"
464// (approval), "in motion" (working), and "broken" (failed). Ready is the
465// unlabeled resting state — the agent stopped and is waiting on the user,
466// whether it finished, asked a question, or proposed a plan.
467// Unread completion is tracked separately: it describes whether a ready
468// thread needs attention, not what the thread is currently doing.
469export type SidebarThreadStatus =
470 | "approval"
471 | "input"
472 | "working"
473 | "monitoring"
474 | "failed"
475 | "ready";
476​
477type SidebarThreadStatusInput = Pick<
478 SidebarThreadSummary,
479 "hasPendingApprovals" | "hasPendingUserInput" | "session" | "backgroundLiveness"
480>;
481​
482export function resolveSidebarThreadStatus(thread: SidebarThreadStatusInput): SidebarThreadStatus {
483 if (thread.hasPendingApprovals) {
484 return "approval";
485 }
486 if (thread.hasPendingUserInput) {
487 return "input";
488 }
489 if (thread.session?.status === "running" || thread.session?.status === "starting") {
490 return "working";
491 }
492 // A failed session outranks lingering background liveness: the user must
493 // see the failure, not a stale Working (review finding).
494 if (thread.session?.status === "error") {
495 return "failed";
496 }
497 // Background work outlives the turn: fleets read as working; monitoring
498 // only when watch loops are the sole live work.
499 if (thread.backgroundLiveness === "working") {
500 return "working";
501 }
502 if (thread.backgroundLiveness === "monitoring") {
503 return "monitoring";
504 }
505 return "ready";
507​
508/** NaN-safe Date.parse for sort comparators: a malformed timestamp must not
509 poison the whole ordering, so it sinks to the epoch instead. */
510export function parseTimestampMs(isoDate: string): number {
511 const parsed = Date.parse(isoDate);
512 return Number.isNaN(parsed) ? 0 : parsed;
514​
515/** First VALID timestamp wins: `a ?? b` falls through on null, but a present-
516 yet-malformed string must also fall through to the next candidate rather
517 than sink the row to the epoch. */
518export function firstValidTimestampMs(
519 ...candidates: ReadonlyArray<string | null | undefined>
520): number {
521 for (const candidate of candidates) {
522 if (candidate == null) continue;
523 const parsed = Date.parse(candidate);
524 if (!Number.isNaN(parsed)) return parsed;
525 }
526 return 0;
528​
529/** String twin of firstValidTimestampMs for callers that need the ISO string
530 (display labels, tick anchors) rather than epoch ms. */
531export function firstValidTimestamp(
532 ...candidates: ReadonlyArray<string | null | undefined>
533): string | null {
534 for (const candidate of candidates) {
535 if (candidate == null) continue;
536 if (!Number.isNaN(Date.parse(candidate))) return candidate;
537 }
538 return null;
540​
541// Sidebar sort: static creation order, newest thread on top. Activity NEVER
542// reorders the list — a row holds its position from open until settled, so
543// the screen only moves at lifecycle transitions. Status (including pending
544// approval) is carried by each card's edge strip, not by position.
545export function sortThreadsForSidebar<
546 T extends { readonly id: string; readonly createdAt: string },
547>(threads: readonly T[]): T[] {
548 return [...threads].toSorted(
549 (left, right) =>
550 parseTimestampMs(right.createdAt) - parseTimestampMs(left.createdAt) ||
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​
578type SettledTimestampInput = Pick<
579 SidebarThreadSummary,
580 "settledAt" | "latestUserMessageAt" | "latestTurn" | "updatedAt"
581>;
582​
583/** The timestamp a settled row sorts and labels by: settledAt when stamped
584 (explicit settles), otherwise last activity — the same candidates
585 threadLastActivityAt feeds the auto-settle window (user message plus all
586 latestTurn stamps), so a thread whose last activity was a turn completion
587 doesn't sort by an older message time. updatedAt is the final net. */
588export function resolveSettledTimestamp(thread: SettledTimestampInput): string | null {
589 const settledAt = firstValidTimestamp(thread.settledAt);
590 if (settledAt !== null) return settledAt;
591 let latest: string | null = null;
592 let latestMs = Number.NEGATIVE_INFINITY;
593 for (const candidate of [
594 thread.latestUserMessageAt,
595 thread.latestTurn?.requestedAt,
596 thread.latestTurn?.startedAt,
597 thread.latestTurn?.completedAt,
598 ]) {
599 if (candidate == null) continue;
600 const parsed = Date.parse(candidate);
601 if (!Number.isNaN(parsed) && parsed > latestMs) {
602 latest = candidate;
603 latestMs = parsed;
604 }
605 }
606 return latest ?? firstValidTimestamp(thread.updatedAt);
608​
609// Settled rows are history, so they order by when the work ENDED, not when
610// the thread was created or last touched.
611export function sortSettledThreadsForSidebar<
612 T extends SettledTimestampInput & { readonly id: string },
613>(threads: readonly T[]): T[] {
614 const timestampMs = (thread: T) => {
615 const timestamp = resolveSettledTimestamp(thread);
616 return timestamp === null ? 0 : Date.parse(timestamp);
617 };
618 return [...threads].toSorted(
619 (left, right) => timestampMs(right) - timestampMs(left) || left.id.localeCompare(right.id),
620 );
622​
623/** The timestamp a working thread's elapsed label counts from: the running
624 turn's start (request time until adoption), falling back to the session's
625 last transition when the turn projection lags behind. Malformed
626 timestamps fall through to the next candidate, not just missing ones. */
627export function resolveWorkingStartedAt(
628 thread: Pick<SidebarThreadSummary, "latestTurn" | "session">,
629): string | null {
630 const turn = thread.latestTurn;
631 if (turn && turn.completedAt === null) {
632 return firstValidTimestamp(turn.startedAt, turn.requestedAt, thread.session?.updatedAt);
633 }
634 return firstValidTimestamp(thread.session?.updatedAt);
636​
637export function formatWorkingDurationLabel(elapsedMs: number): string {
638 const seconds = Number.isFinite(elapsedMs) ? Math.max(0, Math.floor(elapsedMs / 1000)) : 0;
639 if (seconds < 60) return `${seconds}s`;
640 const minutes = Math.floor(seconds / 60);
641 if (minutes < 60) return `${minutes}m`;
642 return `${Math.floor(minutes / 60)}h ${minutes % 60}m`;
644​
645export function resolveThreadStatusPill(input: {
646 thread: ThreadStatusInput;
647}): ThreadStatusPill | null {
648 const { thread } = input;
649​
650 if (thread.hasPendingApprovals) {
651 return {
652 label: "Pending Approval",
653 colorClass: "text-amber-600 dark:text-amber-300/90",
654 dotClass: "bg-amber-500 dark:bg-amber-300/90",
655 pulse: false,
656 };
657 }
658​
659 if (thread.hasPendingUserInput) {
660 return {
661 label: "Awaiting Input",
662 colorClass: "text-indigo-600 dark:text-indigo-300/90",
663 dotClass: "bg-indigo-500 dark:bg-indigo-300/90",
664 pulse: false,
665 };
666 }
667​
668 if (thread.session?.status === "running") {
669 return {
670 label: "Working",
671 colorClass: "text-sky-600 dark:text-sky-300/80",
672 dotClass: "bg-sky-500 dark:bg-sky-300/80",
673 pulse: true,
674 };
675 }
676​
677 if (thread.session?.status === "starting") {
678 return {
679 label: "Connecting",
680 colorClass: "text-sky-600 dark:text-sky-300/80",
681 dotClass: "bg-sky-500 dark:bg-sky-300/80",
682 pulse: true,
683 };
684 }
685​
686 // An actionable plan prompt outranks lingering background work: it needs
687 // the user's decision, while liveness merely reports (review finding).
688 const hasPlanReadyPrompt =
689 !thread.hasPendingUserInput &&
690 thread.interactionMode === "plan" &&
691 isLatestTurnSettled(thread.latestTurn, thread.session) &&
692 thread.hasActionableProposedPlan;
693 if (hasPlanReadyPrompt) {
694 return {
695 label: "Plan Ready",
696 colorClass: "text-violet-600 dark:text-violet-300/90",
697 dotClass: "bg-violet-500 dark:bg-violet-300/90",
698 pulse: false,
699 };
700 }
701​
702 // The turn can settle while native background work runs on. Subagent and
703 // workflow fleets read as plain Working; Monitoring is reserved for watch
704 // loops (a parent agent babysitting a PR, tailing checks) with no other
705 // live work. Same recede treatment as Working per inbox-zero.
706 if (thread.backgroundLiveness === "working") {
707 return {
708 label: "Working",
709 colorClass: "text-sky-600 dark:text-sky-300/80",
710 dotClass: "bg-sky-500 dark:bg-sky-300/80",
711 pulse: true,
712 };
713 }
714​
715 if (thread.backgroundLiveness === "monitoring") {
716 return {
717 label: "Monitoring",
718 colorClass: "text-sky-600 dark:text-sky-300/80",
719 dotClass: "bg-sky-500 dark:bg-sky-300/80",
720 pulse: false,
721 };
722 }
723​
724 if (hasUnseenCompletion(thread)) {
725 return {
726 label: "Completed",
727 colorClass: "text-emerald-600 dark:text-emerald-300/90",
728 dotClass: "bg-emerald-500 dark:bg-emerald-300/90",
729 pulse: false,
730 };
731 }
732​
733 return null;
735​
736export function resolveProjectStatusIndicator(
737 statuses: ReadonlyArray<ThreadStatusPill | null>,
738): ThreadStatusPill | null {
739 let highestPriorityStatus: ThreadStatusPill | null = null;
740​
741 for (const status of statuses) {
742 if (status === null) continue;
743 if (
744 highestPriorityStatus === null ||
745 THREAD_STATUS_PRIORITY[status.label] > THREAD_STATUS_PRIORITY[highestPriorityStatus.label]
746 ) {
747 highestPriorityStatus = status;
748 }
749 }
750​
751 return highestPriorityStatus;
753​
754export function getVisibleThreadsForProject<T extends Pick<Thread, "id">>(input: {
755 threads: readonly T[];
756 activeThreadId: T["id"] | undefined;
757 isThreadListExpanded: boolean;
758 previewLimit: number;
759}): {
760 hasHiddenThreads: boolean;
761 visibleThreads: T[];
762 hiddenThreads: T[];
763} {
764 const { activeThreadId, isThreadListExpanded, previewLimit, threads } = input;
765 const hasHiddenThreads = threads.length > previewLimit;
766​
767 if (!hasHiddenThreads || isThreadListExpanded) {
768 return {
769 hasHiddenThreads,
770 hiddenThreads: [],
771 visibleThreads: [...threads],
772 };
773 }
774​
775 const previewThreads = threads.slice(0, previewLimit);
776 if (!activeThreadId || previewThreads.some((thread) => thread.id === activeThreadId)) {
777 return {
778 hasHiddenThreads: true,
779 hiddenThreads: threads.slice(previewLimit),
780 visibleThreads: previewThreads,
781 };
782 }
783​
784 const activeThread = threads.find((thread) => thread.id === activeThreadId);
785 if (!activeThread) {
786 return {
787 hasHiddenThreads: true,
788 hiddenThreads: threads.slice(previewLimit),
789 visibleThreads: previewThreads,
790 };
791 }
792​
793 const visibleThreadIds = new Set([...previewThreads, activeThread].map((thread) => thread.id));
794​
795 return {
796 hasHiddenThreads: true,
797 hiddenThreads: threads.filter((thread) => !visibleThreadIds.has(thread.id)),
798 visibleThreads: threads.filter((thread) => visibleThreadIds.has(thread.id)),
799 };
801​
802export function getFallbackThreadIdAfterDelete<
803 T extends Pick<Thread, "id" | "projectId" | "createdAt" | "updatedAt"> & ThreadSortInput,
804>(input: {
805 threads: readonly T[];
806 deletedThreadId: T["id"];
807 sortOrder: SidebarThreadSortOrder;
808 deletedThreadIds?: ReadonlySet<T["id"]>;
809}): T["id"] | null {
810 const { deletedThreadId, deletedThreadIds, sortOrder, threads } = input;
811 const deletedThread = threads.find((thread) => thread.id === deletedThreadId);
812 if (!deletedThread) {
813 return null;
814 }
815​
816 return (
817 sortThreads(
818 threads.filter(
819 (thread) =>
820 thread.projectId === deletedThread.projectId &&
821 thread.id !== deletedThreadId &&
822 !deletedThreadIds?.has(thread.id),
823 ),
824 sortOrder,
825 )[0]?.id ?? null
826 );
828export function getProjectSortTimestamp(
829 project: SidebarProject,
830 projectThreads: readonly ThreadSortInput[],
831 sortOrder: Exclude<SidebarProjectSortOrder, "manual">,
832): number {
833 if (projectThreads.length > 0) {
834 return projectThreads.reduce(
835 (latest, thread) => Math.max(latest, getThreadSortTimestamp(thread, sortOrder)),
836 Number.NEGATIVE_INFINITY,
837 );
838 }
839​
840 if (sortOrder === "created_at") {
841 return toSortableTimestamp(project.createdAt) ?? Number.NEGATIVE_INFINITY;
842 }
843 return toSortableTimestamp(project.updatedAt ?? project.createdAt) ?? Number.NEGATIVE_INFINITY;
845​
846function sortProjectsByActivity<TProject extends SidebarProject>(
847 projects: readonly TProject[],
848 sortOrder: SidebarProjectSortOrder,
849 getProjectThreads: (project: TProject) => readonly ThreadSortInput[],
850 compareTies: (left: TProject, right: TProject) => number,
851): TProject[] {
852 if (sortOrder === "manual") {
853 return [...projects];
854 }
855​
856 return [...projects].toSorted((left, right) => {
857 const rightTimestamp = getProjectSortTimestamp(right, getProjectThreads(right), sortOrder);
858 const leftTimestamp = getProjectSortTimestamp(left, getProjectThreads(left), sortOrder);
859 const byTimestamp =
860 rightTimestamp === leftTimestamp ? 0 : rightTimestamp > leftTimestamp ? 1 : -1;
861 return byTimestamp || compareTies(left, right);
862 });
864​
865export function sortProjectsForSidebar<
866 TProject extends SidebarProject,
867 TThread extends Pick<Thread, "projectId" | "createdAt" | "updatedAt"> & ThreadSortInput,
868>(
869 projects: readonly TProject[],
870 threads: readonly TThread[],
871 sortOrder: SidebarProjectSortOrder,
872): TProject[] {
873 const threadsByProjectId = new Map<string, TThread[]>();
874 for (const thread of threads) {
875 const existing = threadsByProjectId.get(thread.projectId) ?? [];
876 existing.push(thread);
877 threadsByProjectId.set(thread.projectId, existing);
878 }
879​
880 return sortProjectsByActivity(
881 projects,
882 sortOrder,
883 (project) => threadsByProjectId.get(project.id) ?? [],
884 (left, right) => left.title.localeCompare(right.title) || left.id.localeCompare(right.id),
885 );
887​
888export function sortLogicalProjectsForSidebar<
889 TProject extends LogicalSidebarProject,
890 TThread extends ScopedSidebarThread,
891>(
892 projects: readonly TProject[],
893 threads: readonly TThread[],
894 sortOrder: SidebarProjectSortOrder,
895): TProject[] {
896 const groupKeyByProjectRef = new Map(
897 projects.flatMap((project) =>
898 project.memberProjectRefs.map(
899 (projectRef) =>
900 [`${projectRef.environmentId}\0${projectRef.projectId}`, project.projectKey] as const,
901 ),
902 ),
903 );
904 const threadsByProjectKey = new Map<string, TThread[]>();
905 for (const thread of threads) {
906 if (thread.archivedAt !== null) continue;
907 const projectKey = groupKeyByProjectRef.get(`${thread.environmentId}\0${thread.projectId}`);
908 if (!projectKey) continue;
909 const existing = threadsByProjectKey.get(projectKey);
910 if (existing) {
911 existing.push(thread);
912 } else {
913 threadsByProjectKey.set(projectKey, [thread]);
914 }
915 }
916​
917 return sortProjectsByActivity(
918 projects,
919 sortOrder,
920 (project) => threadsByProjectKey.get(project.projectKey) ?? [],
921 (left, right) =>
922 left.title.localeCompare(right.title) || left.projectKey.localeCompare(right.projectKey),
923 );
925​
926/**
927 * Sorts the cross-environment project collection used by landing surfaces.
928 * Project ids are only unique within an environment, and archived threads
929 * must not make a project appear recently active.
930 */
931export function sortScopedProjectsForSidebar<
932 TProject extends ScopedSidebarProject,
933 TThread extends ScopedSidebarThread,
934>(
935 projects: readonly TProject[],
936 threads: readonly TThread[],
937 sortOrder: SidebarProjectSortOrder,
938): TProject[] {
939 const scopedKey = (environmentId: string, projectId: string) =>
940 `${environmentId}\u0000${projectId}`;
941 const threadsByProject = new Map<string, TThread[]>();
942 for (const thread of threads) {
943 if (thread.archivedAt !== null) {
944 continue;
945 }
946 const key = scopedKey(thread.environmentId, thread.projectId);
947 const existing = threadsByProject.get(key) ?? [];
948 existing.push(thread);
949 threadsByProject.set(key, existing);
950 }
951​
952 return sortProjectsByActivity(
953 projects,
954 sortOrder,
955 (project) => threadsByProject.get(scopedKey(project.environmentId, project.id)) ?? [],
956 (left, right) =>
957 left.title.localeCompare(right.title) ||
958 left.environmentId.localeCompare(right.environmentId) ||
959 left.id.localeCompare(right.id),
960 );