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

Sidebar.logic.ts

1,086 lines34.6 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 { isLatestRunSettled } 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") archivedThreadKeys.push(entry.threadKey);
81 if (result._tag === "Success") continue;
82 const failure = result as Extract<TResult, { readonly _tag: "Failure" }>;
83 if (didArchive) {
84 followupFailures.push(failure);
85 continue;
86 }
87 return { archivedThreadKeys, mutationFailure: failure, followupFailures };
88 }
89​
90 return { archivedThreadKeys, mutationFailure: null, followupFailures };
92​
93export function buildMultiSelectThreadContextMenuItems(input: {
94 count: number;
95 hasRunningThread: boolean;
96}): readonly ContextMenuItem<"mark-unread" | "archive" | "delete">[] {
97 return [
98 { id: "mark-unread", label: `Mark unread (${input.count})` },
99 {
100 id: "archive",
101 label: `Archive (${input.count})`,
102 disabled: input.hasRunningThread,
103 },
104 { id: "delete", label: `Delete (${input.count})`, destructive: true },
105 ];
107​
108export function isSidebarSubagentThread(thread: Pick<SidebarThreadSummary, "lineage">): boolean {
109 return thread.lineage.relationshipToParent === "subagent";
111​
112export function filterSidebarV2VisibleThreads<
113 T extends Pick<SidebarThreadSummary, "archivedAt" | "lineage"> & {
114 environmentId: string;
115 projectId: string;
116 },
117>(threads: readonly T[], scopedProjectKeys: ReadonlySet<string> | null): T[] {
118 return threads.filter(
119 (thread) =>
120 thread.archivedAt === null &&
121 !isSidebarSubagentThread(thread) &&
122 (scopedProjectKeys === null ||
123 scopedProjectKeys.has(`${thread.environmentId}:${thread.projectId}`)),
124 );
126​
127export function getSidebarForkParentThreadId(
128 thread: Pick<SidebarThreadSummary, "forkedFrom" | "lineage">,
129) {
130 if (thread.lineage.relationshipToParent !== "fork") {
131 return null;
132 }
133 return thread.forkedFrom?.type === "run"
134 ? thread.forkedFrom.threadId
135 : thread.lineage.parentThreadId;
137​
138export function buildBulkTitleRegenerationContextMenuItem(input: {
139 supportedCount: number;
140 actionableCount: number;
141}): ContextMenuItem<"regenerate-title"> | null {
142 if (input.supportedCount === 0) return null;
143 if (input.actionableCount === 0) {
144 return {
145 id: "regenerate-title",
146 label: `Regenerating… (${input.supportedCount})`,
147 disabled: true,
148 };
149 }
150 return {
151 id: "regenerate-title",
152 label: `Regenerate titles (${input.actionableCount})`,
153 };
155​
156export interface ThreadStatusPill {
157 label:
158 | "Working"
159 | "Connecting"
160 | "Completed"
161 | "Pending Approval"
162 | "Awaiting Input"
163 | "Waiting"
164 | "Plan Ready";
165 colorClass: string;
166 dotClass: string;
167 pulse: boolean;
169​
170const THREAD_STATUS_PRIORITY: Record<ThreadStatusPill["label"], number> = {
171 "Pending Approval": 5,
172 "Awaiting Input": 4,
173 Working: 3,
174 Connecting: 3,
175 Waiting: 2.5,
176 "Plan Ready": 2,
177 Completed: 1,
178};
179​
180type ThreadStatusInput = Pick<
181 SidebarThreadSummary,
182 | "hasActionableProposedPlan"
183 | "hasPendingApprovals"
184 | "hasPendingUserInput"
185 | "interactionMode"
186 | "latestRun"
187 | "runtime"
188> & {
189 lastVisitedAt?: string | null | undefined;
190 pendingBackgroundTasks?: SidebarThreadSummary["pendingBackgroundTasks"] | undefined;
191};
192​
193export interface ThreadJumpHintVisibilityController {
194 sync: (shouldShow: boolean) => void;
195 dispose: () => void;
197​
198export function resolveSidebarStageBadgeLabel(input: {
199 primaryServerVersion: string | null | undefined;
200 fallbackStageLabel: string;
201}): string {
202 return resolveServerBackedAppStageLabel(input);
204​
205export function createThreadJumpHintVisibilityController(input: {
206 delayMs: number;
207 onVisibilityChange: (visible: boolean) => void;
208 setTimeoutFn?: typeof globalThis.setTimeout;
209 clearTimeoutFn?: typeof globalThis.clearTimeout;
210}): ThreadJumpHintVisibilityController {
211 const setTimeoutFn = input.setTimeoutFn ?? globalThis.setTimeout;
212 const clearTimeoutFn = input.clearTimeoutFn ?? globalThis.clearTimeout;
213 let isVisible = false;
214 let timeoutId: NodeJS.Timeout | null = null;
215​
216 const clearPendingShow = () => {
217 if (timeoutId === null) {
218 return;
219 }
220 clearTimeoutFn(timeoutId);
221 timeoutId = null;
222 };
223​
224 return {
225 sync: (shouldShow) => {
226 if (!shouldShow) {
227 clearPendingShow();
228 if (isVisible) {
229 isVisible = false;
230 input.onVisibilityChange(false);
231 }
232 return;
233 }
234​
235 if (isVisible || timeoutId !== null) {
236 return;
237 }
238​
239 timeoutId = setTimeoutFn(() => {
240 timeoutId = null;
241 isVisible = true;
242 input.onVisibilityChange(true);
243 }, input.delayMs);
244 },
245 dispose: () => {
246 clearPendingShow();
247 },
248 };
250​
251export function useThreadJumpHintVisibility(): {
252 showThreadJumpHints: boolean;
253 updateThreadJumpHintsVisibility: (shouldShow: boolean) => void;
254} {
255 const [showThreadJumpHints, setShowThreadJumpHints] = React.useState(false);
256 const controllerRef = React.useRef<ThreadJumpHintVisibilityController | null>(null);
257​
258 React.useEffect(() => {
259 const controller = createThreadJumpHintVisibilityController({
260 delayMs: THREAD_JUMP_HINT_SHOW_DELAY_MS,
261 onVisibilityChange: (visible) => {
262 setShowThreadJumpHints(visible);
263 },
264 setTimeoutFn: window.setTimeout.bind(window),
265 clearTimeoutFn: window.clearTimeout.bind(window),
266 });
267 controllerRef.current = controller;
268​
269 return () => {
270 controller.dispose();
271 controllerRef.current = null;
272 };
273 }, []);
274​
275 const updateThreadJumpHintsVisibility = React.useCallback((shouldShow: boolean) => {
276 controllerRef.current?.sync(shouldShow);
277 }, []);
278​
279 return {
280 showThreadJumpHints,
281 updateThreadJumpHintsVisibility,
282 };
284​
285/**
286 * Effective visited watermark for a thread. Servers with visited tracking
287 * project `lastVisitedAt` on the shell and are authoritative — that value is
288 * shared across every device connected to the environment. Pre-tracking
289 * servers omit the field, and the browser's locally persisted watermark keeps
290 * working as before.
291 */
292export function resolveThreadLastVisitedAt(
293 serverLastVisitedAt: string | null | undefined,
294 localLastVisitedAt: string | undefined,
295): string | undefined {
296 // When the server tracks visits it is authoritative — including explicit
297 // rewinds from mark-unread, which a newer browser-local watermark must not
298 // mask. The local value only carries servers without visited tracking.
299 if (serverLastVisitedAt === undefined) return localLastVisitedAt;
300 return serverLastVisitedAt ?? undefined;
302​
303export function hasUnseenCompletion(thread: ThreadStatusInput): boolean {
304 if (!thread.latestRun?.completedAt) return false;
305 const completedAt = Date.parse(thread.latestRun.completedAt);
306 if (Number.isNaN(completedAt)) return false;
307 if (!thread.lastVisitedAt) return false;
308​
309 const lastVisitedAt = Date.parse(thread.lastVisitedAt);
310 if (Number.isNaN(lastVisitedAt)) return true;
311 return completedAt > lastVisitedAt;
313​
314export function shouldClearThreadSelectionOnMouseDown(target: HTMLElement | null): boolean {
315 if (target === null) return true;
316 return !target.closest(THREAD_SELECTION_SAFE_SELECTOR);
318​
319// A double-click dispatches two `click` events before `dblclick`: the first has
320// `detail === 1`, the second `detail === 2`. The second click must not run the
321// row's single-click navigation, otherwise double-click-to-rename would also
322// navigate. `MouseEvent.detail` is 0 for synthetic/keyboard activations, which
323// still count as a normal single activation.
324export function isTrailingDoubleClick(detail: number): boolean {
325 return detail > 1;
327​
328function nodeClosest(node: object | null, selector: string): unknown {
329 if (node === null || !("closest" in node) || typeof node.closest !== "function") return null;
330 return node.closest(selector);
332​
333/** Clicks on a nested link keep the link's meaning. The row must not treat them as multi-select. */
334export function isSidebarNestedLinkClick(target: EventTarget | null): boolean {
335 if (target == null || typeof target !== "object") return false;
336 if (nodeClosest(target, "a[href]") !== null) return true;
337 const parent =
338 "parentElement" in target &&
339 target.parentElement !== null &&
340 typeof target.parentElement === "object"
341 ? target.parentElement
342 : null;
343 return nodeClosest(parent, "a[href]") !== null;
345​
346// Shift+click on the new thread button creates directly in the current
347// project, skipping the command palette's project picker. With a single
348// project there is nothing to pick, so a plain click already creates
349// immediately and the modifier changes nothing.
350export function shouldCreateNewThreadInCurrentProject(
351 shiftKey: boolean,
352 projectGroupCount: number,
353): boolean {
354 return shiftKey || projectGroupCount <= 1;
356​
357export function orderItemsByPreferredIds<TItem, TId>(input: {
358 items: readonly TItem[];
359 preferredIds: readonly TId[];
360 getId: (item: TItem) => TId;
361 getPreferenceIds?: (item: TItem) => readonly TId[];
362}): TItem[] {
363 const { getId, getPreferenceIds, items, preferredIds } = input;
364 if (preferredIds.length === 0) {
365 return [...items];
366 }
367​
368 const indexesByPreferenceId = new Map<TId, number[]>();
369 for (const [index, item] of items.entries()) {
370 const preferenceIds = getPreferenceIds?.(item) ?? [getId(item)];
371 for (const preferenceId of new Set(preferenceIds)) {
372 const indexes = indexesByPreferenceId.get(preferenceId);
373 if (indexes) {
374 indexes.push(index);
375 } else {
376 indexesByPreferenceId.set(preferenceId, [index]);
377 }
378 }
379 }
380​
381 const emittedIndexes = new Set<number>();
382 const ordered = preferredIds.flatMap((id) => {
383 const index = indexesByPreferenceId
384 .get(id)
385 ?.find((candidate) => !emittedIndexes.has(candidate));
386 if (index === undefined) {
387 return [];
388 }
389 emittedIndexes.add(index);
390 return [items[index]!];
391 });
392 const remaining = items.filter((_, index) => !emittedIndexes.has(index));
393 return [...ordered, ...remaining];
395​
396export function getVisibleSidebarThreadIds<TThreadId>(
397 renderedProjects: readonly {
398 shouldShowThreadPanel?: boolean;
399 renderedThreadIds: readonly TThreadId[];
400 }[],
401): TThreadId[] {
402 return renderedProjects.flatMap((renderedProject) =>
403 renderedProject.shouldShowThreadPanel === false ? [] : renderedProject.renderedThreadIds,
404 );
406​
407export function getSidebarThreadIdsToPrewarm<TThreadId>(
408 visibleThreadIds: readonly TThreadId[],
409 limit = SIDEBAR_THREAD_PREWARM_LIMIT,
410): TThreadId[] {
411 return visibleThreadIds.slice(0, Math.max(0, limit));
413​
414export function resolveAdjacentThreadId<T>(input: {
415 threadIds: readonly T[];
416 currentThreadId: T | null;
417 direction: ThreadTraversalDirection;
418}): T | null {
419 const { currentThreadId, direction, threadIds } = input;
420​
421 if (threadIds.length === 0) {
422 return null;
423 }
424​
425 if (currentThreadId === null) {
426 return direction === "previous" ? (threadIds.at(-1) ?? null) : (threadIds[0] ?? null);
427 }
428​
429 const currentIndex = threadIds.indexOf(currentThreadId);
430 if (currentIndex === -1) {
431 return null;
432 }
433​
434 if (direction === "previous") {
435 return currentIndex > 0 ? (threadIds[currentIndex - 1] ?? null) : null;
436 }
437​
438 return currentIndex < threadIds.length - 1 ? (threadIds[currentIndex + 1] ?? null) : null;
440​
441export function shouldNavigateAfterProjectRemoval(input: {
442 routeTarget: ThreadRouteTarget | null;
443 projectThreads: readonly {
444 environmentId: string;
445 id: string;
446 }[];
447 projectDraftId: string | null;
448}): boolean {
449 const { projectDraftId, projectThreads, routeTarget } = input;
450 if (routeTarget?.kind === "draft") {
451 return projectDraftId === routeTarget.draftId;
452 }
453 if (routeTarget?.kind !== "server") {
454 return false;
455 }
456 return projectThreads.some(
457 (thread) =>
458 thread.environmentId === routeTarget.threadRef.environmentId &&
459 thread.id === routeTarget.threadRef.threadId,
460 );
462​
463export function isContextMenuPointerDown(input: {
464 button: number;
465 ctrlKey: boolean;
466 isMac: boolean;
467}): boolean {
468 if (input.button === 2) return true;
469 return input.isMac && input.button === 0 && input.ctrlKey;
471​
472export function resolveThreadRowClassName(input: {
473 isActive: boolean;
474 isSelected: boolean;
475}): string {
476 const baseClassName =
477 "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";
478​
479 if (input.isSelected && input.isActive) {
480 return cn(
481 baseClassName,
482 "bg-sidebar-row-active text-sidebar-foreground font-medium hover:bg-sidebar-row-active hover:text-sidebar-foreground",
483 );
484 }
485​
486 if (input.isSelected) {
487 return cn(
488 baseClassName,
489 "bg-sidebar-row-selected text-sidebar-foreground hover:bg-sidebar-row-active hover:text-sidebar-foreground",
490 );
491 }
492​
493 if (input.isActive) {
494 return cn(
495 baseClassName,
496 "bg-sidebar-row-active text-sidebar-foreground font-medium hover:bg-sidebar-row-active hover:text-sidebar-foreground",
497 );
498 }
499​
500 return cn(
501 baseClassName,
502 "text-sidebar-muted-foreground/80 hover:bg-sidebar-row-hover hover:text-sidebar-foreground",
503 );
505​
506// ── Sidebar v2 status model ─────────────────────────────────────────
507// Six visual states, three colors: color is reserved for "act now"
508// (approval), "in motion" (working), and "broken" (failed). Ready is the
509// unlabeled resting state — the agent stopped and is waiting on the user,
510// whether it finished, asked a question, or proposed a plan. Waiting
511// (runtime status "idle") is the agent stopped with background tasks still
512// open: not the user's turn yet, so it renders grey like working, not as a
513// false Done.
514// Unread completion is tracked separately: it describes whether a ready
515// thread needs attention, not what the thread is currently doing.
516export type SidebarThreadStatus = "approval" | "input" | "working" | "waiting" | "failed" | "ready";
517​
518type SidebarThreadStatusInput = Pick<
519 SidebarThreadSummary,
520 "hasPendingApprovals" | "hasPendingUserInput" | "runtime"
521>;
522​
523export function resolveSidebarThreadStatus(thread: SidebarThreadStatusInput): SidebarThreadStatus {
524 if (thread.hasPendingApprovals) {
525 return "approval";
526 }
527 if (thread.hasPendingUserInput) {
528 return "input";
529 }
530 if (
531 thread.runtime !== null &&
532 ["preparing", "queued", "starting", "running", "waiting"].includes(thread.runtime.status)
533 ) {
534 return "working";
535 }
536 if (thread.runtime?.status === "idle") {
537 return "waiting";
538 }
539 if (thread.runtime?.status === "failed") {
540 return "failed";
541 }
542 return "ready";
544​
545export type SidebarV2TopStatusKind =
546 | "approval"
547 | "done"
548 | "failed"
549 | "input"
550 | "waiting"
551 | "woke"
552 | "working";
553​
554export function resolveSidebarV2TopStatus(input: {
555 readonly status: SidebarThreadStatus;
556 readonly isUnread: boolean;
557 readonly isWoke: boolean;
558}): SidebarV2TopStatusKind | null {
559 if (input.status === "working") {
560 return "working";
561 }
562 if (input.status === "waiting") {
563 return "waiting";
564 }
565 if (input.status === "approval") {
566 return "approval";
567 }
568 if (input.status === "input") {
569 return "input";
570 }
571 if (input.status === "failed") {
572 return "failed";
573 }
574 if (input.isWoke) {
575 return "woke";
576 }
577 return input.isUnread ? "done" : null;
579​
580export function shouldShowSidebarV2Duration(status: SidebarThreadStatus): boolean {
581 return status === "working";
583​
584/** NaN-safe Date.parse for sort comparators: a malformed timestamp must not
585 poison the whole ordering, so it sinks to the epoch instead. */
586export function parseTimestampMs(isoDate: string): number {
587 const parsed = Date.parse(isoDate);
588 return Number.isNaN(parsed) ? 0 : parsed;
590​
591/** First VALID timestamp wins: `a ?? b` falls through on null, but a present-
592 yet-malformed string must also fall through to the next candidate rather
593 than sink the row to the epoch. */
594export function firstValidTimestampMs(
595 ...candidates: ReadonlyArray<string | null | undefined>
596): number {
597 for (const candidate of candidates) {
598 if (candidate == null) continue;
599 const parsed = Date.parse(candidate);
600 if (!Number.isNaN(parsed)) return parsed;
601 }
602 return 0;
604​
605/** String twin of firstValidTimestampMs for callers that need the ISO string
606 (display labels, tick anchors) rather than epoch ms. */
607export function firstValidTimestamp(
608 ...candidates: ReadonlyArray<string | null | undefined>
609): string | null {
610 for (const candidate of candidates) {
611 if (candidate == null) continue;
612 if (!Number.isNaN(Date.parse(candidate))) return candidate;
613 }
614 return null;
616​
617// Sidebar sort: static order, newest anchor on top. Activity NEVER reorders
618// the list — a row holds its position between lifecycle transitions, so the
619// screen only moves when a thread enters or leaves the active list. The
620// anchor is creation time until an un-settle re-anchors it (see
621// activeThreadAnchorTimestampMs), so an un-settled thread surfaces at the
622// top instead of sinking back to its creation-order slot. Status (including
623// pending approval) is carried by each card's edge strip, not by position.
624export function sortThreadsForSidebar<
625 T extends {
626 readonly id: string;
627 readonly createdAt: string;
628 readonly unsettledAt?: string | null | undefined;
629 },
630>(threads: readonly T[]): T[] {
631 return [...threads].toSorted(
632 (left, right) =>
633 activeThreadAnchorTimestampMs(right) - activeThreadAnchorTimestampMs(left) ||
634 left.id.localeCompare(right.id),
635 );
637​
638// Pinned-reorder key math and the keyed sort live in client-runtime
639// (state/thread-sort) so web and mobile compute identical pinned orders.
640export {
641 generateSpreadPinOrderKeys,
642 pinOrderKeyBetween,
643 planPinnedReorder,
644} from "@t3tools/client-runtime/state/thread-sort";
645export { sortPinnedThreadsByOrderKey as sortPinnedThreadsForSidebar } from "@t3tools/client-runtime/state/thread-sort";
646​
647/**
648 * Search the already-ordered sidebar thread collection by title only.
649 * Keeping the input order means lifecycle ordering (active, snoozed, settled)
650 * remains stable while the user narrows the list.
651 */
652export function searchSidebarThreadsByTitle<T extends { readonly title: string }>(
653 threads: readonly T[],
654 query: string,
655): T[] {
656 const normalizedQuery = query.trim().toLowerCase();
657 if (normalizedQuery.length === 0) return [];
658 return threads.filter((thread) => thread.title.toLowerCase().includes(normalizedQuery));
660​
661export function filterSidebarProjectScopeItems<TItem extends { readonly value: string }>(input: {
662 items: readonly TItem[];
663 activeScopeKey: string | null;
664 query: string;
665 matches: (item: TItem, query: string) => boolean;
666}): readonly TItem[] {
667 const projectItems = input.items.filter((item) => item.value !== "all");
668 const query = input.query.trim();
669 if (query.length > 0) {
670 return projectItems.filter((item) => input.matches(item, query));
671 }
672 return input.activeScopeKey === null ? projectItems : input.items;
674​
675export interface SidebarProjectScopeMenuState {
676 readonly open: boolean;
677 readonly query: string;
679​
680export type SidebarProjectScopeMenuAction =
681 | { readonly type: "query-changed"; readonly query: string }
682 | { readonly type: "open-changed"; readonly open: boolean }
683 | { readonly type: "project-settings-opened" };
684​
685export function reduceSidebarProjectScopeMenuState(
686 state: SidebarProjectScopeMenuState,
687 action: SidebarProjectScopeMenuAction,
688): SidebarProjectScopeMenuState {
689 switch (action.type) {
690 case "query-changed":
691 return { ...state, query: action.query };
692 case "open-changed":
693 return { open: action.open, query: "" };
694 case "project-settings-opened":
695 return { open: false, query: "" };
696 }
698​
699type SettledTimestampInput = Pick<
700 SidebarThreadSummary,
701 "settledAt" | "latestUserMessageAt" | "latestRun" | "updatedAt"
702>;
703​
704/** The timestamp a settled row sorts and labels by: settledAt when stamped
705 (explicit settles), otherwise last activity — the same candidates
706 threadLastActivityAt feeds the auto-settle window (user message plus all
707 latestRun stamps), so a thread whose last activity was a run completion
708 doesn't sort by an older message time. updatedAt is the final net. */
709export function resolveSettledTimestamp(thread: SettledTimestampInput): string | null {
710 const settledAt = firstValidTimestamp(thread.settledAt);
711 if (settledAt !== null) return settledAt;
712 let latest: string | null = null;
713 let latestMs = Number.NEGATIVE_INFINITY;
714 for (const candidate of [
715 thread.latestUserMessageAt,
716 thread.latestRun?.requestedAt,
717 thread.latestRun?.startedAt,
718 thread.latestRun?.completedAt,
719 ]) {
720 if (candidate == null) continue;
721 const parsed = Date.parse(candidate);
722 if (!Number.isNaN(parsed) && parsed > latestMs) {
723 latest = candidate;
724 latestMs = parsed;
725 }
726 }
727 return latest ?? firstValidTimestamp(thread.updatedAt);
729​
730// Settled rows are history, so they order by when the work ENDED, not when
731// the thread was created or last touched.
732export function sortSettledThreadsForSidebar<
733 T extends SettledTimestampInput & { readonly id: string },
734>(threads: readonly T[]): T[] {
735 const timestampMs = (thread: T) => {
736 const timestamp = resolveSettledTimestamp(thread);
737 return timestamp === null ? 0 : Date.parse(timestamp);
738 };
739 return [...threads].toSorted(
740 (left, right) => timestampMs(right) - timestampMs(left) || left.id.localeCompare(right.id),
741 );
743​
744/** The timestamp a working thread's elapsed label counts from: the running
745 turn's start (request time until adoption), falling back to the session's
746 last transition when the turn projection lags behind. Malformed
747 timestamps fall through to the next candidate, not just missing ones. */
748export function resolveWorkingStartedAt(
749 thread: Pick<SidebarThreadSummary, "latestRun" | "runtime">,
750): string | null {
751 const run = thread.latestRun;
752 if (run && run.completedAt === null) {
753 return firstValidTimestamp(run.startedAt, run.requestedAt, thread.runtime?.updatedAt);
754 }
755 return firstValidTimestamp(thread.runtime?.updatedAt);
757​
758export function formatWorkingDurationLabel(elapsedMs: number): string {
759 const seconds = Number.isFinite(elapsedMs) ? Math.max(0, Math.floor(elapsedMs / 1000)) : 0;
760 if (seconds < 60) return `${seconds}s`;
761 const minutes = Math.floor(seconds / 60);
762 if (minutes < 60) return `${minutes}m`;
763 return `${Math.floor(minutes / 60)}h ${minutes % 60}m`;
765​
766export function resolveThreadStatusPill(input: {
767 thread: ThreadStatusInput;
768}): ThreadStatusPill | null {
769 const { thread } = input;
770​
771 if (thread.hasPendingApprovals) {
772 return {
773 label: "Pending Approval",
774 colorClass: "text-amber-600 dark:text-amber-300/90",
775 dotClass: "bg-amber-500 dark:bg-amber-300/90",
776 pulse: false,
777 };
778 }
779​
780 if (thread.hasPendingUserInput) {
781 return {
782 label: "Awaiting Input",
783 colorClass: "text-indigo-600 dark:text-indigo-300/90",
784 dotClass: "bg-indigo-500 dark:bg-indigo-300/90",
785 pulse: false,
786 };
787 }
788​
789 if (thread.runtime?.status === "running" || thread.runtime?.status === "waiting") {
790 return {
791 label: "Working",
792 colorClass: "text-sky-600 dark:text-sky-300/80",
793 dotClass: "bg-sky-500 dark:bg-sky-300/80",
794 pulse: true,
795 };
796 }
797​
798 if (
799 thread.runtime?.status === "preparing" ||
800 thread.runtime?.status === "starting" ||
801 thread.runtime?.status === "queued"
802 ) {
803 return {
804 label: "Connecting",
805 colorClass: "text-sky-600 dark:text-sky-300/80",
806 dotClass: "bg-sky-500 dark:bg-sky-300/80",
807 pulse: true,
808 };
809 }
810​
811 if ((thread.pendingBackgroundTasks?.length ?? 0) > 0) {
812 return {
813 label: "Waiting",
814 colorClass: "text-sidebar-muted-foreground",
815 dotClass: "bg-sidebar-muted-foreground",
816 pulse: false,
817 };
818 }
819​
820 const hasPlanReadyPrompt =
821 !thread.hasPendingUserInput &&
822 thread.interactionMode === "plan" &&
823 isLatestRunSettled(thread.latestRun, thread.runtime) &&
824 thread.hasActionableProposedPlan;
825 if (hasPlanReadyPrompt) {
826 return {
827 label: "Plan Ready",
828 colorClass: "text-violet-600 dark:text-violet-300/90",
829 dotClass: "bg-violet-500 dark:bg-violet-300/90",
830 pulse: false,
831 };
832 }
833​
834 if (hasUnseenCompletion(thread)) {
835 return {
836 label: "Completed",
837 colorClass: "text-emerald-600 dark:text-emerald-300/90",
838 dotClass: "bg-emerald-500 dark:bg-emerald-300/90",
839 pulse: false,
840 };
841 }
842​
843 return null;
845​
846export function resolveProjectStatusIndicator(
847 statuses: ReadonlyArray<ThreadStatusPill | null>,
848): ThreadStatusPill | null {
849 let highestPriorityStatus: ThreadStatusPill | null = null;
850​
851 for (const status of statuses) {
852 if (status === null) continue;
853 if (
854 highestPriorityStatus === null ||
855 THREAD_STATUS_PRIORITY[status.label] > THREAD_STATUS_PRIORITY[highestPriorityStatus.label]
856 ) {
857 highestPriorityStatus = status;
858 }
859 }
860​
861 return highestPriorityStatus;
863​
864export function getVisibleThreadsForProject<T extends Pick<Thread, "id">>(input: {
865 threads: readonly T[];
866 activeThreadId: T["id"] | undefined;
867 isThreadListExpanded: boolean;
868 previewLimit: number;
869}): {
870 hasHiddenThreads: boolean;
871 visibleThreads: T[];
872 hiddenThreads: T[];
873} {
874 const { activeThreadId, isThreadListExpanded, previewLimit, threads } = input;
875 const hasHiddenThreads = threads.length > previewLimit;
876​
877 if (!hasHiddenThreads || isThreadListExpanded) {
878 return {
879 hasHiddenThreads,
880 hiddenThreads: [],
881 visibleThreads: [...threads],
882 };
883 }
884​
885 const previewThreads = threads.slice(0, previewLimit);
886 if (!activeThreadId || previewThreads.some((thread) => thread.id === activeThreadId)) {
887 return {
888 hasHiddenThreads: true,
889 hiddenThreads: threads.slice(previewLimit),
890 visibleThreads: previewThreads,
891 };
892 }
893​
894 const activeThread = threads.find((thread) => thread.id === activeThreadId);
895 if (!activeThread) {
896 return {
897 hasHiddenThreads: true,
898 hiddenThreads: threads.slice(previewLimit),
899 visibleThreads: previewThreads,
900 };
901 }
902​
903 const visibleThreadIds = new Set([...previewThreads, activeThread].map((thread) => thread.id));
904​
905 return {
906 hasHiddenThreads: true,
907 hiddenThreads: threads.filter((thread) => !visibleThreadIds.has(thread.id)),
908 visibleThreads: threads.filter((thread) => visibleThreadIds.has(thread.id)),
909 };
911​
912export function getFallbackThreadIdAfterDelete<
913 T extends Pick<Thread, "id" | "projectId" | "createdAt" | "updatedAt"> & ThreadSortInput,
914>(input: {
915 threads: readonly T[];
916 deletedThreadId: T["id"];
917 sortOrder: SidebarThreadSortOrder;
918 deletedThreadIds?: ReadonlySet<T["id"]>;
919}): T["id"] | null {
920 const { deletedThreadId, deletedThreadIds, sortOrder, threads } = input;
921 const deletedThread = threads.find((thread) => thread.id === deletedThreadId);
922 if (!deletedThread) {
923 return null;
924 }
925​
926 return (
927 sortThreads(
928 threads.filter(
929 (thread) =>
930 thread.projectId === deletedThread.projectId &&
931 thread.id !== deletedThreadId &&
932 !deletedThreadIds?.has(thread.id),
933 ),
934 sortOrder,
935 )[0]?.id ?? null
936 );
938export function getProjectSortTimestamp(
939 project: SidebarProject,
940 projectThreads: readonly ThreadSortInput[],
941 sortOrder: Exclude<SidebarProjectSortOrder, "manual">,
942): number {
943 if (projectThreads.length > 0) {
944 return projectThreads.reduce(
945 (latest, thread) => Math.max(latest, getThreadSortTimestamp(thread, sortOrder)),
946 Number.NEGATIVE_INFINITY,
947 );
948 }
949​
950 if (sortOrder === "created_at") {
951 return toSortableTimestamp(project.createdAt) ?? Number.NEGATIVE_INFINITY;
952 }
953 return toSortableTimestamp(project.updatedAt ?? project.createdAt) ?? Number.NEGATIVE_INFINITY;
955​
956function sortProjectsByActivity<TProject extends SidebarProject>(
957 projects: readonly TProject[],
958 sortOrder: SidebarProjectSortOrder,
959 getProjectThreads: (project: TProject) => readonly ThreadSortInput[],
960 compareTies: (left: TProject, right: TProject) => number,
961): TProject[] {
962 if (sortOrder === "manual") {
963 return [...projects];
964 }
965​
966 return [...projects].toSorted((left, right) => {
967 const rightTimestamp = getProjectSortTimestamp(right, getProjectThreads(right), sortOrder);
968 const leftTimestamp = getProjectSortTimestamp(left, getProjectThreads(left), sortOrder);
969 const byTimestamp =
970 rightTimestamp === leftTimestamp ? 0 : rightTimestamp > leftTimestamp ? 1 : -1;
971 return byTimestamp || compareTies(left, right);
972 });
974​
975export function sortProjectsForSidebar<
976 TProject extends SidebarProject,
977 TThread extends Pick<Thread, "projectId" | "createdAt" | "updatedAt"> & ThreadSortInput,
978>(
979 projects: readonly TProject[],
980 threads: readonly TThread[],
981 sortOrder: SidebarProjectSortOrder,
982): TProject[] {
983 const threadsByProjectId = new Map<string, TThread[]>();
984 for (const thread of threads) {
985 const existing = threadsByProjectId.get(thread.projectId) ?? [];
986 existing.push(thread);
987 threadsByProjectId.set(thread.projectId, existing);
988 }
989​
990 return sortProjectsByActivity(
991 projects,
992 sortOrder,
993 (project) => threadsByProjectId.get(project.id) ?? [],
994 (left, right) => left.title.localeCompare(right.title) || left.id.localeCompare(right.id),
995 );
997​
998export function sortLogicalProjectsForSidebar<
999 TProject extends LogicalSidebarProject,
1000 TThread extends ScopedSidebarThread,
1002 projects: readonly TProject[],
1003 threads: readonly TThread[],
1004 sortOrder: SidebarProjectSortOrder,
1005): TProject[] {
1006 const groupKeyByProjectRef = new Map(
1007 projects.flatMap((project) =>
1008 project.memberProjectRefs.map(
1009 (projectRef) =>
1010 [`${projectRef.environmentId}\0${projectRef.projectId}`, project.projectKey] as const,
1011 ),
1012 ),
1013 );
1014 const threadsByProjectKey = new Map<string, TThread[]>();
1015 for (const thread of threads) {
1016 if (thread.archivedAt !== null) continue;
1017 const projectKey = groupKeyByProjectRef.get(`${thread.environmentId}\0${thread.projectId}`);
1018 if (!projectKey) continue;
1019 const existing = threadsByProjectKey.get(projectKey);
1020 if (existing) {
1021 existing.push(thread);
1022 } else {
1023 threadsByProjectKey.set(projectKey, [thread]);
1026​
1027 return sortProjectsByActivity(
1028 projects,
1029 sortOrder,
1030 (project) => threadsByProjectKey.get(project.projectKey) ?? [],
1031 (left, right) =>
1032 left.title.localeCompare(right.title) || left.projectKey.localeCompare(right.projectKey),
1033 );
1035​
1036export function sortSidebarV2ProjectGroups<
1037 TProject extends LogicalSidebarProject,
1038 TThread extends ScopedSidebarThread & Pick<SidebarThreadSummary, "lineage">,
1040 projects: readonly TProject[],
1041 threads: readonly TThread[],
1042 sortOrder: SidebarProjectSortOrder,
1043): TProject[] {
1044 return sortLogicalProjectsForSidebar(
1045 projects,
1046 filterSidebarV2VisibleThreads(threads, null),
1047 sortOrder,
1048 );
1050​
1051/**
1052 * Sorts the cross-environment project collection used by landing surfaces.
1053 * Project ids are only unique within an environment, and archived threads
1054 * must not make a project appear recently active.
1055 */
1056export function sortScopedProjectsForSidebar<
1057 TProject extends ScopedSidebarProject,
1058 TThread extends ScopedSidebarThread,
1060 projects: readonly TProject[],
1061 threads: readonly TThread[],
1062 sortOrder: SidebarProjectSortOrder,
1063): TProject[] {
1064 const scopedKey = (environmentId: string, projectId: string) =>
1065 `${environmentId}\u0000${projectId}`;
1066 const threadsByProject = new Map<string, TThread[]>();
1067 for (const thread of threads) {
1068 if (thread.archivedAt !== null) {
1069 continue;
1071 const key = scopedKey(thread.environmentId, thread.projectId);
1072 const existing = threadsByProject.get(key) ?? [];
1073 existing.push(thread);
1074 threadsByProject.set(key, existing);
1076​
1077 return sortProjectsByActivity(
1078 projects,
1079 sortOrder,
1080 (project) => threadsByProject.get(scopedKey(project.environmentId, project.id)) ?? [],
1081 (left, right) =>
1082 left.title.localeCompare(right.title) ||
1083 left.environmentId.localeCompare(right.environmentId) ||
1084 left.id.localeCompare(right.id),
1085 );