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

Sidebar.logic.ts

1,048 lines33.8 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 resolveSettledThreadTimestamp,
9 sortThreads,
10 toSortableTimestamp,
11 type SettledThreadTimestampInput,
12 type ThreadSortInput,
13} from "../lib/threadSort";
14import type { SidebarThreadSummary, Thread } from "../types";
15import type { ThreadRouteTarget } from "../threadRoutes";
16import { cn } from "../lib/utils";
17import { isLatestTurnSettled } from "../session-logic";
18​
19export const THREAD_SELECTION_SAFE_SELECTOR = "[data-thread-item], [data-thread-selection-safe]";
20export const THREAD_JUMP_HINT_SHOW_DELAY_MS = 200;
21// Visible sidebar rows are prewarmed into the thread-detail cache so opening a
22// nearby thread usually reuses an already-hot subscription. Each prewarmed
23// thread holds a live, fully hydrated detail subscription (all messages and
24// activities, growing as agents work) for as long as the row stays visible,
25// so this limit is a direct renderer-heap and server-load multiplier — keep
26// it small; cold opens still render instantly from the cached snapshot.
27export const SIDEBAR_THREAD_PREWARM_LIMIT = 3;
28// A small buffer keeps the next few rows warm without leasing every row that
29// content-visibility leaves mounted below the scroll viewport.
30export const SIDEBAR_ROW_SUBSCRIPTION_OVERSCAN_PX = 160;
31​
32export function useSidebarRowSubscriptionLease(isActive: boolean): {
33 readonly leaseLiveStatus: boolean;
34 readonly rowRef: React.Dispatch<React.SetStateAction<HTMLElement | null>>;
35} {
36 const [row, setRow] = React.useState<HTMLElement | null>(null);
37 const [isNearViewport, setIsNearViewport] = React.useState(isActive);
38​
39 React.useEffect(() => {
40 if (isActive) {
41 setIsNearViewport(true);
42 return;
43 }
44 if (row === null) return;
45 if (typeof IntersectionObserver === "undefined") {
46 setIsNearViewport(true);
47 return;
48 }
49​
50 const scrollRoot = row.closest<HTMLElement>('[data-slot="scroll-area-viewport"]');
51 const observer = new IntersectionObserver(
52 ([entry]) => setIsNearViewport(entry?.isIntersecting === true),
53 {
54 root: scrollRoot,
55 rootMargin: `${SIDEBAR_ROW_SUBSCRIPTION_OVERSCAN_PX}px 0px`,
56 },
57 );
58 observer.observe(row);
59 return () => observer.disconnect();
60 }, [isActive, row]);
61​
62 return {
63 leaseLiveStatus: isActive || isNearViewport,
64 rowRef: setRow,
65 };
67​
68// A row keeps the last live value it rendered so a released lease never
69// blanks its badge. The value is bound to `key`, so a different worktree or
70// linked pull request cannot reuse the previous one.
71export function useRetainedValue<T>(key: string | null, value: T | null): T | null {
72 const retained = React.useRef<{ readonly key: string; readonly value: T } | null>(null);
73 if (key !== null && value !== null) {
74 retained.current = { key, value };
75 }
76 if (value !== null) return value;
77 return key !== null && retained.current?.key === key ? retained.current.value : null;
79​
80// The list already reaches its destination through sortable transforms while
81// the pointer is down. dnd-kit's default also animates the committed DOM order
82// after release, replaying the same movement across every affected row.
83export const animatePinnedLayoutChanges: AnimateLayoutChanges = (args) =>
84 args.isSorting ? defaultAnimateLayoutChanges(args) : false;
85​
86type SidebarProject = {
87 id: string;
88 title: string;
89 createdAt?: string | undefined;
90 updatedAt?: string | undefined;
91};
92​
93type ScopedSidebarProject = SidebarProject & {
94 environmentId: string;
95};
96​
97type ScopedSidebarThread = ThreadSortInput & {
98 environmentId: string;
99 projectId: string;
100 archivedAt: string | null;
101};
102​
103type LogicalSidebarProject = SidebarProject & {
104 projectKey: string;
105 memberProjectRefs: readonly {
106 environmentId: string;
107 projectId: string;
108 }[];
109};
110​
111export type ThreadTraversalDirection = "previous" | "next";
112​
113export async function archiveSelectedThreadEntries<
114 TEntry extends { readonly threadKey: string },
115 TResult extends { readonly _tag: "Success" | "Failure" },
116>(input: {
117 entries: readonly TEntry[];
118 archive: (entry: TEntry, onArchived: () => void) => Promise<TResult>;
119}): Promise<{
120 archivedThreadKeys: readonly string[];
121 mutationFailure: Extract<TResult, { readonly _tag: "Failure" }> | null;
122 followupFailures: readonly Extract<TResult, { readonly _tag: "Failure" }>[];
123}> {
124 const archivedThreadKeys: string[] = [];
125 const followupFailures: Extract<TResult, { readonly _tag: "Failure" }>[] = [];
126​
127 for (const entry of input.entries) {
128 let didArchive = false;
129 const result = await input.archive(entry, () => {
130 didArchive = true;
131 });
132 if (didArchive || result._tag === "Success") {
133 archivedThreadKeys.push(entry.threadKey);
134 }
135 if (result._tag === "Success") continue;
136 const failure = result as Extract<TResult, { readonly _tag: "Failure" }>;
137 if (didArchive) {
138 followupFailures.push(failure);
139 continue;
140 }
141 return { archivedThreadKeys, mutationFailure: failure, followupFailures };
142 }
143​
144 return { archivedThreadKeys, mutationFailure: null, followupFailures };
146​
147export function buildMultiSelectThreadContextMenuItems(input: {
148 count: number;
149 hasRunningThread: boolean;
150}): readonly ContextMenuItem<"mark-unread" | "archive" | "delete">[] {
151 return [
152 { id: "mark-unread", label: `Mark unread (${input.count})` },
153 {
154 id: "archive",
155 label: `Archive (${input.count})`,
156 disabled: input.hasRunningThread,
157 },
158 { id: "delete", label: `Delete (${input.count})`, destructive: true },
159 ];
161​
162export function buildBulkTitleRegenerationContextMenuItem(input: {
163 supportedCount: number;
164 actionableCount: number;
165}): ContextMenuItem<"regenerate-title"> | null {
166 if (input.supportedCount === 0) return null;
167 if (input.actionableCount === 0) {
168 return {
169 id: "regenerate-title",
170 label: `Regenerating… (${input.supportedCount})`,
171 disabled: true,
172 };
173 }
174 return {
175 id: "regenerate-title",
176 label: `Regenerate titles (${input.actionableCount})`,
177 };
179​
180/**
181 * Bulk unpin follows the same "count only what the action will touch" rule
182 * as title regeneration: on a mixed selection the label counts the pinned
183 * rows alone, and the item disappears when nothing selected is pinned.
184 */
185export function buildBulkUnpinContextMenuItem(input: {
186 pinnedCount: number;
187}): ContextMenuItem<"unpin"> | null {
188 if (input.pinnedCount === 0) return null;
189 return { id: "unpin", label: `Unpin (${input.pinnedCount})` };
191​
192export interface ThreadStatusPill {
193 label:
194 | "Working"
195 | "Monitoring"
196 | "Connecting"
197 | "Completed"
198 | "Pending Approval"
199 | "Awaiting Input"
200 | "Plan Ready";
201 colorClass: string;
202 dotClass: string;
203 pulse: boolean;
205​
206// Rollup order mirrors the per-thread resolver exactly: attention states,
207// then active work, then the actionable plan prompt, then passive
208// monitoring. A Monitoring sibling must never hide a Plan Ready thread.
209const THREAD_STATUS_PRIORITY: Record<ThreadStatusPill["label"], number> = {
210 "Pending Approval": 6,
211 "Awaiting Input": 5,
212 Working: 4,
213 Connecting: 4,
214 "Plan Ready": 3,
215 Monitoring: 2,
216 Completed: 1,
217};
218​
219type ThreadStatusInput = Pick<
220 SidebarThreadSummary,
221 | "hasActionableProposedPlan"
222 | "hasPendingApprovals"
223 | "hasPendingUserInput"
224 | "interactionMode"
225 | "latestTurn"
226 | "session"
227 | "backgroundLiveness"
228> & {
229 lastVisitedAt?: string | undefined;
230};
231​
232export interface ThreadJumpHintVisibilityController {
233 sync: (shouldShow: boolean) => void;
234 dispose: () => void;
236​
237export function createThreadJumpHintVisibilityController(input: {
238 delayMs: number;
239 onVisibilityChange: (visible: boolean) => void;
240 setTimeoutFn?: typeof globalThis.setTimeout;
241 clearTimeoutFn?: typeof globalThis.clearTimeout;
242}): ThreadJumpHintVisibilityController {
243 const setTimeoutFn = input.setTimeoutFn ?? globalThis.setTimeout;
244 const clearTimeoutFn = input.clearTimeoutFn ?? globalThis.clearTimeout;
245 let isVisible = false;
246 let timeoutId: NodeJS.Timeout | null = null;
247​
248 const clearPendingShow = () => {
249 if (timeoutId === null) {
250 return;
251 }
252 clearTimeoutFn(timeoutId);
253 timeoutId = null;
254 };
255​
256 return {
257 sync: (shouldShow) => {
258 if (!shouldShow) {
259 clearPendingShow();
260 if (isVisible) {
261 isVisible = false;
262 input.onVisibilityChange(false);
263 }
264 return;
265 }
266​
267 if (isVisible || timeoutId !== null) {
268 return;
269 }
270​
271 timeoutId = setTimeoutFn(() => {
272 timeoutId = null;
273 isVisible = true;
274 input.onVisibilityChange(true);
275 }, input.delayMs);
276 },
277 dispose: () => {
278 clearPendingShow();
279 },
280 };
282​
283export function useThreadJumpHintVisibility(): {
284 showThreadJumpHints: boolean;
285 updateThreadJumpHintsVisibility: (shouldShow: boolean) => void;
286} {
287 const [showThreadJumpHints, setShowThreadJumpHints] = React.useState(false);
288 const controllerRef = React.useRef<ThreadJumpHintVisibilityController | null>(null);
289​
290 React.useEffect(() => {
291 const controller = createThreadJumpHintVisibilityController({
292 delayMs: THREAD_JUMP_HINT_SHOW_DELAY_MS,
293 onVisibilityChange: (visible) => {
294 setShowThreadJumpHints(visible);
295 },
296 setTimeoutFn: window.setTimeout.bind(window),
297 clearTimeoutFn: window.clearTimeout.bind(window),
298 });
299 controllerRef.current = controller;
300​
301 return () => {
302 controller.dispose();
303 controllerRef.current = null;
304 };
305 }, []);
306​
307 const updateThreadJumpHintsVisibility = React.useCallback((shouldShow: boolean) => {
308 controllerRef.current?.sync(shouldShow);
309 }, []);
310​
311 return {
312 showThreadJumpHints,
313 updateThreadJumpHintsVisibility,
314 };
316​
317export function hasUnseenCompletion(thread: ThreadStatusInput): boolean {
318 if (!thread.latestTurn?.completedAt) return false;
319 const completedAt = Date.parse(thread.latestTurn.completedAt);
320 if (Number.isNaN(completedAt)) return false;
321 if (!thread.lastVisitedAt) return false;
322​
323 const lastVisitedAt = Date.parse(thread.lastVisitedAt);
324 if (Number.isNaN(lastVisitedAt)) return true;
325 return completedAt > lastVisitedAt;
327​
328export function shouldClearThreadSelectionOnMouseDown(target: HTMLElement | null): boolean {
329 if (target === null) return true;
330 return !target.closest(THREAD_SELECTION_SAFE_SELECTOR);
332​
333// A double-click dispatches two `click` events before `dblclick`: the first has
334// `detail === 1`, the second `detail === 2`. The second click must not run the
335// row's single-click navigation, otherwise double-click-to-rename would also
336// navigate. `MouseEvent.detail` is 0 for synthetic/keyboard activations, which
337// still count as a normal single activation.
338export function isTrailingDoubleClick(detail: number): boolean {
339 return detail > 1;
341​
342function nodeClosest(node: object | null, selector: string): unknown {
343 if (node === null || !("closest" in node) || typeof node.closest !== "function") return null;
344 return node.closest(selector);
346​
347/** Clicks on a nested link keep the link's meaning. The row must not treat them as multi-select. */
348export function isSidebarNestedLinkClick(target: EventTarget | null): boolean {
349 if (target == null || typeof target !== "object") return false;
350 if (nodeClosest(target, "a[href]") !== null) return true;
351 const parent =
352 "parentElement" in target &&
353 target.parentElement !== null &&
354 typeof target.parentElement === "object"
355 ? target.parentElement
356 : null;
357 return nodeClosest(parent, "a[href]") !== null;
359​
360// Shift+click on the new thread button creates directly in the current
361// project, skipping the command palette's project picker. With a single
362// project there is nothing to pick, so a plain click already creates
363// immediately and the modifier changes nothing.
364export function shouldCreateNewThreadInCurrentProject(
365 shiftKey: boolean,
366 projectGroupCount: number,
367): boolean {
368 return shiftKey || projectGroupCount <= 1;
370​
371export function orderItemsByPreferredIds<TItem, TId>(input: {
372 items: readonly TItem[];
373 preferredIds: readonly TId[];
374 getId: (item: TItem) => TId;
375 getPreferenceIds?: (item: TItem) => readonly TId[];
376}): TItem[] {
377 const { getId, getPreferenceIds, items, preferredIds } = input;
378 if (preferredIds.length === 0) {
379 return [...items];
380 }
381​
382 const indexesByPreferenceId = new Map<TId, number[]>();
383 for (const [index, item] of items.entries()) {
384 const preferenceIds = getPreferenceIds?.(item) ?? [getId(item)];
385 for (const preferenceId of new Set(preferenceIds)) {
386 const indexes = indexesByPreferenceId.get(preferenceId);
387 if (indexes) {
388 indexes.push(index);
389 } else {
390 indexesByPreferenceId.set(preferenceId, [index]);
391 }
392 }
393 }
394​
395 const emittedIndexes = new Set<number>();
396 const ordered = preferredIds.flatMap((id) => {
397 const index = indexesByPreferenceId
398 .get(id)
399 ?.find((candidate) => !emittedIndexes.has(candidate));
400 if (index === undefined) {
401 return [];
402 }
403 emittedIndexes.add(index);
404 return [items[index]!];
405 });
406 const remaining = items.filter((_, index) => !emittedIndexes.has(index));
407 return [...ordered, ...remaining];
409​
410export function getVisibleSidebarThreadIds<TThreadId>(
411 renderedProjects: readonly {
412 shouldShowThreadPanel?: boolean;
413 renderedThreadIds: readonly TThreadId[];
414 }[],
415): TThreadId[] {
416 return renderedProjects.flatMap((renderedProject) =>
417 renderedProject.shouldShowThreadPanel === false ? [] : renderedProject.renderedThreadIds,
418 );
420​
421export function getSidebarThreadIdsToPrewarm<TThreadId>(
422 visibleThreadIds: readonly TThreadId[],
423 limit = SIDEBAR_THREAD_PREWARM_LIMIT,
424): TThreadId[] {
425 return visibleThreadIds.slice(0, Math.max(0, limit));
427​
428export function resolveAdjacentThreadId<T>(input: {
429 threadIds: readonly T[];
430 currentThreadId: T | null;
431 direction: ThreadTraversalDirection;
432}): T | null {
433 const { currentThreadId, direction, threadIds } = input;
434​
435 if (threadIds.length === 0) {
436 return null;
437 }
438​
439 if (currentThreadId === null) {
440 return direction === "previous" ? (threadIds.at(-1) ?? null) : (threadIds[0] ?? null);
441 }
442​
443 const currentIndex = threadIds.indexOf(currentThreadId);
444 if (currentIndex === -1) {
445 return null;
446 }
447​
448 if (direction === "previous") {
449 return currentIndex > 0 ? (threadIds[currentIndex - 1] ?? null) : null;
450 }
451​
452 return currentIndex < threadIds.length - 1 ? (threadIds[currentIndex + 1] ?? null) : null;
454​
455export function shouldNavigateAfterProjectRemoval(input: {
456 routeTarget: ThreadRouteTarget | null;
457 projectThreads: readonly {
458 environmentId: string;
459 id: string;
460 }[];
461 projectDraftId: string | null;
462}): boolean {
463 const { projectDraftId, projectThreads, routeTarget } = input;
464 if (routeTarget?.kind === "draft") {
465 return projectDraftId === routeTarget.draftId;
466 }
467 if (routeTarget?.kind !== "server") {
468 return false;
469 }
470 return projectThreads.some(
471 (thread) =>
472 thread.environmentId === routeTarget.threadRef.environmentId &&
473 thread.id === routeTarget.threadRef.threadId,
474 );
476​
477export function isContextMenuPointerDown(input: {
478 button: number;
479 ctrlKey: boolean;
480 isMac: boolean;
481}): boolean {
482 if (input.button === 2) return true;
483 return input.isMac && input.button === 0 && input.ctrlKey;
485​
486export function resolveThreadRowClassName(input: {
487 isActive: boolean;
488 isSelected: boolean;
489}): string {
490 const baseClassName =
491 "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";
492​
493 if (input.isSelected && 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 if (input.isSelected) {
501 return cn(
502 baseClassName,
503 "bg-sidebar-row-selected text-sidebar-foreground hover:bg-sidebar-row-active hover:text-sidebar-foreground",
504 );
505 }
506​
507 if (input.isActive) {
508 return cn(
509 baseClassName,
510 "bg-sidebar-row-active text-sidebar-foreground font-medium hover:bg-sidebar-row-active hover:text-sidebar-foreground",
511 );
512 }
513​
514 return cn(
515 baseClassName,
516 "text-sidebar-muted-foreground/80 hover:bg-sidebar-row-hover hover:text-sidebar-foreground",
517 );
519​
520// ── Sidebar thread status model ─────────────────────────────────────
521// Five visual states, three colors: color is reserved for "act now"
522// (approval), "in motion" (working), and "broken" (failed). Ready is the
523// unlabeled resting state — the agent stopped and is waiting on the user,
524// whether it finished, asked a question, or proposed a plan.
525// Unread completion is tracked separately: it describes whether a ready
526// thread needs attention, not what the thread is currently doing.
527export type SidebarThreadStatus =
528 | "approval"
529 | "input"
530 | "working"
531 | "monitoring"
532 | "failed"
533 | "ready";
534​
535export function shouldRecedeSidebarThread(input: {
536 status: SidebarThreadStatus;
537 isUnread: boolean;
538 isWoke: boolean;
539 isActive: boolean;
540 isSelected: boolean;
541}): boolean {
542 if (input.isActive || input.isSelected) return false;
543 if (input.status === "working" || input.status === "monitoring") return true;
544 if (input.status === "ready" || input.status === "approval" || input.status === "input") {
545 return !input.isUnread && !input.isWoke;
546 }
547 return false;
549​
550type SidebarThreadStatusInput = Pick<
551 SidebarThreadSummary,
552 "hasPendingApprovals" | "hasPendingUserInput" | "session" | "backgroundLiveness"
553>;
554​
555export function resolveSidebarThreadStatus(thread: SidebarThreadStatusInput): SidebarThreadStatus {
556 if (thread.hasPendingApprovals) {
557 return "approval";
558 }
559 if (thread.hasPendingUserInput) {
560 return "input";
561 }
562 if (thread.session?.status === "running" || thread.session?.status === "starting") {
563 return "working";
564 }
565 // A failed session outranks lingering background liveness: the user must
566 // see the failure, not a stale Working (review finding).
567 if (thread.session?.status === "error") {
568 return "failed";
569 }
570 // Background work outlives the turn: fleets read as working; monitoring
571 // only when watch loops are the sole live work.
572 if (thread.backgroundLiveness === "working") {
573 return "working";
574 }
575 if (thread.backgroundLiveness === "monitoring") {
576 return "monitoring";
577 }
578 return "ready";
580​
581/** NaN-safe Date.parse for sort comparators: a malformed timestamp must not
582 poison the whole ordering, so it sinks to the epoch instead. */
583export function parseTimestampMs(isoDate: string): number {
584 const parsed = Date.parse(isoDate);
585 return Number.isNaN(parsed) ? 0 : parsed;
587​
588/** First VALID timestamp wins: `a ?? b` falls through on null, but a present-
589 yet-malformed string must also fall through to the next candidate rather
590 than sink the row to the epoch. */
591export function firstValidTimestampMs(
592 ...candidates: ReadonlyArray<string | null | undefined>
593): number {
594 for (const candidate of candidates) {
595 if (candidate == null) continue;
596 const parsed = Date.parse(candidate);
597 if (!Number.isNaN(parsed)) return parsed;
598 }
599 return 0;
601​
602/** String twin of firstValidTimestampMs for callers that need the ISO string
603 (display labels, tick anchors) rather than epoch ms. */
604export function firstValidTimestamp(
605 ...candidates: ReadonlyArray<string | null | undefined>
606): string | null {
607 for (const candidate of candidates) {
608 if (candidate == null) continue;
609 if (!Number.isNaN(Date.parse(candidate))) return candidate;
610 }
611 return null;
613​
614// Sidebar sort: static order, newest anchor on top. Activity NEVER reorders
615// the list — a row holds its position between lifecycle transitions, so the
616// screen only moves when a thread enters or leaves the active list. The
617// anchor is creation time until an un-settle re-anchors it (see
618// activeThreadAnchorTimestampMs), so an un-settled thread surfaces at the
619// top instead of sinking back to its creation-order slot. Status (including
620// pending approval) is carried by each card's edge strip, not by position.
621export function sortThreadsForSidebar<
622 T extends {
623 readonly id: string;
624 readonly createdAt: string;
625 readonly unsettledAt?: string | null | undefined;
626 },
627>(threads: readonly T[]): T[] {
628 return [...threads].toSorted(
629 (left, right) =>
630 activeThreadAnchorTimestampMs(right) - activeThreadAnchorTimestampMs(left) ||
631 left.id.localeCompare(right.id),
632 );
634​
635// Pinned-reorder key math and the keyed sort live in client-runtime
636// (state/thread-sort) so web and mobile compute identical pinned orders.
637export {
638 generateSpreadPinOrderKeys,
639 pinOrderKeyBetween,
640 planPinnedReorder,
641} from "@t3tools/client-runtime/state/thread-sort";
642export { sortPinnedThreadsByOrderKey as sortPinnedThreadsForSidebar } from "@t3tools/client-runtime/state/thread-sort";
643​
644/**
645 * Search the already-ordered sidebar thread collection by title only.
646 * Keeping the input order means lifecycle ordering (active, snoozed, settled)
647 * remains stable while the user narrows the list.
648 */
649export function searchSidebarThreadsByTitle<T extends { readonly title: string }>(
650 threads: readonly T[],
651 query: string,
652): T[] {
653 const normalizedQuery = query.trim().toLowerCase();
654 if (normalizedQuery.length === 0) return [];
655 return threads.filter((thread) => thread.title.toLowerCase().includes(normalizedQuery));
657​
658export function filterSidebarProjectScopeItems<TItem extends { readonly value: string }>(input: {
659 items: readonly TItem[];
660 activeScopeKey: string | null;
661 query: string;
662 matches: (item: TItem, query: string) => boolean;
663}): readonly TItem[] {
664 const projectItems = input.items.filter((item) => item.value !== "all");
665 const query = input.query.trim();
666 if (query.length > 0) {
667 return projectItems.filter((item) => input.matches(item, query));
668 }
669 return input.activeScopeKey === null ? projectItems : input.items;
671​
672export interface SidebarProjectScopeMenuState {
673 readonly open: boolean;
674 readonly query: string;
676​
677export type SidebarProjectScopeMenuAction =
678 | { readonly type: "query-changed"; readonly query: string }
679 | { readonly type: "open-changed"; readonly open: boolean }
680 | { readonly type: "project-settings-opened" };
681​
682export function reduceSidebarProjectScopeMenuState(
683 state: SidebarProjectScopeMenuState,
684 action: SidebarProjectScopeMenuAction,
685): SidebarProjectScopeMenuState {
686 switch (action.type) {
687 case "query-changed":
688 return { ...state, query: action.query };
689 case "open-changed":
690 return { open: action.open, query: "" };
691 case "project-settings-opened":
692 return { open: false, query: "" };
693 }
695​
696// Settled rows are history, so they order by when the work ENDED, not when
697// the thread was created or last touched.
698export function sortSettledThreadsForSidebar<
699 T extends SettledThreadTimestampInput & { readonly id: string },
700>(threads: readonly T[]): T[] {
701 const timestampMs = (thread: T) => {
702 const timestamp = resolveSettledThreadTimestamp(thread);
703 return timestamp === null ? 0 : Date.parse(timestamp);
704 };
705 return [...threads].toSorted(
706 (left, right) => timestampMs(right) - timestampMs(left) || left.id.localeCompare(right.id),
707 );
709​
710/** The timestamp a working thread's elapsed label counts from: the running
711 turn's start (request time until adoption), falling back to the session's
712 last transition when the turn projection lags behind. Malformed
713 timestamps fall through to the next candidate, not just missing ones. */
714export function resolveWorkingStartedAt(
715 thread: Pick<SidebarThreadSummary, "latestTurn" | "session">,
716): string | null {
717 const turn = thread.latestTurn;
718 if (turn && turn.completedAt === null) {
719 return firstValidTimestamp(turn.startedAt, turn.requestedAt, thread.session?.updatedAt);
720 }
721 return firstValidTimestamp(thread.session?.updatedAt);
723​
724export function formatWorkingDurationLabel(elapsedMs: number): string {
725 const seconds = Number.isFinite(elapsedMs) ? Math.max(0, Math.floor(elapsedMs / 1000)) : 0;
726 if (seconds < 60) return `${seconds}s`;
727 const minutes = Math.floor(seconds / 60);
728 if (minutes < 60) return `${minutes}m`;
729 return `${Math.floor(minutes / 60)}h ${minutes % 60}m`;
731​
732export function resolveThreadStatusPill(input: {
733 thread: ThreadStatusInput;
734}): ThreadStatusPill | null {
735 const { thread } = input;
736​
737 if (thread.hasPendingApprovals) {
738 return {
739 label: "Pending Approval",
740 colorClass: "text-amber-600 dark:text-amber-300/90",
741 dotClass: "bg-amber-500 dark:bg-amber-300/90",
742 pulse: false,
743 };
744 }
745​
746 if (thread.hasPendingUserInput) {
747 return {
748 label: "Awaiting Input",
749 colorClass: "text-indigo-600 dark:text-indigo-300/90",
750 dotClass: "bg-indigo-500 dark:bg-indigo-300/90",
751 pulse: false,
752 };
753 }
754​
755 if (thread.session?.status === "running") {
756 return {
757 label: "Working",
758 colorClass: "text-sky-600 dark:text-sky-300/80",
759 dotClass: "bg-sky-500 dark:bg-sky-300/80",
760 pulse: true,
761 };
762 }
763​
764 if (thread.session?.status === "starting") {
765 return {
766 label: "Connecting",
767 colorClass: "text-sky-600 dark:text-sky-300/80",
768 dotClass: "bg-sky-500 dark:bg-sky-300/80",
769 pulse: true,
770 };
771 }
772​
773 // An actionable plan prompt outranks lingering background work: it needs
774 // the user's decision, while liveness merely reports (review finding).
775 const hasPlanReadyPrompt =
776 !thread.hasPendingUserInput &&
777 thread.interactionMode === "plan" &&
778 isLatestTurnSettled(thread.latestTurn, thread.session) &&
779 thread.hasActionableProposedPlan;
780 if (hasPlanReadyPrompt) {
781 return {
782 label: "Plan Ready",
783 colorClass: "text-violet-600 dark:text-violet-300/90",
784 dotClass: "bg-violet-500 dark:bg-violet-300/90",
785 pulse: false,
786 };
787 }
788​
789 // The turn can settle while native background work runs on. Subagent and
790 // workflow fleets read as plain Working; Monitoring is reserved for watch
791 // loops (a parent agent babysitting a PR, tailing checks) with no other
792 // live work. Same recede treatment as Working per inbox-zero.
793 if (thread.backgroundLiveness === "working") {
794 return {
795 label: "Working",
796 colorClass: "text-sky-600 dark:text-sky-300/80",
797 dotClass: "bg-sky-500 dark:bg-sky-300/80",
798 pulse: true,
799 };
800 }
801​
802 if (thread.backgroundLiveness === "monitoring") {
803 return {
804 label: "Monitoring",
805 colorClass: "text-sky-600 dark:text-sky-300/80",
806 dotClass: "bg-sky-500 dark:bg-sky-300/80",
807 pulse: false,
808 };
809 }
810​
811 if (hasUnseenCompletion(thread)) {
812 return {
813 label: "Completed",
814 colorClass: "text-emerald-600 dark:text-emerald-300/90",
815 dotClass: "bg-emerald-500 dark:bg-emerald-300/90",
816 pulse: false,
817 };
818 }
819​
820 return null;
822​
823export function resolveProjectStatusIndicator(
824 statuses: ReadonlyArray<ThreadStatusPill | null>,
825): ThreadStatusPill | null {
826 let highestPriorityStatus: ThreadStatusPill | null = null;
827​
828 for (const status of statuses) {
829 if (status === null) continue;
830 if (
831 highestPriorityStatus === null ||
832 THREAD_STATUS_PRIORITY[status.label] > THREAD_STATUS_PRIORITY[highestPriorityStatus.label]
833 ) {
834 highestPriorityStatus = status;
835 }
836 }
837​
838 return highestPriorityStatus;
840​
841export function getVisibleThreadsForProject<T extends Pick<Thread, "id">>(input: {
842 threads: readonly T[];
843 activeThreadId: T["id"] | undefined;
844 isThreadListExpanded: boolean;
845 previewLimit: number;
846}): {
847 hasHiddenThreads: boolean;
848 visibleThreads: T[];
849 hiddenThreads: T[];
850} {
851 const { activeThreadId, isThreadListExpanded, previewLimit, threads } = input;
852 const hasHiddenThreads = threads.length > previewLimit;
853​
854 if (!hasHiddenThreads || isThreadListExpanded) {
855 return {
856 hasHiddenThreads,
857 hiddenThreads: [],
858 visibleThreads: [...threads],
859 };
860 }
861​
862 const previewThreads = threads.slice(0, previewLimit);
863 if (!activeThreadId || previewThreads.some((thread) => thread.id === activeThreadId)) {
864 return {
865 hasHiddenThreads: true,
866 hiddenThreads: threads.slice(previewLimit),
867 visibleThreads: previewThreads,
868 };
869 }
870​
871 const activeThread = threads.find((thread) => thread.id === activeThreadId);
872 if (!activeThread) {
873 return {
874 hasHiddenThreads: true,
875 hiddenThreads: threads.slice(previewLimit),
876 visibleThreads: previewThreads,
877 };
878 }
879​
880 const visibleThreadIds = new Set([...previewThreads, activeThread].map((thread) => thread.id));
881​
882 return {
883 hasHiddenThreads: true,
884 hiddenThreads: threads.filter((thread) => !visibleThreadIds.has(thread.id)),
885 visibleThreads: threads.filter((thread) => visibleThreadIds.has(thread.id)),
886 };
888​
889export function getFallbackThreadIdAfterDelete<
890 T extends Pick<Thread, "id" | "projectId" | "createdAt" | "updatedAt"> & ThreadSortInput,
891>(input: {
892 threads: readonly T[];
893 deletedThreadId: T["id"];
894 sortOrder: SidebarThreadSortOrder;
895 deletedThreadIds?: ReadonlySet<T["id"]>;
896}): T["id"] | null {
897 const { deletedThreadId, deletedThreadIds, sortOrder, threads } = input;
898 const deletedThread = threads.find((thread) => thread.id === deletedThreadId);
899 if (!deletedThread) {
900 return null;
901 }
902​
903 return (
904 sortThreads(
905 threads.filter(
906 (thread) =>
907 thread.projectId === deletedThread.projectId &&
908 thread.id !== deletedThreadId &&
909 !deletedThreadIds?.has(thread.id),
910 ),
911 sortOrder,
912 )[0]?.id ?? null
913 );
915export function getProjectSortTimestamp(
916 project: SidebarProject,
917 projectThreads: readonly ThreadSortInput[],
918 sortOrder: Exclude<SidebarProjectSortOrder, "manual">,
919): number {
920 if (projectThreads.length > 0) {
921 return projectThreads.reduce(
922 (latest, thread) => Math.max(latest, getThreadSortTimestamp(thread, sortOrder)),
923 Number.NEGATIVE_INFINITY,
924 );
925 }
926​
927 if (sortOrder === "created_at") {
928 return toSortableTimestamp(project.createdAt) ?? Number.NEGATIVE_INFINITY;
929 }
930 return toSortableTimestamp(project.updatedAt ?? project.createdAt) ?? Number.NEGATIVE_INFINITY;
932​
933function sortProjectsByActivity<TProject extends SidebarProject>(
934 projects: readonly TProject[],
935 sortOrder: SidebarProjectSortOrder,
936 getProjectThreads: (project: TProject) => readonly ThreadSortInput[],
937 compareTies: (left: TProject, right: TProject) => number,
938): TProject[] {
939 if (sortOrder === "manual") {
940 return [...projects];
941 }
942​
943 return [...projects].toSorted((left, right) => {
944 const rightTimestamp = getProjectSortTimestamp(right, getProjectThreads(right), sortOrder);
945 const leftTimestamp = getProjectSortTimestamp(left, getProjectThreads(left), sortOrder);
946 const byTimestamp =
947 rightTimestamp === leftTimestamp ? 0 : rightTimestamp > leftTimestamp ? 1 : -1;
948 return byTimestamp || compareTies(left, right);
949 });
951​
952export function sortProjectsForSidebar<
953 TProject extends SidebarProject,
954 TThread extends Pick<Thread, "projectId" | "createdAt" | "updatedAt"> & ThreadSortInput,
955>(
956 projects: readonly TProject[],
957 threads: readonly TThread[],
958 sortOrder: SidebarProjectSortOrder,
959): TProject[] {
960 const threadsByProjectId = new Map<string, TThread[]>();
961 for (const thread of threads) {
962 const existing = threadsByProjectId.get(thread.projectId) ?? [];
963 existing.push(thread);
964 threadsByProjectId.set(thread.projectId, existing);
965 }
966​
967 return sortProjectsByActivity(
968 projects,
969 sortOrder,
970 (project) => threadsByProjectId.get(project.id) ?? [],
971 (left, right) => left.title.localeCompare(right.title) || left.id.localeCompare(right.id),
972 );
974​
975export function sortLogicalProjectsForSidebar<
976 TProject extends LogicalSidebarProject,
977 TThread extends ScopedSidebarThread,
978>(
979 projects: readonly TProject[],
980 threads: readonly TThread[],
981 sortOrder: SidebarProjectSortOrder,
982): TProject[] {
983 const groupKeyByProjectRef = new Map(
984 projects.flatMap((project) =>
985 project.memberProjectRefs.map(
986 (projectRef) =>
987 [`${projectRef.environmentId}\0${projectRef.projectId}`, project.projectKey] as const,
988 ),
989 ),
990 );
991 const threadsByProjectKey = new Map<string, TThread[]>();
992 for (const thread of threads) {
993 if (thread.archivedAt !== null) continue;
994 const projectKey = groupKeyByProjectRef.get(`${thread.environmentId}\0${thread.projectId}`);
995 if (!projectKey) continue;
996 const existing = threadsByProjectKey.get(projectKey);
997 if (existing) {
998 existing.push(thread);
999 } else {
1000 threadsByProjectKey.set(projectKey, [thread]);
1003​
1004 return sortProjectsByActivity(
1005 projects,
1006 sortOrder,
1007 (project) => threadsByProjectKey.get(project.projectKey) ?? [],
1008 (left, right) =>
1009 left.title.localeCompare(right.title) || left.projectKey.localeCompare(right.projectKey),
1010 );
1012​
1013/**
1014 * Sorts the cross-environment project collection used by landing surfaces.
1015 * Project ids are only unique within an environment, and archived threads
1016 * must not make a project appear recently active.
1017 */
1018export function sortScopedProjectsForSidebar<
1019 TProject extends ScopedSidebarProject,
1020 TThread extends ScopedSidebarThread,
1022 projects: readonly TProject[],
1023 threads: readonly TThread[],
1024 sortOrder: SidebarProjectSortOrder,
1025): TProject[] {
1026 const scopedKey = (environmentId: string, projectId: string) =>
1027 `${environmentId}\u0000${projectId}`;
1028 const threadsByProject = new Map<string, TThread[]>();
1029 for (const thread of threads) {
1030 if (thread.archivedAt !== null) {
1031 continue;
1033 const key = scopedKey(thread.environmentId, thread.projectId);
1034 const existing = threadsByProject.get(key) ?? [];
1035 existing.push(thread);
1036 threadsByProject.set(key, existing);
1038​
1039 return sortProjectsByActivity(
1040 projects,
1041 sortOrder,
1042 (project) => threadsByProject.get(scopedKey(project.environmentId, project.id)) ?? [],
1043 (left, right) =>
1044 left.title.localeCompare(right.title) ||
1045 left.environmentId.localeCompare(right.environmentId) ||
1046 left.id.localeCompare(right.id),
1047 );