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

Sidebar.logic.ts

1,442 lines48.3 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 } 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 | "interactionMode"
656 | "latestRun"
657 | "runtime"
658> & {
659 lastVisitedAt?: string | null | undefined;
660 pendingBackgroundTasks?: SidebarThreadSummary["pendingBackgroundTasks"] | undefined;
661};
662​
663export interface ThreadJumpHintVisibilityController {
664 sync: (shouldShow: boolean) => void;
665 dispose: () => void;
667​
668export function resolveSidebarStageBadgeLabel(input: {
669 primaryServerVersion: string | null | undefined;
670 fallbackStageLabel: string;
671}): string {
672 return resolveServerBackedAppStageLabel(input);
674​
675export function createThreadJumpHintVisibilityController(input: {
676 delayMs: number;
677 onVisibilityChange: (visible: boolean) => void;
678 setTimeoutFn?: typeof globalThis.setTimeout;
679 clearTimeoutFn?: typeof globalThis.clearTimeout;
680}): ThreadJumpHintVisibilityController {
681 const setTimeoutFn = input.setTimeoutFn ?? globalThis.setTimeout;
682 const clearTimeoutFn = input.clearTimeoutFn ?? globalThis.clearTimeout;
683 let isVisible = false;
684 let timeoutId: NodeJS.Timeout | null = null;
685​
686 const clearPendingShow = () => {
687 if (timeoutId === null) {
688 return;
689 }
690 clearTimeoutFn(timeoutId);
691 timeoutId = null;
692 };
693​
694 return {
695 sync: (shouldShow) => {
696 if (!shouldShow) {
697 clearPendingShow();
698 if (isVisible) {
699 isVisible = false;
700 input.onVisibilityChange(false);
701 }
702 return;
703 }
704​
705 if (isVisible || timeoutId !== null) {
706 return;
707 }
708​
709 timeoutId = setTimeoutFn(() => {
710 timeoutId = null;
711 isVisible = true;
712 input.onVisibilityChange(true);
713 }, input.delayMs);
714 },
715 dispose: () => {
716 clearPendingShow();
717 },
718 };
720​
721export function useThreadJumpHintVisibility(): {
722 showThreadJumpHints: boolean;
723 updateThreadJumpHintsVisibility: (shouldShow: boolean) => void;
724} {
725 const [showThreadJumpHints, setShowThreadJumpHints] = React.useState(false);
726 const controllerRef = React.useRef<ThreadJumpHintVisibilityController | null>(null);
727​
728 React.useEffect(() => {
729 const controller = createThreadJumpHintVisibilityController({
730 delayMs: THREAD_JUMP_HINT_SHOW_DELAY_MS,
731 onVisibilityChange: (visible) => {
732 setShowThreadJumpHints(visible);
733 },
734 setTimeoutFn: window.setTimeout.bind(window),
735 clearTimeoutFn: window.clearTimeout.bind(window),
736 });
737 controllerRef.current = controller;
738​
739 return () => {
740 controller.dispose();
741 controllerRef.current = null;
742 };
743 }, []);
744​
745 const updateThreadJumpHintsVisibility = React.useCallback((shouldShow: boolean) => {
746 controllerRef.current?.sync(shouldShow);
747 }, []);
748​
749 return {
750 showThreadJumpHints,
751 updateThreadJumpHintsVisibility,
752 };
754​
755/**
756 * Effective visited watermark for a thread. Servers with visited tracking
757 * project `lastVisitedAt` on the shell and are authoritative — that value is
758 * shared across every device connected to the environment. Pre-tracking
759 * servers omit the field, and the browser's locally persisted watermark keeps
760 * working as before.
761 */
762export function resolveThreadLastVisitedAt(
763 serverLastVisitedAt: string | null | undefined,
764 localLastVisitedAt: string | undefined,
765): string | undefined {
766 // When the server tracks visits it is authoritative — including explicit
767 // rewinds from mark-unread, which a newer browser-local watermark must not
768 // mask. The local value only carries servers without visited tracking.
769 if (serverLastVisitedAt === undefined) return localLastVisitedAt;
770 return serverLastVisitedAt ?? undefined;
772​
773export function hasUnseenCompletion(thread: ThreadStatusInput): boolean {
774 if (!thread.latestRun?.completedAt) return false;
775 const completedAt = Date.parse(thread.latestRun.completedAt);
776 if (Number.isNaN(completedAt)) return false;
777 if (!thread.lastVisitedAt) return false;
778​
779 const lastVisitedAt = Date.parse(thread.lastVisitedAt);
780 if (Number.isNaN(lastVisitedAt)) return true;
781 return completedAt > lastVisitedAt;
783​
784export function shouldClearThreadSelectionOnMouseDown(target: HTMLElement | null): boolean {
785 if (target === null) return true;
786 return !target.closest(THREAD_SELECTION_SAFE_SELECTOR);
788​
789// A double-click dispatches two `click` events before `dblclick`: the first has
790// `detail === 1`, the second `detail === 2`. The second click must not run the
791// row's single-click navigation, otherwise double-click-to-rename would also
792// navigate. `MouseEvent.detail` is 0 for synthetic/keyboard activations, which
793// still count as a normal single activation.
794export function isTrailingDoubleClick(detail: number): boolean {
795 return detail > 1;
797​
798function nodeClosest(node: object | null, selector: string): unknown {
799 if (node === null || !("closest" in node) || typeof node.closest !== "function") return null;
800 return node.closest(selector);
802​
803/** Clicks on a nested link keep the link's meaning. The row must not treat them as multi-select. */
804export function isSidebarNestedLinkClick(target: EventTarget | null): boolean {
805 if (target == null || typeof target !== "object") return false;
806 if (nodeClosest(target, "a[href]") !== null) return true;
807 const parent =
808 "parentElement" in target &&
809 target.parentElement !== null &&
810 typeof target.parentElement === "object"
811 ? target.parentElement
812 : null;
813 return nodeClosest(parent, "a[href]") !== null;
815​
816// Shift+click on the new thread button creates directly in the current
817// project, skipping the command palette's project picker. With a single
818// project there is nothing to pick, so a plain click already creates
819// immediately and the modifier changes nothing.
820export function shouldCreateNewThreadInCurrentProject(
821 shiftKey: boolean,
822 projectGroupCount: number,
823): boolean {
824 return shiftKey || projectGroupCount <= 1;
826​
827export function orderItemsByPreferredIds<TItem, TId>(input: {
828 items: readonly TItem[];
829 preferredIds: readonly TId[];
830 getId: (item: TItem) => TId;
831 getPreferenceIds?: (item: TItem) => readonly TId[];
832}): TItem[] {
833 const { getId, getPreferenceIds, items, preferredIds } = input;
834 if (preferredIds.length === 0) {
835 return [...items];
836 }
837​
838 const indexesByPreferenceId = new Map<TId, number[]>();
839 for (const [index, item] of items.entries()) {
840 const preferenceIds = getPreferenceIds?.(item) ?? [getId(item)];
841 for (const preferenceId of new Set(preferenceIds)) {
842 const indexes = indexesByPreferenceId.get(preferenceId);
843 if (indexes) {
844 indexes.push(index);
845 } else {
846 indexesByPreferenceId.set(preferenceId, [index]);
847 }
848 }
849 }
850​
851 const emittedIndexes = new Set<number>();
852 const ordered = preferredIds.flatMap((id) => {
853 const index = indexesByPreferenceId
854 .get(id)
855 ?.find((candidate) => !emittedIndexes.has(candidate));
856 if (index === undefined) {
857 return [];
858 }
859 emittedIndexes.add(index);
860 return [items[index]!];
861 });
862 const remaining = items.filter((_, index) => !emittedIndexes.has(index));
863 return [...ordered, ...remaining];
865​
866export function getSidebarThreadIdsToPrewarm<TThreadId>(
867 visibleThreadIds: readonly TThreadId[],
868 limit = SIDEBAR_THREAD_PREWARM_LIMIT,
869): TThreadId[] {
870 return visibleThreadIds.slice(0, Math.max(0, limit));
872​
873export function resolveAdjacentThreadId<T>(input: {
874 threadIds: readonly T[];
875 currentThreadId: T | null;
876 direction: ThreadTraversalDirection;
877}): T | null {
878 const { currentThreadId, direction, threadIds } = input;
879​
880 if (threadIds.length === 0) {
881 return null;
882 }
883​
884 if (currentThreadId === null) {
885 return direction === "previous" ? (threadIds.at(-1) ?? null) : (threadIds[0] ?? null);
886 }
887​
888 const currentIndex = threadIds.indexOf(currentThreadId);
889 if (currentIndex === -1) {
890 return null;
891 }
892​
893 if (direction === "previous") {
894 return currentIndex > 0 ? (threadIds[currentIndex - 1] ?? null) : null;
895 }
896​
897 return currentIndex < threadIds.length - 1 ? (threadIds[currentIndex + 1] ?? null) : null;
899​
900export function isContextMenuPointerDown(input: {
901 button: number;
902 ctrlKey: boolean;
903 isMac: boolean;
904}): boolean {
905 if (input.button === 2) return true;
906 return input.isMac && input.button === 0 && input.ctrlKey;
908​
909export function resolveThreadRowClassName(input: {
910 isActive: boolean;
911 isSelected: boolean;
912}): string {
913 const baseClassName =
914 "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";
915​
916 if (input.isSelected && input.isActive) {
917 return cn(
918 baseClassName,
919 "bg-sidebar-row-active text-sidebar-foreground font-medium hover:bg-sidebar-row-active hover:text-sidebar-foreground",
920 );
921 }
922​
923 if (input.isSelected) {
924 return cn(
925 baseClassName,
926 "bg-sidebar-row-selected text-sidebar-foreground hover:bg-sidebar-row-active hover:text-sidebar-foreground",
927 );
928 }
929​
930 if (input.isActive) {
931 return cn(
932 baseClassName,
933 "bg-sidebar-row-active text-sidebar-foreground font-medium hover:bg-sidebar-row-active hover:text-sidebar-foreground",
934 );
935 }
936​
937 return cn(
938 baseClassName,
939 "text-sidebar-muted-foreground/80 hover:bg-sidebar-row-hover hover:text-sidebar-foreground",
940 );
942​
943// ── Sidebar v2 status model ─────────────────────────────────────────
944// Six visual states, three colors: color is reserved for "act now"
945// (approval), "in motion" (working), and "broken" (failed). Ready is the
946// unlabeled resting state — the agent stopped and is waiting on the user,
947// whether it finished, asked a question, or proposed a plan. Waiting
948// (runtime status "idle") is the agent stopped with background work that will
949// wake it (subagents, monitors): not the user's turn yet, so it renders grey
950// like working, not as a false Done. Commands it left running, such as a dev
951// server, do not hold the thread; it reads as ready.
952// Unread completion is tracked separately: it describes whether a ready
953// thread needs attention, not what the thread is currently doing.
954export type SidebarThreadStatus =
955 | "approval"
956 | "input"
957 | "working"
958 | "waiting"
959 | "failed"
960 | "limited"
961 | "ready";
962​
963export function shouldRecedeSidebarThread(input: {
964 status: SidebarThreadStatus;
965 isUnread: boolean;
966 isWoke: boolean;
967 isActive: boolean;
968 isSelected: boolean;
969}): boolean {
970 if (input.isActive || input.isSelected || input.status === "input") return false;
971 if (input.status === "working" || input.status === "waiting") return true;
972 if (input.status === "ready" || input.status === "approval") {
973 return !input.isUnread && !input.isWoke;
974 }
975 return false;
977​
978type SidebarThreadStatusInput = Pick<
979 SidebarThreadSummary,
980 "hasPendingApprovals" | "hasPendingUserInput" | "runtime"
981>;
982​
983export function resolveSidebarThreadStatus(thread: SidebarThreadStatusInput): SidebarThreadStatus {
984 if (thread.hasPendingApprovals) {
985 return "approval";
986 }
987 if (thread.hasPendingUserInput) {
988 return "input";
989 }
990 if (
991 thread.runtime !== null &&
992 ["preparing", "queued", "starting", "running", "waiting"].includes(thread.runtime.status)
993 ) {
994 return "working";
995 }
996 if (thread.runtime?.status === "idle") {
997 return "waiting";
998 }
999 if (thread.runtime?.status === "failed") {
1000 return thread.runtime.lastErrorClass === "usage_limit" ? "limited" : "failed";
1002 return "ready";
1004​
1005export type SidebarV2TopStatusKind =
1006 | "approval"
1007 | "done"
1008 | "failed"
1009 | "limited"
1010 | "input"
1011 | "waiting"
1012 | "woke"
1013 | "working";
1014​
1015export function resolveSidebarV2TopStatus(input: {
1016 readonly status: SidebarThreadStatus;
1017 readonly isUnread: boolean;
1018 readonly isWoke: boolean;
1019}): SidebarV2TopStatusKind | null {
1020 if (input.status === "working") {
1021 return "working";
1023 if (input.status === "waiting") {
1024 return "waiting";
1026 if (input.status === "approval") {
1027 return "approval";
1029 if (input.status === "input") {
1030 return "input";
1032 if (input.status === "failed" || input.status === "limited") {
1033 return input.status;
1035 if (input.isWoke) {
1036 return "woke";
1038 return input.isUnread ? "done" : null;
1040​
1041export function shouldShowSidebarV2Duration(status: SidebarThreadStatus): boolean {
1042 return status === "working";
1044​
1045/** First VALID timestamp wins: `a ?? b` falls through on null, but a present-
1046 yet-malformed string must also fall through to the next candidate rather
1047 than sink the row to the epoch. */
1048export function firstValidTimestampMs(
1049 ...candidates: ReadonlyArray<string | null | undefined>
1050): number {
1051 for (const candidate of candidates) {
1052 if (candidate == null) continue;
1053 const parsed = Date.parse(candidate);
1054 if (!Number.isNaN(parsed)) return parsed;
1056 return 0;
1058​
1059export { sortActiveThreadsByOrderKey as sortThreadsForSidebar } from "@t3tools/client-runtime/state/thread-sort";
1060// The Working section beta folds and orders the inbox the same way on mobile.
1061export {
1062 isThreadWorking as isSidebarThreadWorking,
1063 sortInboxThreadsByReturn,
1064 sortWorkingThreadsBySend,
1065} from "@t3tools/client-runtime/state/thread-inbox";
1066​
1067// Pinned-reorder key math and the keyed sort live in client-runtime
1068// (state/thread-sort) so web and mobile compute identical pinned orders.
1069export { pinOrderKeyBetween } from "@t3tools/client-runtime/state/thread-sort";
1070export { sortPinnedThreadsByOrderKey as sortPinnedThreadsForSidebar } from "@t3tools/client-runtime/state/thread-sort";
1071​
1072const EMPTY_CONTENT_MATCH_KEYS: ReadonlySet<string> = new Set<string>();
1073​
1074/**
1075 * Search the already-ordered sidebar thread collection by title or linked PR,
1076 * plus any thread whose messages the server matched (`contentMatchKeys`, keyed
1077 * by `threadSearchMatchKey`). Keeping the input order means lifecycle ordering
1078 * (active, snoozed, settled) remains stable while the user narrows the list.
1079 */
1080export function searchSidebarThreads<
1081 T extends {
1082 readonly environmentId: EnvironmentId;
1083 readonly id: ThreadId;
1084 readonly title: string;
1085 } & Parameters<typeof threadPullRequestSearchTerms>[0],
1087 threads: readonly T[],
1088 query: string,
1089 contentMatchKeys: ReadonlySet<string> = EMPTY_CONTENT_MATCH_KEYS,
1090): T[] {
1091 const normalizedQuery = query.trim().toLowerCase();
1092 if (normalizedQuery.length === 0) return [];
1093 const titleMatches: T[] = [];
1094 const contentMatches: T[] = [];
1095 for (const thread of threads) {
1096 const matchesTitle = [thread.title, ...threadPullRequestSearchTerms(thread)].some((term) =>
1097 term.toLowerCase().includes(normalizedQuery),
1098 );
1099 if (matchesTitle) {
1100 titleMatches.push(thread);
1101 } else if (
1102 contentMatchKeys.size > 0 &&
1103 contentMatchKeys.has(
1104 threadSearchMatchKey({ environmentId: thread.environmentId, threadId: thread.id }),
1106 ) {
1107 contentMatches.push(thread);
1110 return [...titleMatches, ...contentMatches];
1112​
1113export function filterSidebarProjectScopeItems<TItem extends { readonly value: string }>(input: {
1114 items: readonly TItem[];
1115 query: string;
1116 matches: (item: TItem, query: string) => boolean;
1117}): readonly TItem[] {
1118 const query = input.query.trim();
1119 if (query.length === 0) return input.items;
1120 return input.items.filter((item) => item.value !== "all" && input.matches(item, query));
1122​
1123export interface SidebarProjectScopeMenuState {
1124 readonly open: boolean;
1125 readonly query: string;
1127​
1128export type SidebarProjectScopeMenuAction =
1129 | { readonly type: "query-changed"; readonly query: string }
1130 | { readonly type: "open-changed"; readonly open: boolean }
1131 | { readonly type: "project-settings-opened" };
1132​
1133export function reduceSidebarProjectScopeMenuState(
1134 state: SidebarProjectScopeMenuState,
1135 action: SidebarProjectScopeMenuAction,
1136): SidebarProjectScopeMenuState {
1137 switch (action.type) {
1138 case "query-changed":
1139 return { ...state, query: action.query };
1140 case "open-changed":
1141 return { open: action.open, query: "" };
1142 case "project-settings-opened":
1143 return { open: false, query: "" };
1146​
1147/** The timestamp a working thread's elapsed label counts from: when its
1148 current work started (request time until adoption). Background wakes do
1149 not reset it. Malformed timestamps fall through to the next candidate. */
1150export function resolveWorkingStartedAt(
1151 thread: Pick<SidebarThreadSummary, "latestRun" | "runtime">,
1152): string | null {
1153 return resolveThreadWorkingStartedAt(thread);
1155​
1156export function formatWorkingDurationLabel(elapsedMs: number): string {
1157 const seconds = Number.isFinite(elapsedMs) ? Math.max(0, Math.floor(elapsedMs / 1000)) : 0;
1158 if (seconds < 60) return `${seconds}s`;
1159 const minutes = Math.floor(seconds / 60);
1160 if (minutes < 60) return `${minutes}m`;
1161 return `${Math.floor(minutes / 60)}h ${minutes % 60}m`;
1163​
1164export function resolveThreadStatusPill(input: {
1165 thread: ThreadStatusInput;
1166}): ThreadStatusPill | null {
1167 const { thread } = input;
1168​
1169 if (thread.hasPendingApprovals) {
1170 return {
1171 label: "Pending Approval",
1172 colorClass: "text-amber-600 dark:text-amber-300/90",
1173 dotClass: "bg-amber-500 dark:bg-amber-300/90",
1174 pulse: false,
1175 };
1177​
1178 if (thread.hasPendingUserInput) {
1179 return {
1180 label: "Awaiting Input",
1181 colorClass: "text-indigo-600 dark:text-indigo-300/90",
1182 dotClass: "bg-indigo-500 dark:bg-indigo-300/90",
1183 pulse: false,
1184 };
1186​
1187 if (thread.runtime?.status === "running" || thread.runtime?.status === "waiting") {
1188 return {
1189 label: "Working",
1190 colorClass: "text-sky-600 dark:text-sky-300/80",
1191 dotClass: "bg-sky-500 dark:bg-sky-300/80",
1192 pulse: true,
1193 };
1195​
1196 if (
1197 thread.runtime?.status === "preparing" ||
1198 thread.runtime?.status === "starting" ||
1199 thread.runtime?.status === "queued"
1200 ) {
1201 return {
1202 label: "Connecting",
1203 colorClass: "text-sky-600 dark:text-sky-300/80",
1204 dotClass: "bg-sky-500 dark:bg-sky-300/80",
1205 pulse: true,
1206 };
1208​
1209 if (backgroundWorkHoldsCompletion(thread.pendingBackgroundTasks ?? [])) {
1210 return {
1211 label: "Waiting",
1212 colorClass: "text-sidebar-muted-foreground",
1213 dotClass: "bg-sidebar-muted-foreground",
1214 pulse: false,
1215 };
1217​
1218 const hasPlanReadyPrompt =
1219 !thread.hasPendingUserInput &&
1220 thread.interactionMode === "plan" &&
1221 isLatestRunSettled(thread.latestRun, thread.runtime) &&
1222 thread.hasActionableProposedPlan;
1223 if (hasPlanReadyPrompt) {
1224 return {
1225 label: "Plan Ready",
1226 colorClass: "text-violet-600 dark:text-violet-300/90",
1227 dotClass: "bg-violet-500 dark:bg-violet-300/90",
1228 pulse: false,
1229 };
1231​
1232 if (hasUnseenCompletion(thread)) {
1233 return {
1234 label: "Completed",
1235 colorClass: "text-emerald-600 dark:text-emerald-300/90",
1236 dotClass: "bg-emerald-500 dark:bg-emerald-300/90",
1237 pulse: false,
1238 };
1240​
1241 return null;
1243​
1244export function resolveProjectStatusIndicator(
1245 statuses: ReadonlyArray<ThreadStatusPill | null>,
1246): ThreadStatusPill | null {
1247 let highestPriorityStatus: ThreadStatusPill | null = null;
1248​
1249 for (const status of statuses) {
1250 if (status === null) continue;
1251 if (
1252 highestPriorityStatus === null ||
1253 THREAD_STATUS_PRIORITY[status.label] > THREAD_STATUS_PRIORITY[highestPriorityStatus.label]
1254 ) {
1255 highestPriorityStatus = status;
1258​
1259 return highestPriorityStatus;
1261​
1262export function getFallbackThreadIdAfterDelete<
1263 T extends Pick<Thread, "id" | "projectId" | "createdAt" | "updatedAt"> & ThreadSortInput,
1264>(input: {
1265 threads: readonly T[];
1266 deletedThreadId: T["id"];
1267 sortOrder: SidebarThreadSortOrder;
1268 deletedThreadIds?: ReadonlySet<T["id"]>;
1269}): T["id"] | null {
1270 const { deletedThreadId, deletedThreadIds, sortOrder, threads } = input;
1271 const deletedThread = threads.find((thread) => thread.id === deletedThreadId);
1272 if (!deletedThread) {
1273 return null;
1275​
1276 return (
1277 sortThreads(
1278 threads.filter(
1279 (thread) =>
1280 thread.projectId === deletedThread.projectId &&
1281 thread.id !== deletedThreadId &&
1282 !deletedThreadIds?.has(thread.id),
1283 ),
1284 sortOrder,
1285 )[0]?.id ?? null
1286 );
1288export function getProjectSortTimestamp(
1289 project: SidebarProject,
1290 projectThreads: readonly ThreadSortInput[],
1291 sortOrder: Exclude<SidebarProjectSortOrder, "manual">,
1292): number {
1293 if (projectThreads.length > 0) {
1294 return projectThreads.reduce(
1295 (latest, thread) => Math.max(latest, getThreadSortTimestamp(thread, sortOrder)),
1296 Number.NEGATIVE_INFINITY,
1297 );
1299​
1300 if (sortOrder === "created_at") {
1301 return toSortableTimestamp(project.createdAt) ?? Number.NEGATIVE_INFINITY;
1303 return toSortableTimestamp(project.updatedAt ?? project.createdAt) ?? Number.NEGATIVE_INFINITY;
1305​
1306function sortProjectsByActivity<TProject extends SidebarProject>(
1307 projects: readonly TProject[],
1308 sortOrder: SidebarProjectSortOrder,
1309 getProjectThreads: (project: TProject) => readonly ThreadSortInput[],
1310 compareTies: (left: TProject, right: TProject) => number,
1311): TProject[] {
1312 if (sortOrder === "manual") {
1313 return [...projects];
1315​
1316 // Each project's timestamp walks all of its threads, so compute it once
1317 // per project instead of once per comparison.
1318 return projects
1319 .map((project) => ({
1320 project,
1321 timestamp: getProjectSortTimestamp(project, getProjectThreads(project), sortOrder),
1322 }))
1323 .sort((left, right) => {
1324 const byTimestamp =
1325 right.timestamp === left.timestamp ? 0 : right.timestamp > left.timestamp ? 1 : -1;
1326 return byTimestamp || compareTies(left.project, right.project);
1327 })
1328 .map(({ project }) => project);
1330​
1331export function sortProjectsForSidebar<
1332 TProject extends SidebarProject,
1333 TThread extends Pick<Thread, "projectId" | "createdAt" | "updatedAt"> & ThreadSortInput,
1335 projects: readonly TProject[],
1336 threads: readonly TThread[],
1337 sortOrder: SidebarProjectSortOrder,
1338): TProject[] {
1339 const threadsByProjectId = new Map<string, TThread[]>();
1340 for (const thread of threads) {
1341 const existing = threadsByProjectId.get(thread.projectId) ?? [];
1342 existing.push(thread);
1343 threadsByProjectId.set(thread.projectId, existing);
1345​
1346 return sortProjectsByActivity(
1347 projects,
1348 sortOrder,
1349 (project) => threadsByProjectId.get(project.id) ?? [],
1350 (left, right) => left.title.localeCompare(right.title) || left.id.localeCompare(right.id),
1351 );
1353​
1354export function sortLogicalProjectsForSidebar<
1355 TProject extends LogicalSidebarProject,
1356 TThread extends ScopedSidebarThread,
1358 projects: readonly TProject[],
1359 threads: readonly TThread[],
1360 sortOrder: SidebarProjectSortOrder,
1361): TProject[] {
1362 const groupKeyByProjectRef = new Map(
1363 projects.flatMap((project) =>
1364 project.memberProjectRefs.map(
1365 (projectRef) =>
1366 [`${projectRef.environmentId}\0${projectRef.projectId}`, project.projectKey] as const,
1367 ),
1368 ),
1369 );
1370 const threadsByProjectKey = new Map<string, TThread[]>();
1371 for (const thread of threads) {
1372 if (thread.archivedAt !== null) continue;
1373 const projectKey = groupKeyByProjectRef.get(`${thread.environmentId}\0${thread.projectId}`);
1374 if (!projectKey) continue;
1375 const existing = threadsByProjectKey.get(projectKey);
1376 if (existing) {
1377 existing.push(thread);
1378 } else {
1379 threadsByProjectKey.set(projectKey, [thread]);
1382​
1383 return sortProjectsByActivity(
1384 projects,
1385 sortOrder,
1386 (project) => threadsByProjectKey.get(project.projectKey) ?? [],
1387 (left, right) =>
1388 left.title.localeCompare(right.title) || left.projectKey.localeCompare(right.projectKey),
1389 );
1391​
1392export function sortSidebarV2ProjectGroups<
1393 TProject extends LogicalSidebarProject,
1394 TThread extends ScopedSidebarThread & Pick<SidebarThreadSummary, "lineage">,
1396 projects: readonly TProject[],
1397 threads: readonly TThread[],
1398 sortOrder: SidebarProjectSortOrder,
1399): TProject[] {
1400 return sortLogicalProjectsForSidebar(
1401 projects,
1402 filterSidebarV2VisibleThreads(threads, null),
1403 sortOrder,
1404 );
1406​
1407/**
1408 * Sorts the cross-environment project collection used by landing surfaces.
1409 * Project ids are only unique within an environment, and archived threads
1410 * must not make a project appear recently active.
1411 */
1412export function sortScopedProjectsForSidebar<
1413 TProject extends ScopedSidebarProject,
1414 TThread extends ScopedSidebarThread,
1416 projects: readonly TProject[],
1417 threads: readonly TThread[],
1418 sortOrder: SidebarProjectSortOrder,
1419): TProject[] {
1420 const scopedKey = (environmentId: string, projectId: string) =>
1421 `${environmentId}\u0000${projectId}`;
1422 const threadsByProject = new Map<string, TThread[]>();
1423 for (const thread of threads) {
1424 if (thread.archivedAt !== null) {
1425 continue;
1427 const key = scopedKey(thread.environmentId, thread.projectId);
1428 const existing = threadsByProject.get(key) ?? [];
1429 existing.push(thread);
1430 threadsByProject.set(key, existing);
1432​
1433 return sortProjectsByActivity(
1434 projects,
1435 sortOrder,
1436 (project) => threadsByProject.get(scopedKey(project.environmentId, project.id)) ?? [],
1437 (left, right) =>
1438 left.title.localeCompare(right.title) ||
1439 left.environmentId.localeCompare(right.environmentId) ||
1440 left.id.localeCompare(right.id),
1441 );