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

Sidebar.logic.ts

1,458 lines49.2 KB

1import { resolveThreadWorkingStartedAt } from "@t3tools/client-runtime/state/models";
2import { backgroundWorkHoldsCompletion } from "@t3tools/shared/orchestrationV2PendingBackgroundWork";
3import { threadPullRequestSearchTerms } from "@t3tools/shared/threadPullRequests";
4import * as React from "react";
5import {
6 isAtomCommandInterrupted,
7 type AtomCommandResult,
8} from "@t3tools/client-runtime/state/runtime";
9import { defaultAnimateLayoutChanges, type AnimateLayoutChanges } from "@dnd-kit/sortable";
10import { threadSearchMatchKey } from "@t3tools/client-runtime/state/thread-search";
11import type { ContextMenuItem, EnvironmentId, ThreadId } from "@t3tools/contracts";
12import type { SidebarProjectSortOrder, SidebarThreadSortOrder } from "@t3tools/contracts/settings";
13import type { AsyncResult } from "effect/reactivity";
14import { planPinnedReorder } from "@t3tools/client-runtime/state/thread-sort";
15import {
16 effectiveSnoozed,
17 type ThreadSnoozeShell,
18} from "@t3tools/client-runtime/state/thread-settled";
19import {
20 getThreadSortTimestamp,
21 sortThreads,
22 toSortableTimestamp,
23 type ThreadSortInput,
24} from "../lib/threadSort";
25import type { SidebarThreadSummary, Thread } from "../types";
26import { cn, normalizeSearchText } from "../lib/utils";
27import { isLatestRunSettled } from "../session-logic";
28import { resolveServerBackedAppStageLabel } from "../branding.logic";
29​
30export function shouldNavigateAfterThreadPark(input: {
31 readonly threadKey: string;
32 readonly currentThreadKey: string | null;
33 readonly action: "settle" | "snooze";
34 readonly now: string;
35 readonly thread: (ThreadSnoozeShell & Pick<SidebarThreadSummary, "settledOverride">) | null;
36}): boolean {
37 return (
38 input.threadKey === input.currentThreadKey &&
39 input.thread !== null &&
40 (input.action === "settle"
41 ? input.thread.settledOverride === "settled"
42 : effectiveSnoozed(input.thread, { now: input.now }))
43 );
45​
46const THREAD_SELECTION_SAFE_SELECTOR = "[data-thread-item], [data-thread-selection-safe]";
47export const THREAD_JUMP_HINT_SHOW_DELAY_MS = 200;
48​
49export function resolveSidebarRowAccessibility(input: {
50 readonly title: string;
51 readonly statusLabel: string | null;
52 readonly projectDisplayName: string | null;
53 readonly isActive: boolean;
54}): { readonly label: string; readonly current: "page" | undefined } {
55 return {
56 // The title is the row's identity and must lead when users scan tasks.
57 // Only static context belongs here; nested action labels remain separate controls.
58 label: [input.title, input.statusLabel, input.projectDisplayName].filter(Boolean).join(", "),
59 current: input.isActive ? "page" : undefined,
60 };
62​
63// Visible sidebar rows are prewarmed into the thread-detail cache so opening a
64// nearby thread usually reuses an already-hot subscription. Each prewarmed
65// thread holds a live, fully hydrated detail subscription (all messages and
66// activities, growing as agents work) for as long as the row stays visible,
67// so this limit is a direct renderer-heap and server-load multiplier — keep
68// it small; cold opens still render instantly from the cached snapshot.
69const SIDEBAR_THREAD_PREWARM_LIMIT = 3;
70// A small buffer keeps the next few rows warm without leasing every row that
71// content-visibility leaves mounted below the scroll viewport.
72const SIDEBAR_ROW_SUBSCRIPTION_OVERSCAN_PX = 160;
73​
74export function useSidebarRowSubscriptionLease(isActive: boolean): {
75 readonly leaseLiveStatus: boolean;
76 readonly rowRef: React.Dispatch<React.SetStateAction<HTMLElement | null>>;
77} {
78 const [row, setRow] = React.useState<HTMLElement | null>(null);
79 const [isNearViewport, setIsNearViewport] = React.useState(isActive);
80​
81 React.useEffect(() => {
82 if (isActive) {
83 setIsNearViewport(true);
84 return;
85 }
86 if (row === null) return;
87 if (typeof IntersectionObserver === "undefined") {
88 setIsNearViewport(true);
89 return;
90 }
91​
92 const scrollRoot = row.closest<HTMLElement>('[data-slot="scroll-area-viewport"]');
93 const observer = new IntersectionObserver(
94 ([entry]) => setIsNearViewport(entry?.isIntersecting === true),
95 {
96 root: scrollRoot,
97 rootMargin: `${SIDEBAR_ROW_SUBSCRIPTION_OVERSCAN_PX}px 0px`,
98 },
99 );
100 observer.observe(row);
101 return () => observer.disconnect();
102 }, [isActive, row]);
103​
104 return {
105 leaseLiveStatus: isActive || isNearViewport,
106 rowRef: setRow,
107 };
109​
110// A row keeps the last live value it rendered so a released lease never
111// blanks its badge. The value is bound to `key`, so a different worktree or
112// linked pull request cannot reuse the previous one.
113export function useRetainedValue<T>(key: string | null, value: T | null): T | null {
114 const retained = React.useRef<{ readonly key: string; readonly value: T } | null>(null);
115 if (key !== null && value !== null) {
116 retained.current = { key, value };
117 }
118 if (value !== null) return value;
119 return key !== null && retained.current?.key === key ? retained.current.value : null;
121​
122// Sidebar.motion handles ordinary section changes. Sortable transforms own
123// dragging; replaying their committed DOM order would animate the drop twice.
124export const animateSidebarLayoutChanges: AnimateLayoutChanges = (args) =>
125 args.isSorting ? defaultAnimateLayoutChanges(args) : false;
126​
127// Rows and section markers share one sortable list. The separators resolve
128// the lifecycle action; Sidebar.drag previews the resulting layout. Pinned
129// and active threads keep the dragged position; settled threads use time
130// order. Snoozed rows can leave the shelf, but dropping into it is not
131// supported because snoozing requires a wake time. The Working shelf (beta)
132// follows live status, so it is neither a drag source nor a destination.
133​
134export type SidebarSection = "pinned" | "active" | "working" | "snoozed" | "settled";
135​
136/** Resolve the shelf a visible thread belongs to. Snooze is temporary and
137 * wins until its wake boundary; settlement then wins over a stale pin. */
138export function resolveSidebarThreadSection(input: {
139 readonly snoozed: boolean;
140 readonly settled: boolean;
141 readonly pinned: boolean;
142}): SidebarSection {
143 if (input.snoozed) return "snoozed";
144 if (input.settled) return "settled";
145 if (input.pinned) return "pinned";
146 return "active";
148​
149/** Sortable ids: thread rows use their scoped key; structural items use a
150 colon-free prefix: scoped thread keys always contain a colon. */
151const SIDEBAR_MARKER_PREFIX = "sidebar-marker-";
152​
153export type SidebarListMarker =
154 /** The top boundary is also a landing target when there are no pins. */
155 | "pinned-header"
156 /** Stand-in rows so an empty section has somewhere for the gap to open. */
157 | "active-placeholder"
158 | "settled-placeholder"
159 /** The boundary between pinned and active rows. */
160 | "pinned-divider"
161 | "working-header"
162 | "snoozed-header"
163 | "settled-header";
164​
165export function sidebarMarkerId(marker: SidebarListMarker): string {
166 return `${SIDEBAR_MARKER_PREFIX}${marker}`;
168​
169export type SidebarListItem =
170 | { readonly kind: "thread"; readonly key: string; readonly section: SidebarSection }
171 | { readonly kind: "marker"; readonly marker: SidebarListMarker };
172​
173export function sidebarListItemId(item: SidebarListItem): string {
174 return item.kind === "thread" ? item.key : sidebarMarkerId(item.marker);
176​
177/** The section a slot belongs to, read off the markers around it: from
178 the top down, everything before the pinned divider is pinned, then the
179 inbox until the first shelf header, each shelf until the next header,
180 then settled. */
181function sectionAtSidebarSlot(items: readonly SidebarListItem[], index: number): SidebarSection {
182 let section: SidebarSection = "pinned";
183 for (let i = 0; i < index && i < items.length; i += 1) {
184 const item = items[i]!;
185 if (item.kind !== "marker") continue;
186 if (item.marker === "pinned-divider") section = "active";
187 else if (item.marker === "working-header") section = "working";
188 else if (item.marker === "snoozed-header") section = "snoozed";
189 else if (item.marker === "settled-header") section = "settled";
190 }
191 return section;
193​
194/** Resolve the destination section and manual order from an arrayMove across
195 * the separators. The working and snoozed shelves are never destinations. */
196export type SidebarDropTarget = {
197 readonly section: "pinned" | "active" | "settled";
198 readonly pinnedOrder: readonly string[];
199 readonly activeOrder: readonly string[];
200};
201​
202export function resolveSidebarDropTarget(
203 items: readonly SidebarListItem[],
204 activeKey: string,
205 overId: string,
206): SidebarDropTarget | null {
207 const activeIndex = items.findIndex((item) => sidebarListItemId(item) === activeKey);
208 const overIndex = items.findIndex((item) => sidebarListItemId(item) === overId);
209 if (activeIndex === -1 || overIndex === -1 || items[activeIndex]?.kind !== "thread") return null;
210 const moved = items.filter((_, index) => index !== activeIndex);
211 moved.splice(overIndex, 0, items[activeIndex]!);
212 const section = sectionAtSidebarSlot(moved, overIndex);
213 if (section === "working" || section === "snoozed") return null;
214 const pinnedOrder: string[] = [];
215 const activeOrder: string[] = [];
216 let currentSection: SidebarSection = "pinned";
217 for (const item of moved) {
218 if (item.kind === "marker") {
219 if (item.marker === "pinned-divider") currentSection = "active";
220 else if (
221 item.marker === "working-header" ||
222 item.marker === "snoozed-header" ||
223 item.marker === "settled-header"
224 )
225 break;
226 } else if (currentSection === "pinned") pinnedOrder.push(item.key);
227 else activeOrder.push(item.key);
228 }
229 return { section, pinnedOrder, activeOrder };
231​
232export type SidebarThreadDropPlan =
233 | { readonly kind: "none" }
234 /** Within the pinned block: the existing key writes. */
235 | {
236 readonly kind: "reorder-pinned";
237 readonly order: readonly string[];
238 readonly assignments: ReadonlyArray<{ readonly id: string; readonly orderKey: string }>;
239 }
240 /** From another section into the pinned block. Fresh pins take `orderKey`
241 on the pin command. `extraAssignments` land afterward, including the
242 moved row when it was already pinned beneath a snooze. */
243 | {
244 readonly kind: "pin";
245 readonly order: readonly string[];
246 readonly orderKey: string | undefined;
247 readonly extraAssignments: ReadonlyArray<{ readonly id: string; readonly orderKey: string }>;
248 }
249 | {
250 readonly kind: "move-active";
251 /** Null when the inbox is time-ordered: the drop has no placement. */
252 readonly order: readonly string[] | null;
253 readonly assignments: ReadonlyArray<{ readonly id: string; readonly orderKey: string }>;
254 readonly unpin: boolean;
255 readonly unsettle: boolean;
256 readonly unsnooze: boolean;
257 }
258 | { readonly kind: "settle" };
259​
260/** What dropping in `to` does to a thread lifted from `from`, for the badge
261 on the lifted row. Null while reordering inside one section and for the
262 working and snoozed shelves, which cannot be drop targets. */
263export type SidebarDropVerb = "pin" | "unpin" | "settle" | "unsettle" | "wake";
264​
265export function resolveSidebarDropVerb(
266 from: SidebarSection,
267 to: SidebarSection | null,
268): SidebarDropVerb | null {
269 if (to === null || to === from || to === "working" || to === "snoozed") return null;
270 if (to === "pinned") return "pin";
271 if (to === "settled") return "settle";
272 if (from === "pinned") return "unpin";
273 if (from === "settled") return "unsettle";
274 return "wake";
276​
277/** Eligible rows between the pressed action and the pointer, in sidebar order. */
278export function resolveSidebarSweepKeys(
279 orderedKeys: readonly string[],
280 originKey: string,
281 targetKey: string,
282 canApply: (key: string) => boolean,
283): string[] {
284 const origin = orderedKeys.indexOf(originKey);
285 const target = orderedKeys.indexOf(targetKey);
286 if (origin === -1 || target === -1) return [];
287 return orderedKeys.slice(Math.min(origin, target), Math.max(origin, target) + 1).filter(canApply);
289​
290/** The thread row at a pointer height, clamped to the rows visible in the
291 sidebar's scroll viewport. A gap between rows resolves to the row above
292 it. Rows carry their key in data-thread-item, which departing motion
293 clones drop. */
294export function sidebarThreadKeyAtY(list: HTMLElement, y: number): string | null {
295 const viewport = list.closest('[data-slot="scroll-area-viewport"]')?.getBoundingClientRect();
296 const visibleY = viewport ? Math.min(Math.max(y, viewport.top), viewport.bottom - 1) : y;
297 let key: string | null = null;
298 for (const row of list.querySelectorAll<HTMLElement>("li[data-thread-item]")) {
299 if (key !== null && row.getBoundingClientRect().top > visibleY) break;
300 key = row.dataset.threadItem ?? null;
301 }
302 return key;
304​
305export function planSidebarThreadDrop(input: {
306 readonly activeKey: string;
307 readonly activeSection: SidebarSection;
308 /** Snoozed threads can retain pinning and settlement beneath the shelf. */
309 readonly activePinned?: boolean;
310 readonly activeSettled?: boolean;
311 readonly supportsSettlement?: boolean;
312 readonly target: SidebarDropTarget;
313 /** All pinned keys in displayed order before the drop. */
314 readonly pinnedOrder: readonly string[];
315 readonly pinnedKeysById: ReadonlyMap<string, string | null | undefined>;
316 readonly reorderableKeys?: ReadonlySet<string>;
317 readonly activeOrder: readonly string[];
318 readonly activeKeysById: ReadonlyMap<string, string | null | undefined>;
319 readonly activeReorderableKeys?: ReadonlySet<string>;
320 /** Working beta: the inbox sorts by time, so drops only change lifecycle. */
321 readonly activeTimeOrdered?: boolean;
322}): SidebarThreadDropPlan {
323 const {
324 activeKey,
325 activeSection,
326 activePinned = activeSection === "pinned",
327 activeSettled = activeSection === "settled",
328 target,
329 pinnedOrder,
330 pinnedKeysById,
331 reorderableKeys,
332 activeOrder,
333 activeKeysById,
334 activeReorderableKeys,
335 } = input;
336 if (input.supportsSettlement === false && (target.section === "settled" || activeSettled)) {
337 return { kind: "none" };
338 }
339 // Rows whose server cannot store an order (an older server, or a machine
340 // that is offline) are never written. Keyless ones sort outside the keyed
341 // run, so they leave the plan; keyed ones stay as bounds. Before, one keyless row
342 // refused every drop that needed fresh keys for its neighbors.
343 const arrange = (
344 order: readonly string[],
345 keysById: ReadonlyMap<string, string | null | undefined>,
346 writable: ReadonlySet<string> | undefined,
347 ) => {
348 if (!writable) return planPinnedReorder({ orderedIds: order, keysById, movedId: activeKey });
349 if (!writable.has(activeKey)) return null;
350 const assignments = planPinnedReorder({
351 orderedIds: order.filter((key) => writable.has(key) || keysById.get(key) != null),
352 keysById,
353 movedId: activeKey,
354 });
355 return assignments.every(({ id }) => writable.has(id)) ? assignments : null;
356 };
357 switch (target.section) {
358 case "active": {
359 // Like the settled tail: threads can enter a time-ordered inbox, but
360 // not be arranged inside it.
361 if (input.activeTimeOrdered) {
362 return activeSection === "active"
363 ? { kind: "none" }
364 : {
365 kind: "move-active",
366 order: null,
367 assignments: [],
368 unpin: activePinned,
369 unsettle: activeSettled,
370 unsnooze: activeSection === "snoozed",
371 };
372 }
373 const order = target.activeOrder;
374 if (
375 activeSection === "active" &&
376 order.length === activeOrder.length &&
377 order.every((key, index) => key === activeOrder[index])
378 ) {
379 return { kind: "none" };
380 }
381 const assignments = arrange(order, activeKeysById, activeReorderableKeys);
382 if (assignments === null) return { kind: "none" };
383 return {
384 kind: "move-active",
385 order,
386 assignments,
387 unpin: activePinned,
388 unsettle: activeSettled,
389 unsnooze: activeSection === "snoozed",
390 };
391 }
392 case "settled":
393 return activeSection === "settled" ? { kind: "none" } : { kind: "settle" };
394 case "pinned": {
395 const order = target.pinnedOrder;
396 // Dropped back where it started: nothing to write.
397 if (
398 activeSection === "pinned" &&
399 order.length === pinnedOrder.length &&
400 order.every((key, index) => key === pinnedOrder[index])
401 ) {
402 return { kind: "none" };
403 }
404 const assignments = arrange(order, pinnedKeysById, reorderableKeys);
405 if (assignments === null) return { kind: "none" };
406 if (activeSection === "pinned") {
407 return assignments.length === 0
408 ? { kind: "none" }
409 : { kind: "reorder-pinned", order, assignments };
410 }
411 return {
412 kind: "pin",
413 order,
414 orderKey: assignments.find((assignment) => assignment.id === activeKey)?.orderKey,
415 extraAssignments: activePinned
416 ? assignments
417 : assignments.filter((assignment) => assignment.id !== activeKey),
418 };
419 }
420 }
422​
423/** Project a drop's lifecycle fields before sorting its destination. Reusing
424 the server's re-entry rules keeps the preview in place when events arrive. */
425export function applySidebarThreadDrop<
426 T extends Pick<
427 SidebarThreadSummary,
428 | "pinnedAt"
429 | "pinOrderKey"
430 | "activeOrderKey"
431 | "snoozedAt"
432 | "snoozedUntil"
433 | "settledAt"
434 | "settledOverride"
435 | "unsettledAt"
436 >,
437>(thread: T, section: "pinned" | "active" | "settled", now: string, orderKey?: string): T {
438 const wasSettled = thread.settledOverride === "settled";
439 const awake = { ...thread, snoozedAt: null, snoozedUntil: null };
440 if (section === "settled") {
441 return {
442 ...awake,
443 pinnedAt: null,
444 pinOrderKey: null,
445 activeOrderKey: null,
446 settledOverride: "settled",
447 settledAt: wasSettled ? (thread.settledAt ?? now) : now,
448 unsettledAt: null,
449 };
450 }
451 const resumed = wasSettled
452 ? { ...awake, settledOverride: "active" as const, settledAt: null, unsettledAt: now }
453 : awake;
454 return {
455 ...resumed,
456 pinnedAt: section === "pinned" ? (thread.pinnedAt ?? now) : null,
457 pinOrderKey: section === "pinned" ? (orderKey ?? thread.pinOrderKey) : null,
458 ...(section === "active" && orderKey !== undefined ? { activeOrderKey: orderKey } : {}),
459 };
461​
462type SidebarProject = {
463 id: string;
464 title: string;
465 createdAt?: string | undefined;
466 updatedAt?: string | undefined;
467};
468​
469type ScopedSidebarProject = SidebarProject & {
470 environmentId: string;
471};
472​
473type ScopedSidebarThread = ThreadSortInput & {
474 environmentId: string;
475 projectId: string;
476 archivedAt: string | null;
477};
478​
479type LogicalSidebarProject = SidebarProject & {
480 projectKey: string;
481 memberProjectRefs: readonly {
482 environmentId: string;
483 projectId: string;
484 }[];
485};
486​
487export type ThreadTraversalDirection = "previous" | "next";
488​
489/**
490 * Shared-worktree checks must exclude only successful deletions, never the
491 * whole batch. A null result skips an entry that the caller can no longer find.
492 */
493export async function deleteSelectedThreadEntries<
494 TEntry extends { readonly threadKey: string },
495>(input: {
496 entries: readonly TEntry[];
497 delete: (
498 entry: TEntry,
499 deletedThreadKeys: ReadonlySet<string>,
500 ) => Promise<AtomCommandResult<unknown, unknown> | null>;
501}) {
502 const deletedThreadKeys = new Set<string>();
503 let firstFailure: AsyncResult.Failure<unknown, unknown> | null = null;
504​
505 for (const entry of input.entries) {
506 const result = await input.delete(entry, deletedThreadKeys);
507 if (result === null) continue;
508 if (result._tag === "Failure") {
509 if (isAtomCommandInterrupted(result)) break;
510 firstFailure ??= result;
511 continue;
512 }
513 deletedThreadKeys.add(entry.threadKey);
514 }
515​
516 return { deletedThreadKeys, firstFailure };
518​
519export async function archiveSelectedThreadEntries<
520 TEntry extends { readonly threadKey: string },
521 TResult extends { readonly _tag: "Success" | "Failure" },
522>(input: {
523 entries: readonly TEntry[];
524 archive: (entry: TEntry, onArchived: () => void) => Promise<TResult>;
525}): Promise<{
526 archivedThreadKeys: readonly string[];
527 mutationFailure: Extract<TResult, { readonly _tag: "Failure" }> | null;
528 followupFailures: readonly Extract<TResult, { readonly _tag: "Failure" }>[];
529}> {
530 const archivedThreadKeys: string[] = [];
531 const followupFailures: Extract<TResult, { readonly _tag: "Failure" }>[] = [];
532​
533 for (const entry of input.entries) {
534 let didArchive = false;
535 const result = await input.archive(entry, () => {
536 didArchive = true;
537 });
538 if (didArchive || result._tag === "Success") archivedThreadKeys.push(entry.threadKey);
539 if (result._tag === "Success") continue;
540 const failure = result as Extract<TResult, { readonly _tag: "Failure" }>;
541 if (didArchive) {
542 followupFailures.push(failure);
543 continue;
544 }
545 return { archivedThreadKeys, mutationFailure: failure, followupFailures };
546 }
547​
548 return { archivedThreadKeys, mutationFailure: null, followupFailures };
550​
551export function buildMultiSelectThreadContextMenuItems(input: {
552 count: number;
553 hasRunningThread: boolean;
554}): readonly ContextMenuItem<"mark-unread" | "archive" | "delete">[] {
555 return [
556 { id: "mark-unread", label: `Mark unread (${input.count})` },
557 {
558 id: "archive",
559 label: `Archive (${input.count})`,
560 disabled: input.hasRunningThread,
561 },
562 { id: "delete", label: `Delete (${input.count})`, destructive: true },
563 ];
565​
566export function isSidebarSubagentThread(thread: Pick<SidebarThreadSummary, "lineage">): boolean {
567 return thread.lineage.relationshipToParent === "subagent";
569​
570export function filterSidebarV2VisibleThreads<
571 T extends Pick<SidebarThreadSummary, "archivedAt" | "lineage"> & {
572 environmentId: string;
573 projectId: string;
574 },
575>(threads: readonly T[], scopedProjectKeys: ReadonlySet<string> | null): T[] {
576 return threads.filter(
577 (thread) =>
578 thread.archivedAt === null &&
579 !isSidebarSubagentThread(thread) &&
580 (scopedProjectKeys === null ||
581 scopedProjectKeys.has(`${thread.environmentId}:${thread.projectId}`)),
582 );
584​
585export function getSidebarForkParentThreadId(
586 thread: Pick<SidebarThreadSummary, "forkedFrom" | "lineage">,
587) {
588 if (thread.lineage.relationshipToParent !== "fork") {
589 return null;
590 }
591 return thread.forkedFrom?.type === "run"
592 ? thread.forkedFrom.threadId
593 : thread.lineage.parentThreadId;
595​
596export function buildBulkTitleRegenerationContextMenuItem(input: {
597 supportedCount: number;
598 actionableCount: number;
599}): ContextMenuItem<"regenerate-title"> | null {
600 if (input.supportedCount === 0) return null;
601 if (input.actionableCount === 0) {
602 return {
603 id: "regenerate-title",
604 label: `Regenerating… (${input.supportedCount})`,
605 disabled: true,
606 };
607 }
608 return {
609 id: "regenerate-title",
610 label: `Regenerate titles (${input.actionableCount})`,
611 };
613​
614/**
615 * Bulk unpin follows the same "count only what the action will touch" rule
616 * as title regeneration: on a mixed selection the label counts the pinned
617 * rows alone, and the item disappears when nothing selected is pinned.
618 */
619export function buildBulkUnpinContextMenuItem(input: {
620 pinnedCount: number;
621}): ContextMenuItem<"unpin"> | null {
622 if (input.pinnedCount === 0) return null;
623 return { id: "unpin", label: `Unpin (${input.pinnedCount})` };
625​
626export interface ThreadStatusPill {
627 label:
628 | "Working"
629 | "Connecting"
630 | "Completed"
631 | "Pending Approval"
632 | "Awaiting Input"
633 | "Waiting"
634 | "Plan Ready";
635 colorClass: string;
636 dotClass: string;
637 pulse: boolean;
639​
640const THREAD_STATUS_PRIORITY: Record<ThreadStatusPill["label"], number> = {
641 "Pending Approval": 5,
642 "Awaiting Input": 4,
643 Working: 3,
644 Connecting: 3,
645 Waiting: 2.5,
646 "Plan Ready": 2,
647 Completed: 1,
648};
649​
650type ThreadStatusInput = Pick<
651 SidebarThreadSummary,
652 | "hasActionableProposedPlan"
653 | "hasPendingApprovals"
654 | "hasPendingUserInput"
655 | "pendingSubagentRequest"
656 | "interactionMode"
657 | "latestRun"
658 | "runtime"
659> & {
660 lastVisitedAt?: string | null | undefined;
661 pendingBackgroundTasks?: SidebarThreadSummary["pendingBackgroundTasks"] | undefined;
662};
663​
664export interface ThreadJumpHintVisibilityController {
665 sync: (shouldShow: boolean) => void;
666 dispose: () => void;
668​
669export function resolveSidebarStageBadgeLabel(input: {
670 primaryServerVersion: string | null | undefined;
671 fallbackStageLabel: string;
672}): string {
673 return resolveServerBackedAppStageLabel(input);
675​
676export function createThreadJumpHintVisibilityController(input: {
677 delayMs: number;
678 onVisibilityChange: (visible: boolean) => void;
679 setTimeoutFn?: typeof globalThis.setTimeout;
680 clearTimeoutFn?: typeof globalThis.clearTimeout;
681}): ThreadJumpHintVisibilityController {
682 const setTimeoutFn = input.setTimeoutFn ?? globalThis.setTimeout;
683 const clearTimeoutFn = input.clearTimeoutFn ?? globalThis.clearTimeout;
684 let isVisible = false;
685 let timeoutId: NodeJS.Timeout | null = null;
686​
687 const clearPendingShow = () => {
688 if (timeoutId === null) {
689 return;
690 }
691 clearTimeoutFn(timeoutId);
692 timeoutId = null;
693 };
694​
695 return {
696 sync: (shouldShow) => {
697 if (!shouldShow) {
698 clearPendingShow();
699 if (isVisible) {
700 isVisible = false;
701 input.onVisibilityChange(false);
702 }
703 return;
704 }
705​
706 if (isVisible || timeoutId !== null) {
707 return;
708 }
709​
710 timeoutId = setTimeoutFn(() => {
711 timeoutId = null;
712 isVisible = true;
713 input.onVisibilityChange(true);
714 }, input.delayMs);
715 },
716 dispose: () => {
717 clearPendingShow();
718 },
719 };
721​
722export function useThreadJumpHintVisibility(): {
723 showThreadJumpHints: boolean;
724 updateThreadJumpHintsVisibility: (shouldShow: boolean) => void;
725} {
726 const [showThreadJumpHints, setShowThreadJumpHints] = React.useState(false);
727 const controllerRef = React.useRef<ThreadJumpHintVisibilityController | null>(null);
728​
729 React.useEffect(() => {
730 const controller = createThreadJumpHintVisibilityController({
731 delayMs: THREAD_JUMP_HINT_SHOW_DELAY_MS,
732 onVisibilityChange: (visible) => {
733 setShowThreadJumpHints(visible);
734 },
735 setTimeoutFn: window.setTimeout.bind(window),
736 clearTimeoutFn: window.clearTimeout.bind(window),
737 });
738 controllerRef.current = controller;
739​
740 return () => {
741 controller.dispose();
742 controllerRef.current = null;
743 };
744 }, []);
745​
746 const updateThreadJumpHintsVisibility = React.useCallback((shouldShow: boolean) => {
747 controllerRef.current?.sync(shouldShow);
748 }, []);
749​
750 return {
751 showThreadJumpHints,
752 updateThreadJumpHintsVisibility,
753 };
755​
756/**
757 * Effective visited watermark for a thread. Servers with visited tracking
758 * project `lastVisitedAt` on the shell and are authoritative — that value is
759 * shared across every device connected to the environment. Pre-tracking
760 * servers omit the field, and the browser's locally persisted watermark keeps
761 * working as before.
762 */
763export function resolveThreadLastVisitedAt(
764 serverLastVisitedAt: string | null | undefined,
765 localLastVisitedAt: string | undefined,
766): string | undefined {
767 // When the server tracks visits it is authoritative — including explicit
768 // rewinds from mark-unread, which a newer browser-local watermark must not
769 // mask. The local value only carries servers without visited tracking.
770 if (serverLastVisitedAt === undefined) return localLastVisitedAt;
771 return serverLastVisitedAt ?? undefined;
773​
774export function hasUnseenCompletion(thread: ThreadStatusInput): boolean {
775 if (!thread.latestRun?.completedAt) return false;
776 const completedAt = Date.parse(thread.latestRun.completedAt);
777 if (Number.isNaN(completedAt)) return false;
778 if (!thread.lastVisitedAt) return false;
779​
780 const lastVisitedAt = Date.parse(thread.lastVisitedAt);
781 if (Number.isNaN(lastVisitedAt)) return true;
782 return completedAt > lastVisitedAt;
784​
785export function shouldClearThreadSelectionOnMouseDown(target: HTMLElement | null): boolean {
786 if (target === null) return true;
787 return !target.closest(THREAD_SELECTION_SAFE_SELECTOR);
789​
790// A double-click dispatches two `click` events before `dblclick`: the first has
791// `detail === 1`, the second `detail === 2`. The second click must not run the
792// row's single-click navigation, otherwise double-click-to-rename would also
793// navigate. `MouseEvent.detail` is 0 for synthetic/keyboard activations, which
794// still count as a normal single activation.
795export function isTrailingDoubleClick(detail: number): boolean {
796 return detail > 1;
798​
799function nodeClosest(node: object | null, selector: string): unknown {
800 if (node === null || !("closest" in node) || typeof node.closest !== "function") return null;
801 return node.closest(selector);
803​
804/** Clicks on a nested link keep the link's meaning. The row must not treat them as multi-select. */
805export function isSidebarNestedLinkClick(target: EventTarget | null): boolean {
806 if (target == null || typeof target !== "object") return false;
807 if (nodeClosest(target, "a[href]") !== null) return true;
808 const parent =
809 "parentElement" in target &&
810 target.parentElement !== null &&
811 typeof target.parentElement === "object"
812 ? target.parentElement
813 : null;
814 return nodeClosest(parent, "a[href]") !== null;
816​
817// Shift+click on the new thread button creates directly in the current
818// project, skipping the command palette's project picker. With a single
819// project there is nothing to pick, so a plain click already creates
820// immediately and the modifier changes nothing.
821export function shouldCreateNewThreadInCurrentProject(
822 shiftKey: boolean,
823 projectGroupCount: number,
824): boolean {
825 return shiftKey || projectGroupCount <= 1;
827​
828export function orderItemsByPreferredIds<TItem, TId>(input: {
829 items: readonly TItem[];
830 preferredIds: readonly TId[];
831 getId: (item: TItem) => TId;
832 getPreferenceIds?: (item: TItem) => readonly TId[];
833}): TItem[] {
834 const { getId, getPreferenceIds, items, preferredIds } = input;
835 if (preferredIds.length === 0) {
836 return [...items];
837 }
838​
839 const indexesByPreferenceId = new Map<TId, number[]>();
840 for (const [index, item] of items.entries()) {
841 const preferenceIds = getPreferenceIds?.(item) ?? [getId(item)];
842 for (const preferenceId of new Set(preferenceIds)) {
843 const indexes = indexesByPreferenceId.get(preferenceId);
844 if (indexes) {
845 indexes.push(index);
846 } else {
847 indexesByPreferenceId.set(preferenceId, [index]);
848 }
849 }
850 }
851​
852 const emittedIndexes = new Set<number>();
853 const ordered = preferredIds.flatMap((id) => {
854 const index = indexesByPreferenceId
855 .get(id)
856 ?.find((candidate) => !emittedIndexes.has(candidate));
857 if (index === undefined) {
858 return [];
859 }
860 emittedIndexes.add(index);
861 return [items[index]!];
862 });
863 const remaining = items.filter((_, index) => !emittedIndexes.has(index));
864 return [...ordered, ...remaining];
866​
867export function getSidebarThreadIdsToPrewarm<TThreadId>(
868 visibleThreadIds: readonly TThreadId[],
869 limit = SIDEBAR_THREAD_PREWARM_LIMIT,
870): TThreadId[] {
871 return visibleThreadIds.slice(0, Math.max(0, limit));
873​
874export function resolveAdjacentThreadId<T>(input: {
875 threadIds: readonly T[];
876 currentThreadId: T | null;
877 direction: ThreadTraversalDirection;
878}): T | null {
879 const { currentThreadId, direction, threadIds } = input;
880​
881 if (threadIds.length === 0) {
882 return null;
883 }
884​
885 if (currentThreadId === null) {
886 return direction === "previous" ? (threadIds.at(-1) ?? null) : (threadIds[0] ?? null);
887 }
888​
889 const currentIndex = threadIds.indexOf(currentThreadId);
890 if (currentIndex === -1) {
891 return null;
892 }
893​
894 if (direction === "previous") {
895 return currentIndex > 0 ? (threadIds[currentIndex - 1] ?? null) : null;
896 }
897​
898 return currentIndex < threadIds.length - 1 ? (threadIds[currentIndex + 1] ?? null) : null;
900​
901export function isContextMenuPointerDown(input: {
902 button: number;
903 ctrlKey: boolean;
904 isMac: boolean;
905}): boolean {
906 if (input.button === 2) return true;
907 return input.isMac && input.button === 0 && input.ctrlKey;
909​
910export function resolveThreadRowClassName(input: {
911 isActive: boolean;
912 isSelected: boolean;
913}): string {
914 const baseClassName =
915 "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";
916​
917 if (input.isSelected && input.isActive) {
918 return cn(
919 baseClassName,
920 "bg-sidebar-row-active text-sidebar-foreground font-medium hover:bg-sidebar-row-active hover:text-sidebar-foreground",
921 );
922 }
923​
924 if (input.isSelected) {
925 return cn(
926 baseClassName,
927 "bg-sidebar-row-selected text-sidebar-foreground hover:bg-sidebar-row-active hover:text-sidebar-foreground",
928 );
929 }
930​
931 if (input.isActive) {
932 return cn(
933 baseClassName,
934 "bg-sidebar-row-active text-sidebar-foreground font-medium hover:bg-sidebar-row-active hover:text-sidebar-foreground",
935 );
936 }
937​
938 return cn(
939 baseClassName,
940 "text-sidebar-muted-foreground/80 hover:bg-sidebar-row-hover hover:text-sidebar-foreground",
941 );
943​
944// ── Sidebar v2 status model ─────────────────────────────────────────
945// Six visual states, three colors: color is reserved for "act now"
946// (approval), "in motion" (working), and "broken" (failed). Ready is the
947// unlabeled resting state — the agent stopped and is waiting on the user,
948// whether it finished, asked a question, or proposed a plan. Waiting
949// (runtime status "idle") is the agent stopped with background work that will
950// wake it (subagents, monitors): not the user's turn yet, so it renders grey
951// like working, not as a false Done. Commands it left running, such as a dev
952// server, do not hold the thread; it reads as ready.
953// Unread completion is tracked separately: it describes whether a ready
954// thread needs attention, not what the thread is currently doing.
955export type SidebarThreadStatus =
956 | "approval"
957 | "input"
958 | "working"
959 | "waiting"
960 | "failed"
961 | "limited"
962 | "ready";
963​
964export function shouldRecedeSidebarThread(input: {
965 status: SidebarThreadStatus;
966 isUnread: boolean;
967 isWoke: boolean;
968 isActive: boolean;
969 isSelected: boolean;
970}): boolean {
971 if (input.isActive || input.isSelected || input.status === "input") return false;
972 if (input.status === "working" || input.status === "waiting") return true;
973 if (input.status === "ready" || input.status === "approval") {
974 return !input.isUnread && !input.isWoke;
975 }
976 return false;
978​
979type SidebarThreadStatusInput = Pick<
980 SidebarThreadSummary,
981 "hasPendingApprovals" | "hasPendingUserInput" | "pendingSubagentRequest" | "runtime"
982>;
983​
984export function resolveSidebarThreadStatus(thread: SidebarThreadStatusInput): SidebarThreadStatus {
985 if (thread.hasPendingApprovals || thread.pendingSubagentRequest === "approval") {
986 return "approval";
987 }
988 if (thread.hasPendingUserInput || thread.pendingSubagentRequest === "user_input") {
989 return "input";
990 }
991 if (
992 thread.runtime !== null &&
993 ["preparing", "queued", "starting", "running", "waiting"].includes(thread.runtime.status)
994 ) {
995 return "working";
996 }
997 if (thread.runtime?.status === "idle") {
998 return "waiting";
999 }
1000 if (thread.runtime?.status === "failed") {
1001 return thread.runtime.lastErrorClass === "usage_limit" ? "limited" : "failed";
1003 return "ready";
1005​
1006export type SidebarV2TopStatusKind =
1007 | "approval"
1008 | "done"
1009 | "failed"
1010 | "limited"
1011 | "input"
1012 | "waiting"
1013 | "woke"
1014 | "working";
1015​
1016export function resolveSidebarV2TopStatus(input: {
1017 readonly status: SidebarThreadStatus;
1018 readonly isUnread: boolean;
1019 readonly isWoke: boolean;
1020}): SidebarV2TopStatusKind | null {
1021 if (input.status === "working") {
1022 return "working";
1024 if (input.status === "waiting") {
1025 return "waiting";
1027 if (input.status === "approval") {
1028 return "approval";
1030 if (input.status === "input") {
1031 return "input";
1033 if (input.status === "failed" || input.status === "limited") {
1034 return input.status;
1036 if (input.isWoke) {
1037 return "woke";
1039 return input.isUnread ? "done" : null;
1041​
1042export function shouldShowSidebarV2Duration(status: SidebarThreadStatus): boolean {
1043 return status === "working";
1045​
1046/** First VALID timestamp wins: `a ?? b` falls through on null, but a present-
1047 yet-malformed string must also fall through to the next candidate rather
1048 than sink the row to the epoch. */
1049export function firstValidTimestampMs(
1050 ...candidates: ReadonlyArray<string | null | undefined>
1051): number {
1052 for (const candidate of candidates) {
1053 if (candidate == null) continue;
1054 const parsed = Date.parse(candidate);
1055 if (!Number.isNaN(parsed)) return parsed;
1057 return 0;
1059​
1060export { sortActiveThreadsByOrderKey as sortThreadsForSidebar } from "@t3tools/client-runtime/state/thread-sort";
1061// The Working section beta folds and orders the inbox the same way on mobile.
1062export {
1063 isThreadWorking as isSidebarThreadWorking,
1064 sortInboxThreadsByReturn,
1065 sortWorkingThreadsBySend,
1066} from "@t3tools/client-runtime/state/thread-inbox";
1067​
1068// Pinned-reorder key math and the keyed sort live in client-runtime
1069// (state/thread-sort) so web and mobile compute identical pinned orders.
1070export { pinOrderKeyBetween } from "@t3tools/client-runtime/state/thread-sort";
1071export { sortPinnedThreadsByOrderKey as sortPinnedThreadsForSidebar } from "@t3tools/client-runtime/state/thread-sort";
1072​
1073const EMPTY_CONTENT_MATCH_KEYS: ReadonlySet<string> = new Set<string>();
1074​
1075/**
1076 * Search the already-ordered sidebar thread collection by title or linked PR,
1077 * plus any thread whose messages the server matched (`contentMatchKeys`, keyed
1078 * by `threadSearchMatchKey`). Keeping the input order means lifecycle ordering
1079 * (active, snoozed, settled) remains stable while the user narrows the list.
1080 */
1081export function searchSidebarThreads<
1082 T extends {
1083 readonly environmentId: EnvironmentId;
1084 readonly id: ThreadId;
1085 readonly title: string;
1086 } & Parameters<typeof threadPullRequestSearchTerms>[0],
1088 threads: readonly T[],
1089 query: string,
1090 contentMatchKeys: ReadonlySet<string> = EMPTY_CONTENT_MATCH_KEYS,
1091): T[] {
1092 const normalizedQuery = query.trim().toLowerCase();
1093 if (normalizedQuery.length === 0) return [];
1094 const titleMatches: T[] = [];
1095 const contentMatches: T[] = [];
1096 for (const thread of threads) {
1097 const matchesTitle = [thread.title, ...threadPullRequestSearchTerms(thread)].some((term) =>
1098 term.toLowerCase().includes(normalizedQuery),
1099 );
1100 if (matchesTitle) {
1101 titleMatches.push(thread);
1102 } else if (
1103 contentMatchKeys.size > 0 &&
1104 contentMatchKeys.has(
1105 threadSearchMatchKey({ environmentId: thread.environmentId, threadId: thread.id }),
1107 ) {
1108 contentMatches.push(thread);
1111 return [...titleMatches, ...contentMatches];
1113​
1114/**
1115 * Whether a PR's search terms contain every whitespace-separated token of the
1116 * query. Search results use this to pick the PR number to show, so it has to
1117 * accept the multi-token queries the command palette matches on.
1118 */
1119export function pullRequestMatchesSearchQuery(
1120 pullRequest: Parameters<typeof threadPullRequestSearchTerms>[0],
1121 query: string,
1122): boolean {
1123 const normalizedQuery = normalizeSearchText(query);
1124 if (normalizedQuery.length === 0) return false;
1125 const haystack = normalizeSearchText(threadPullRequestSearchTerms(pullRequest).join(" "));
1126 return normalizedQuery.split(" ").every((token) => haystack.includes(token));
1128​
1129export function filterSidebarProjectScopeItems<TItem extends { readonly value: string }>(input: {
1130 items: readonly TItem[];
1131 query: string;
1132 matches: (item: TItem, query: string) => boolean;
1133}): readonly TItem[] {
1134 const query = input.query.trim();
1135 if (query.length === 0) return input.items;
1136 return input.items.filter((item) => item.value !== "all" && input.matches(item, query));
1138​
1139export interface SidebarProjectScopeMenuState {
1140 readonly open: boolean;
1141 readonly query: string;
1143​
1144export type SidebarProjectScopeMenuAction =
1145 | { readonly type: "query-changed"; readonly query: string }
1146 | { readonly type: "open-changed"; readonly open: boolean }
1147 | { readonly type: "project-settings-opened" };
1148​
1149export function reduceSidebarProjectScopeMenuState(
1150 state: SidebarProjectScopeMenuState,
1151 action: SidebarProjectScopeMenuAction,
1152): SidebarProjectScopeMenuState {
1153 switch (action.type) {
1154 case "query-changed":
1155 return { ...state, query: action.query };
1156 case "open-changed":
1157 return { open: action.open, query: "" };
1158 case "project-settings-opened":
1159 return { open: false, query: "" };
1162​
1163/** The timestamp a working thread's elapsed label counts from: when its
1164 current work started (request time until adoption). Background wakes do
1165 not reset it. Malformed timestamps fall through to the next candidate. */
1166export function resolveWorkingStartedAt(
1167 thread: Pick<SidebarThreadSummary, "latestRun" | "runtime">,
1168): string | null {
1169 return resolveThreadWorkingStartedAt(thread);
1171​
1172export function formatWorkingDurationLabel(elapsedMs: number): string {
1173 const seconds = Number.isFinite(elapsedMs) ? Math.max(0, Math.floor(elapsedMs / 1000)) : 0;
1174 if (seconds < 60) return `${seconds}s`;
1175 const minutes = Math.floor(seconds / 60);
1176 if (minutes < 60) return `${minutes}m`;
1177 return `${Math.floor(minutes / 60)}h ${minutes % 60}m`;
1179​
1180export function resolveThreadStatusPill(input: {
1181 thread: ThreadStatusInput;
1182}): ThreadStatusPill | null {
1183 const { thread } = input;
1184​
1185 if (thread.hasPendingApprovals || thread.pendingSubagentRequest === "approval") {
1186 return {
1187 label: "Pending Approval",
1188 colorClass: "text-amber-600 dark:text-amber-300/90",
1189 dotClass: "bg-amber-500 dark:bg-amber-300/90",
1190 pulse: false,
1191 };
1193​
1194 if (thread.hasPendingUserInput || thread.pendingSubagentRequest === "user_input") {
1195 return {
1196 label: "Awaiting Input",
1197 colorClass: "text-indigo-600 dark:text-indigo-300/90",
1198 dotClass: "bg-indigo-500 dark:bg-indigo-300/90",
1199 pulse: false,
1200 };
1202​
1203 if (thread.runtime?.status === "running" || thread.runtime?.status === "waiting") {
1204 return {
1205 label: "Working",
1206 colorClass: "text-sky-600 dark:text-sky-300/80",
1207 dotClass: "bg-sky-500 dark:bg-sky-300/80",
1208 pulse: true,
1209 };
1211​
1212 if (
1213 thread.runtime?.status === "preparing" ||
1214 thread.runtime?.status === "starting" ||
1215 thread.runtime?.status === "queued"
1216 ) {
1217 return {
1218 label: "Connecting",
1219 colorClass: "text-sky-600 dark:text-sky-300/80",
1220 dotClass: "bg-sky-500 dark:bg-sky-300/80",
1221 pulse: true,
1222 };
1224​
1225 if (backgroundWorkHoldsCompletion(thread.pendingBackgroundTasks ?? [])) {
1226 return {
1227 label: "Waiting",
1228 colorClass: "text-sidebar-muted-foreground",
1229 dotClass: "bg-sidebar-muted-foreground",
1230 pulse: false,
1231 };
1233​
1234 const hasPlanReadyPrompt =
1235 !thread.hasPendingUserInput &&
1236 thread.interactionMode === "plan" &&
1237 isLatestRunSettled(thread.latestRun, thread.runtime) &&
1238 thread.hasActionableProposedPlan;
1239 if (hasPlanReadyPrompt) {
1240 return {
1241 label: "Plan Ready",
1242 colorClass: "text-violet-600 dark:text-violet-300/90",
1243 dotClass: "bg-violet-500 dark:bg-violet-300/90",
1244 pulse: false,
1245 };
1247​
1248 if (hasUnseenCompletion(thread)) {
1249 return {
1250 label: "Completed",
1251 colorClass: "text-emerald-600 dark:text-emerald-300/90",
1252 dotClass: "bg-emerald-500 dark:bg-emerald-300/90",
1253 pulse: false,
1254 };
1256​
1257 return null;
1259​
1260export function resolveProjectStatusIndicator(
1261 statuses: ReadonlyArray<ThreadStatusPill | null>,
1262): ThreadStatusPill | null {
1263 let highestPriorityStatus: ThreadStatusPill | null = null;
1264​
1265 for (const status of statuses) {
1266 if (status === null) continue;
1267 if (
1268 highestPriorityStatus === null ||
1269 THREAD_STATUS_PRIORITY[status.label] > THREAD_STATUS_PRIORITY[highestPriorityStatus.label]
1270 ) {
1271 highestPriorityStatus = status;
1274​
1275 return highestPriorityStatus;
1277​
1278export function getFallbackThreadIdAfterDelete<
1279 T extends Pick<Thread, "id" | "projectId" | "createdAt" | "updatedAt"> & ThreadSortInput,
1280>(input: {
1281 threads: readonly T[];
1282 deletedThreadId: T["id"];
1283 sortOrder: SidebarThreadSortOrder;
1284 deletedThreadIds?: ReadonlySet<T["id"]>;
1285}): T["id"] | null {
1286 const { deletedThreadId, deletedThreadIds, sortOrder, threads } = input;
1287 const deletedThread = threads.find((thread) => thread.id === deletedThreadId);
1288 if (!deletedThread) {
1289 return null;
1291​
1292 return (
1293 sortThreads(
1294 threads.filter(
1295 (thread) =>
1296 thread.projectId === deletedThread.projectId &&
1297 thread.id !== deletedThreadId &&
1298 !deletedThreadIds?.has(thread.id),
1299 ),
1300 sortOrder,
1301 )[0]?.id ?? null
1302 );
1304export function getProjectSortTimestamp(
1305 project: SidebarProject,
1306 projectThreads: readonly ThreadSortInput[],
1307 sortOrder: Exclude<SidebarProjectSortOrder, "manual">,
1308): number {
1309 if (projectThreads.length > 0) {
1310 return projectThreads.reduce(
1311 (latest, thread) => Math.max(latest, getThreadSortTimestamp(thread, sortOrder)),
1312 Number.NEGATIVE_INFINITY,
1313 );
1315​
1316 if (sortOrder === "created_at") {
1317 return toSortableTimestamp(project.createdAt) ?? Number.NEGATIVE_INFINITY;
1319 return toSortableTimestamp(project.updatedAt ?? project.createdAt) ?? Number.NEGATIVE_INFINITY;
1321​
1322function sortProjectsByActivity<TProject extends SidebarProject>(
1323 projects: readonly TProject[],
1324 sortOrder: SidebarProjectSortOrder,
1325 getProjectThreads: (project: TProject) => readonly ThreadSortInput[],
1326 compareTies: (left: TProject, right: TProject) => number,
1327): TProject[] {
1328 if (sortOrder === "manual") {
1329 return [...projects];
1331​
1332 // Each project's timestamp walks all of its threads, so compute it once
1333 // per project instead of once per comparison.
1334 return projects
1335 .map((project) => ({
1336 project,
1337 timestamp: getProjectSortTimestamp(project, getProjectThreads(project), sortOrder),
1338 }))
1339 .sort((left, right) => {
1340 const byTimestamp =
1341 right.timestamp === left.timestamp ? 0 : right.timestamp > left.timestamp ? 1 : -1;
1342 return byTimestamp || compareTies(left.project, right.project);
1343 })
1344 .map(({ project }) => project);
1346​
1347export function sortProjectsForSidebar<
1348 TProject extends SidebarProject,
1349 TThread extends Pick<Thread, "projectId" | "createdAt" | "updatedAt"> & ThreadSortInput,
1351 projects: readonly TProject[],
1352 threads: readonly TThread[],
1353 sortOrder: SidebarProjectSortOrder,
1354): TProject[] {
1355 const threadsByProjectId = new Map<string, TThread[]>();
1356 for (const thread of threads) {
1357 const existing = threadsByProjectId.get(thread.projectId) ?? [];
1358 existing.push(thread);
1359 threadsByProjectId.set(thread.projectId, existing);
1361​
1362 return sortProjectsByActivity(
1363 projects,
1364 sortOrder,
1365 (project) => threadsByProjectId.get(project.id) ?? [],
1366 (left, right) => left.title.localeCompare(right.title) || left.id.localeCompare(right.id),
1367 );
1369​
1370export function sortLogicalProjectsForSidebar<
1371 TProject extends LogicalSidebarProject,
1372 TThread extends ScopedSidebarThread,
1374 projects: readonly TProject[],
1375 threads: readonly TThread[],
1376 sortOrder: SidebarProjectSortOrder,
1377): TProject[] {
1378 const groupKeyByProjectRef = new Map(
1379 projects.flatMap((project) =>
1380 project.memberProjectRefs.map(
1381 (projectRef) =>
1382 [`${projectRef.environmentId}\0${projectRef.projectId}`, project.projectKey] as const,
1383 ),
1384 ),
1385 );
1386 const threadsByProjectKey = new Map<string, TThread[]>();
1387 for (const thread of threads) {
1388 if (thread.archivedAt !== null) continue;
1389 const projectKey = groupKeyByProjectRef.get(`${thread.environmentId}\0${thread.projectId}`);
1390 if (!projectKey) continue;
1391 const existing = threadsByProjectKey.get(projectKey);
1392 if (existing) {
1393 existing.push(thread);
1394 } else {
1395 threadsByProjectKey.set(projectKey, [thread]);
1398​
1399 return sortProjectsByActivity(
1400 projects,
1401 sortOrder,
1402 (project) => threadsByProjectKey.get(project.projectKey) ?? [],
1403 (left, right) =>
1404 left.title.localeCompare(right.title) || left.projectKey.localeCompare(right.projectKey),
1405 );
1407​
1408export function sortSidebarV2ProjectGroups<
1409 TProject extends LogicalSidebarProject,
1410 TThread extends ScopedSidebarThread & Pick<SidebarThreadSummary, "lineage">,
1412 projects: readonly TProject[],
1413 threads: readonly TThread[],
1414 sortOrder: SidebarProjectSortOrder,
1415): TProject[] {
1416 return sortLogicalProjectsForSidebar(
1417 projects,
1418 filterSidebarV2VisibleThreads(threads, null),
1419 sortOrder,
1420 );
1422​
1423/**
1424 * Sorts the cross-environment project collection used by landing surfaces.
1425 * Project ids are only unique within an environment, and archived threads
1426 * must not make a project appear recently active.
1427 */
1428export function sortScopedProjectsForSidebar<
1429 TProject extends ScopedSidebarProject,
1430 TThread extends ScopedSidebarThread,
1432 projects: readonly TProject[],
1433 threads: readonly TThread[],
1434 sortOrder: SidebarProjectSortOrder,
1435): TProject[] {
1436 const scopedKey = (environmentId: string, projectId: string) =>
1437 `${environmentId}\u0000${projectId}`;
1438 const threadsByProject = new Map<string, TThread[]>();
1439 for (const thread of threads) {
1440 if (thread.archivedAt !== null) {
1441 continue;
1443 const key = scopedKey(thread.environmentId, thread.projectId);
1444 const existing = threadsByProject.get(key) ?? [];
1445 existing.push(thread);
1446 threadsByProject.set(key, existing);
1448​
1449 return sortProjectsByActivity(
1450 projects,
1451 sortOrder,
1452 (project) => threadsByProject.get(scopedKey(project.environmentId, project.id)) ?? [],
1453 (left, right) =>
1454 left.title.localeCompare(right.title) ||
1455 left.environmentId.localeCompare(right.environmentId) ||
1456 left.id.localeCompare(right.id),
1457 );