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

Sidebar.logic.ts

995 lines31.0 KB

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