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

Sidebar.logic.ts

1,237 lines41.2 KB

1import { threadPullRequestSearchTerms } from "@t3tools/shared/threadPullRequests";
2import * as React from "react";
3import { defaultAnimateLayoutChanges, type AnimateLayoutChanges } from "@dnd-kit/sortable";
4import {
5 isAtomCommandInterrupted,
6 type AtomCommandResult,
7} from "@t3tools/client-runtime/state/runtime";
8import type { ContextMenuItem } from "@t3tools/contracts";
9import type { SidebarProjectSortOrder, SidebarThreadSortOrder } from "@t3tools/contracts/settings";
10import type { AsyncResult } from "effect/unstable/reactivity";
11import { planPinnedReorder } from "@t3tools/client-runtime/state/thread-sort";
12import {
13 getThreadSortTimestamp,
14 resolveSettledThreadTimestamp,
15 sortThreads,
16 toSortableTimestamp,
17 type SettledThreadTimestampInput,
18 type ThreadSortInput,
19} from "../lib/threadSort";
20import type { SidebarThreadSummary, Thread } from "../types";
21import { cn } from "../lib/utils";
22import { isLatestTurnSettled } from "../session-logic";
23​
24const THREAD_SELECTION_SAFE_SELECTOR = "[data-thread-item], [data-thread-selection-safe]";
25export const THREAD_JUMP_HINT_SHOW_DELAY_MS = 200;
26// Visible sidebar rows are prewarmed into the thread-detail cache so opening a
27// nearby thread usually reuses an already-hot subscription. Each prewarmed
28// thread holds a live, fully hydrated detail subscription (all messages and
29// activities, growing as agents work) for as long as the row stays visible,
30// so this limit is a direct renderer-heap and server-load multiplier — keep
31// it small; cold opens still render instantly from the cached snapshot.
32const SIDEBAR_THREAD_PREWARM_LIMIT = 3;
33// A small buffer keeps the next few rows warm without leasing every row that
34// content-visibility leaves mounted below the scroll viewport.
35const SIDEBAR_ROW_SUBSCRIPTION_OVERSCAN_PX = 160;
36​
37export function useSidebarRowSubscriptionLease(isActive: boolean): {
38 readonly leaseLiveStatus: boolean;
39 readonly rowRef: React.Dispatch<React.SetStateAction<HTMLElement | null>>;
40} {
41 const [row, setRow] = React.useState<HTMLElement | null>(null);
42 const [isNearViewport, setIsNearViewport] = React.useState(isActive);
43​
44 React.useEffect(() => {
45 if (isActive) {
46 setIsNearViewport(true);
47 return;
48 }
49 if (row === null) return;
50 if (typeof IntersectionObserver === "undefined") {
51 setIsNearViewport(true);
52 return;
53 }
54​
55 const scrollRoot = row.closest<HTMLElement>('[data-slot="scroll-area-viewport"]');
56 const observer = new IntersectionObserver(
57 ([entry]) => setIsNearViewport(entry?.isIntersecting === true),
58 {
59 root: scrollRoot,
60 rootMargin: `${SIDEBAR_ROW_SUBSCRIPTION_OVERSCAN_PX}px 0px`,
61 },
62 );
63 observer.observe(row);
64 return () => observer.disconnect();
65 }, [isActive, row]);
66​
67 return {
68 leaseLiveStatus: isActive || isNearViewport,
69 rowRef: setRow,
70 };
72​
73// A row keeps the last live value it rendered so a released lease never
74// blanks its badge. The value is bound to `key`, so a different worktree or
75// linked pull request cannot reuse the previous one.
76export function useRetainedValue<T>(key: string | null, value: T | null): T | null {
77 const retained = React.useRef<{ readonly key: string; readonly value: T } | null>(null);
78 if (key !== null && value !== null) {
79 retained.current = { key, value };
80 }
81 if (value !== null) return value;
82 return key !== null && retained.current?.key === key ? retained.current.value : null;
84​
85// Sidebar.motion handles ordinary section changes. Sortable transforms own
86// dragging; replaying their committed DOM order would animate the drop twice.
87export const animateSidebarLayoutChanges: AnimateLayoutChanges = (args) =>
88 args.isSorting ? defaultAnimateLayoutChanges(args) : false;
89​
90// Rows and section markers share one sortable list. The separators resolve
91// the lifecycle action; Sidebar.drag previews the resulting layout. Pinned
92// and active threads keep the dragged position; settled threads use time
93// order. Snoozed rows can leave the shelf, but dropping into it is not
94// supported because snoozing requires a wake time.
95​
96export type SidebarSection = "pinned" | "active" | "snoozed" | "settled";
97​
98/** Sortable ids: thread rows use their scoped key; structural items use a
99 colon-free prefix: scoped thread keys always contain a colon. */
100const SIDEBAR_MARKER_PREFIX = "sidebar-marker-";
101​
102export type SidebarListMarker =
103 /** The top boundary is also a landing target when there are no pins. */
104 | "pinned-header"
105 /** Stand-in rows so an empty section has somewhere for the gap to open. */
106 | "active-placeholder"
107 | "settled-placeholder"
108 /** The boundary between pinned and active rows. */
109 | "pinned-divider"
110 | "snoozed-header"
111 | "settled-header";
112​
113export function sidebarMarkerId(marker: SidebarListMarker): string {
114 return `${SIDEBAR_MARKER_PREFIX}${marker}`;
116​
117export type SidebarListItem =
118 | { readonly kind: "thread"; readonly key: string; readonly section: SidebarSection }
119 | { readonly kind: "marker"; readonly marker: SidebarListMarker };
120​
121export function sidebarListItemId(item: SidebarListItem): string {
122 return item.kind === "thread" ? item.key : sidebarMarkerId(item.marker);
124​
125/** The section a slot belongs to, read off the markers around it: from
126 the top down, everything before the pinned divider is pinned, then the
127 inbox until the snoozed header, the shelf until the settled header,
128 then settled. */
129function sectionAtSidebarSlot(items: readonly SidebarListItem[], index: number): SidebarSection {
130 let section: SidebarSection = "pinned";
131 for (let i = 0; i < index && i < items.length; i += 1) {
132 const item = items[i]!;
133 if (item.kind !== "marker") continue;
134 if (item.marker === "pinned-divider") section = "active";
135 else if (item.marker === "snoozed-header") section = "snoozed";
136 else if (item.marker === "settled-header") section = "settled";
137 }
138 return section;
140​
141/** Resolve the destination section and manual order from an arrayMove across
142 * the separators. The snoozed shelf is never a destination. */
143export type SidebarDropTarget = {
144 readonly section: "pinned" | "active" | "settled";
145 readonly pinnedOrder: readonly string[];
146 readonly activeOrder: readonly string[];
147};
148​
149export function resolveSidebarDropTarget(
150 items: readonly SidebarListItem[],
151 activeKey: string,
152 overId: string,
153): SidebarDropTarget | null {
154 const activeIndex = items.findIndex((item) => sidebarListItemId(item) === activeKey);
155 const overIndex = items.findIndex((item) => sidebarListItemId(item) === overId);
156 if (activeIndex === -1 || overIndex === -1 || items[activeIndex]?.kind !== "thread") return null;
157 const moved = items.filter((_, index) => index !== activeIndex);
158 moved.splice(overIndex, 0, items[activeIndex]!);
159 const section = sectionAtSidebarSlot(moved, overIndex);
160 if (section === "snoozed") return null;
161 const pinnedOrder: string[] = [];
162 const activeOrder: string[] = [];
163 let currentSection: SidebarSection = "pinned";
164 for (const item of moved) {
165 if (item.kind === "marker") {
166 if (item.marker === "pinned-divider") currentSection = "active";
167 else if (item.marker === "snoozed-header" || item.marker === "settled-header") break;
168 } else if (currentSection === "pinned") pinnedOrder.push(item.key);
169 else activeOrder.push(item.key);
170 }
171 return { section, pinnedOrder, activeOrder };
173​
174export type SidebarThreadDropPlan =
175 | { readonly kind: "none" }
176 /** Within the pinned block: the existing key writes. */
177 | {
178 readonly kind: "reorder-pinned";
179 readonly order: readonly string[];
180 readonly assignments: ReadonlyArray<{ readonly id: string; readonly orderKey: string }>;
181 }
182 /** From another section into the pinned block. Fresh pins take `orderKey`
183 on the pin command. `extraAssignments` land afterward, including the
184 moved row when it was already pinned beneath a snooze. */
185 | {
186 readonly kind: "pin";
187 readonly order: readonly string[];
188 readonly orderKey: string | undefined;
189 readonly extraAssignments: ReadonlyArray<{ readonly id: string; readonly orderKey: string }>;
190 }
191 | {
192 readonly kind: "move-active";
193 readonly order: readonly string[];
194 readonly assignments: ReadonlyArray<{ readonly id: string; readonly orderKey: string }>;
195 readonly unpin: boolean;
196 readonly unsettle: boolean;
197 readonly unsnooze: boolean;
198 }
199 | { readonly kind: "settle" };
200​
201/** What dropping in `to` does to a thread lifted from `from`, for the badge
202 on the lifted row. Null while reordering inside one section and for the
203 snoozed shelf, which cannot be a drop target. */
204export type SidebarDropVerb = "pin" | "unpin" | "settle" | "unsettle" | "wake";
205​
206export function resolveSidebarDropVerb(
207 from: SidebarSection,
208 to: SidebarSection | null,
209): SidebarDropVerb | null {
210 if (to === null || to === from || to === "snoozed") return null;
211 if (to === "pinned") return "pin";
212 if (to === "settled") return "settle";
213 if (from === "pinned") return "unpin";
214 if (from === "settled") return "unsettle";
215 return "wake";
217​
218export function planSidebarThreadDrop(input: {
219 readonly activeKey: string;
220 readonly activeSection: SidebarSection;
221 /** Snoozed threads can retain pinning and settlement beneath the shelf. */
222 readonly activePinned?: boolean;
223 readonly activeSettled?: boolean;
224 readonly supportsSettlement?: boolean;
225 readonly target: SidebarDropTarget;
226 /** All pinned keys in displayed order before the drop. */
227 readonly pinnedOrder: readonly string[];
228 readonly pinnedKeysById: ReadonlyMap<string, string | null | undefined>;
229 readonly reorderableKeys?: ReadonlySet<string>;
230 readonly activeOrder: readonly string[];
231 readonly activeKeysById: ReadonlyMap<string, string | null | undefined>;
232 readonly activeReorderableKeys?: ReadonlySet<string>;
233}): SidebarThreadDropPlan {
234 const {
235 activeKey,
236 activeSection,
237 activePinned = activeSection === "pinned",
238 activeSettled = activeSection === "settled",
239 target,
240 pinnedOrder,
241 pinnedKeysById,
242 reorderableKeys,
243 activeOrder,
244 activeKeysById,
245 activeReorderableKeys,
246 } = input;
247 if (input.supportsSettlement === false && (target.section === "settled" || activeSettled)) {
248 return { kind: "none" };
249 }
250 switch (target.section) {
251 case "active": {
252 const order = target.activeOrder;
253 if (
254 activeSection === "active" &&
255 order.length === activeOrder.length &&
256 order.every((key, index) => key === activeOrder[index])
257 ) {
258 return { kind: "none" };
259 }
260 const assignments = planPinnedReorder({
261 orderedIds: order,
262 keysById: activeKeysById,
263 movedId: activeKey,
264 });
265 if (activeReorderableKeys && assignments.some(({ id }) => !activeReorderableKeys.has(id))) {
266 return { kind: "none" };
267 }
268 return {
269 kind: "move-active",
270 order,
271 assignments,
272 unpin: activePinned,
273 unsettle: activeSettled,
274 unsnooze: activeSection === "snoozed",
275 };
276 }
277 case "settled":
278 return activeSection === "settled" ? { kind: "none" } : { kind: "settle" };
279 case "pinned": {
280 const order = target.pinnedOrder;
281 // Dropped back where it started: nothing to write.
282 if (
283 activeSection === "pinned" &&
284 order.length === pinnedOrder.length &&
285 order.every((key, index) => key === pinnedOrder[index])
286 ) {
287 return { kind: "none" };
288 }
289 const assignments = planPinnedReorder({
290 orderedIds: order,
291 keysById: pinnedKeysById,
292 movedId: activeKey,
293 });
294 if (reorderableKeys && assignments.some(({ id }) => !reorderableKeys.has(id))) {
295 return { kind: "none" };
296 }
297 if (activeSection === "pinned") {
298 return assignments.length === 0
299 ? { kind: "none" }
300 : { kind: "reorder-pinned", order, assignments };
301 }
302 return {
303 kind: "pin",
304 order,
305 orderKey: assignments.find((assignment) => assignment.id === activeKey)?.orderKey,
306 extraAssignments: activePinned
307 ? assignments
308 : assignments.filter((assignment) => assignment.id !== activeKey),
309 };
310 }
311 }
313​
314/** Project a drop's lifecycle fields before sorting its destination. Reusing
315 the server's re-entry rules keeps the preview in place when events arrive. */
316export function applySidebarThreadDrop<
317 T extends Pick<
318 SidebarThreadSummary,
319 | "pinnedAt"
320 | "pinOrderKey"
321 | "activeOrderKey"
322 | "snoozedAt"
323 | "snoozedUntil"
324 | "settledAt"
325 | "settledOverride"
326 | "unsettledAt"
327 >,
328>(thread: T, section: "pinned" | "active" | "settled", now: string, orderKey?: string): T {
329 const wasSettled = thread.settledOverride === "settled";
330 const awake = { ...thread, snoozedAt: null, snoozedUntil: null };
331 if (section === "settled") {
332 return {
333 ...awake,
334 pinnedAt: null,
335 pinOrderKey: null,
336 activeOrderKey: null,
337 settledOverride: "settled",
338 settledAt: wasSettled ? (thread.settledAt ?? now) : now,
339 unsettledAt: null,
340 };
341 }
342 const resumed = wasSettled
343 ? { ...awake, settledOverride: "active" as const, settledAt: null, unsettledAt: now }
344 : awake;
345 return {
346 ...resumed,
347 pinnedAt: section === "pinned" ? (thread.pinnedAt ?? now) : null,
348 pinOrderKey: section === "pinned" ? (orderKey ?? thread.pinOrderKey) : null,
349 ...(section === "active" && orderKey !== undefined ? { activeOrderKey: orderKey } : {}),
350 };
352​
353type SidebarProject = {
354 id: string;
355 title: string;
356 createdAt?: string | undefined;
357 updatedAt?: string | undefined;
358};
359​
360type ScopedSidebarProject = SidebarProject & {
361 environmentId: string;
362};
363​
364type ScopedSidebarThread = ThreadSortInput & {
365 environmentId: string;
366 projectId: string;
367 archivedAt: string | null;
368};
369​
370type LogicalSidebarProject = SidebarProject & {
371 projectKey: string;
372 memberProjectRefs: readonly {
373 environmentId: string;
374 projectId: string;
375 }[];
376};
377​
378export type ThreadTraversalDirection = "previous" | "next";
379​
380/**
381 * Shared-worktree checks must exclude only successful deletions, never the
382 * whole batch. A null result skips an entry that the caller can no longer find.
383 */
384export async function deleteSelectedThreadEntries<
385 TEntry extends { readonly threadKey: string },
386>(input: {
387 entries: readonly TEntry[];
388 delete: (
389 entry: TEntry,
390 deletedThreadKeys: ReadonlySet<string>,
391 ) => Promise<AtomCommandResult<unknown, unknown> | null>;
392}) {
393 const deletedThreadKeys = new Set<string>();
394 let firstFailure: AsyncResult.Failure<unknown, unknown> | null = null;
395​
396 for (const entry of input.entries) {
397 const result = await input.delete(entry, deletedThreadKeys);
398 if (result === null) continue;
399 if (result._tag === "Failure") {
400 if (isAtomCommandInterrupted(result)) break;
401 firstFailure ??= result;
402 continue;
403 }
404 deletedThreadKeys.add(entry.threadKey);
405 }
406​
407 return { deletedThreadKeys, firstFailure };
409​
410export async function archiveSelectedThreadEntries<
411 TEntry extends { readonly threadKey: string },
412 TResult extends { readonly _tag: "Success" | "Failure" },
413>(input: {
414 entries: readonly TEntry[];
415 archive: (entry: TEntry, onArchived: () => void) => Promise<TResult>;
416}): Promise<{
417 archivedThreadKeys: readonly string[];
418 mutationFailure: Extract<TResult, { readonly _tag: "Failure" }> | null;
419 followupFailures: readonly Extract<TResult, { readonly _tag: "Failure" }>[];
420}> {
421 const archivedThreadKeys: string[] = [];
422 const followupFailures: Extract<TResult, { readonly _tag: "Failure" }>[] = [];
423​
424 for (const entry of input.entries) {
425 let didArchive = false;
426 const result = await input.archive(entry, () => {
427 didArchive = true;
428 });
429 if (didArchive || result._tag === "Success") {
430 archivedThreadKeys.push(entry.threadKey);
431 }
432 if (result._tag === "Success") continue;
433 const failure = result as Extract<TResult, { readonly _tag: "Failure" }>;
434 if (didArchive) {
435 followupFailures.push(failure);
436 continue;
437 }
438 return { archivedThreadKeys, mutationFailure: failure, followupFailures };
439 }
440​
441 return { archivedThreadKeys, mutationFailure: null, followupFailures };
443​
444export function buildMultiSelectThreadContextMenuItems(input: {
445 count: number;
446 hasRunningThread: boolean;
447}): readonly ContextMenuItem<"mark-unread" | "archive" | "delete">[] {
448 return [
449 { id: "mark-unread", label: `Mark unread (${input.count})` },
450 {
451 id: "archive",
452 label: `Archive (${input.count})`,
453 disabled: input.hasRunningThread,
454 },
455 { id: "delete", label: `Delete (${input.count})`, destructive: true },
456 ];
458​
459export function buildBulkTitleRegenerationContextMenuItem(input: {
460 supportedCount: number;
461 actionableCount: number;
462}): ContextMenuItem<"regenerate-title"> | null {
463 if (input.supportedCount === 0) return null;
464 if (input.actionableCount === 0) {
465 return {
466 id: "regenerate-title",
467 label: `Regenerating… (${input.supportedCount})`,
468 disabled: true,
469 };
470 }
471 return {
472 id: "regenerate-title",
473 label: `Regenerate titles (${input.actionableCount})`,
474 };
476​
477/**
478 * Bulk unpin follows the same "count only what the action will touch" rule
479 * as title regeneration: on a mixed selection the label counts the pinned
480 * rows alone, and the item disappears when nothing selected is pinned.
481 */
482export function buildBulkUnpinContextMenuItem(input: {
483 pinnedCount: number;
484}): ContextMenuItem<"unpin"> | null {
485 if (input.pinnedCount === 0) return null;
486 return { id: "unpin", label: `Unpin (${input.pinnedCount})` };
488​
489export interface ThreadStatusPill {
490 label:
491 | "Working"
492 | "Monitoring"
493 | "Connecting"
494 | "Completed"
495 | "Pending Approval"
496 | "Awaiting Input"
497 | "Plan Ready";
498 colorClass: string;
499 dotClass: string;
500 pulse: boolean;
502​
503// Rollup order mirrors the per-thread resolver exactly: attention states,
504// then active work, then the actionable plan prompt, then passive
505// monitoring. A Monitoring sibling must never hide a Plan Ready thread.
506const THREAD_STATUS_PRIORITY: Record<ThreadStatusPill["label"], number> = {
507 "Pending Approval": 6,
508 "Awaiting Input": 5,
509 Working: 4,
510 Connecting: 4,
511 "Plan Ready": 3,
512 Monitoring: 2,
513 Completed: 1,
514};
515​
516type ThreadStatusInput = Pick<
517 SidebarThreadSummary,
518 | "hasActionableProposedPlan"
519 | "hasPendingApprovals"
520 | "hasPendingUserInput"
521 | "interactionMode"
522 | "latestTurn"
523 | "session"
524 | "backgroundLiveness"
525> & {
526 lastVisitedAt?: string | undefined;
527};
528​
529export interface ThreadJumpHintVisibilityController {
530 sync: (shouldShow: boolean) => void;
531 dispose: () => void;
533​
534export function createThreadJumpHintVisibilityController(input: {
535 delayMs: number;
536 onVisibilityChange: (visible: boolean) => void;
537 setTimeoutFn?: typeof globalThis.setTimeout;
538 clearTimeoutFn?: typeof globalThis.clearTimeout;
539}): ThreadJumpHintVisibilityController {
540 const setTimeoutFn = input.setTimeoutFn ?? globalThis.setTimeout;
541 const clearTimeoutFn = input.clearTimeoutFn ?? globalThis.clearTimeout;
542 let isVisible = false;
543 let timeoutId: NodeJS.Timeout | null = null;
544​
545 const clearPendingShow = () => {
546 if (timeoutId === null) {
547 return;
548 }
549 clearTimeoutFn(timeoutId);
550 timeoutId = null;
551 };
552​
553 return {
554 sync: (shouldShow) => {
555 if (!shouldShow) {
556 clearPendingShow();
557 if (isVisible) {
558 isVisible = false;
559 input.onVisibilityChange(false);
560 }
561 return;
562 }
563​
564 if (isVisible || timeoutId !== null) {
565 return;
566 }
567​
568 timeoutId = setTimeoutFn(() => {
569 timeoutId = null;
570 isVisible = true;
571 input.onVisibilityChange(true);
572 }, input.delayMs);
573 },
574 dispose: () => {
575 clearPendingShow();
576 },
577 };
579​
580export function useThreadJumpHintVisibility(): {
581 showThreadJumpHints: boolean;
582 updateThreadJumpHintsVisibility: (shouldShow: boolean) => void;
583} {
584 const [showThreadJumpHints, setShowThreadJumpHints] = React.useState(false);
585 const controllerRef = React.useRef<ThreadJumpHintVisibilityController | null>(null);
586​
587 React.useEffect(() => {
588 const controller = createThreadJumpHintVisibilityController({
589 delayMs: THREAD_JUMP_HINT_SHOW_DELAY_MS,
590 onVisibilityChange: (visible) => {
591 setShowThreadJumpHints(visible);
592 },
593 setTimeoutFn: window.setTimeout.bind(window),
594 clearTimeoutFn: window.clearTimeout.bind(window),
595 });
596 controllerRef.current = controller;
597​
598 return () => {
599 controller.dispose();
600 controllerRef.current = null;
601 };
602 }, []);
603​
604 const updateThreadJumpHintsVisibility = React.useCallback((shouldShow: boolean) => {
605 controllerRef.current?.sync(shouldShow);
606 }, []);
607​
608 return {
609 showThreadJumpHints,
610 updateThreadJumpHintsVisibility,
611 };
613​
614export function hasUnseenCompletion(thread: ThreadStatusInput): boolean {
615 if (!thread.latestTurn?.completedAt) return false;
616 const completedAt = Date.parse(thread.latestTurn.completedAt);
617 if (Number.isNaN(completedAt)) return false;
618 if (!thread.lastVisitedAt) return false;
619​
620 const lastVisitedAt = Date.parse(thread.lastVisitedAt);
621 if (Number.isNaN(lastVisitedAt)) return true;
622 return completedAt > lastVisitedAt;
624​
625export function shouldClearThreadSelectionOnMouseDown(target: HTMLElement | null): boolean {
626 if (target === null) return true;
627 return !target.closest(THREAD_SELECTION_SAFE_SELECTOR);
629​
630// A double-click dispatches two `click` events before `dblclick`: the first has
631// `detail === 1`, the second `detail === 2`. The second click must not run the
632// row's single-click navigation, otherwise double-click-to-rename would also
633// navigate. `MouseEvent.detail` is 0 for synthetic/keyboard activations, which
634// still count as a normal single activation.
635export function isTrailingDoubleClick(detail: number): boolean {
636 return detail > 1;
638​
639function nodeClosest(node: object | null, selector: string): unknown {
640 if (node === null || !("closest" in node) || typeof node.closest !== "function") return null;
641 return node.closest(selector);
643​
644/** Clicks on a nested link keep the link's meaning. The row must not treat them as multi-select. */
645export function isSidebarNestedLinkClick(target: EventTarget | null): boolean {
646 if (target == null || typeof target !== "object") return false;
647 if (nodeClosest(target, "a[href]") !== null) return true;
648 const parent =
649 "parentElement" in target &&
650 target.parentElement !== null &&
651 typeof target.parentElement === "object"
652 ? target.parentElement
653 : null;
654 return nodeClosest(parent, "a[href]") !== null;
656​
657// Shift+click on the new thread button creates directly in the current
658// project, skipping the command palette's project picker. With a single
659// project there is nothing to pick, so a plain click already creates
660// immediately and the modifier changes nothing.
661export function shouldCreateNewThreadInCurrentProject(
662 shiftKey: boolean,
663 projectGroupCount: number,
664): boolean {
665 return shiftKey || projectGroupCount <= 1;
667​
668export function orderItemsByPreferredIds<TItem, TId>(input: {
669 items: readonly TItem[];
670 preferredIds: readonly TId[];
671 getId: (item: TItem) => TId;
672 getPreferenceIds?: (item: TItem) => readonly TId[];
673}): TItem[] {
674 const { getId, getPreferenceIds, items, preferredIds } = input;
675 if (preferredIds.length === 0) {
676 return [...items];
677 }
678​
679 const indexesByPreferenceId = new Map<TId, number[]>();
680 for (const [index, item] of items.entries()) {
681 const preferenceIds = getPreferenceIds?.(item) ?? [getId(item)];
682 for (const preferenceId of new Set(preferenceIds)) {
683 const indexes = indexesByPreferenceId.get(preferenceId);
684 if (indexes) {
685 indexes.push(index);
686 } else {
687 indexesByPreferenceId.set(preferenceId, [index]);
688 }
689 }
690 }
691​
692 const emittedIndexes = new Set<number>();
693 const ordered = preferredIds.flatMap((id) => {
694 const index = indexesByPreferenceId
695 .get(id)
696 ?.find((candidate) => !emittedIndexes.has(candidate));
697 if (index === undefined) {
698 return [];
699 }
700 emittedIndexes.add(index);
701 return [items[index]!];
702 });
703 const remaining = items.filter((_, index) => !emittedIndexes.has(index));
704 return [...ordered, ...remaining];
706​
707export function getSidebarThreadIdsToPrewarm<TThreadId>(
708 visibleThreadIds: readonly TThreadId[],
709 limit = SIDEBAR_THREAD_PREWARM_LIMIT,
710): TThreadId[] {
711 return visibleThreadIds.slice(0, Math.max(0, limit));
713​
714export function resolveAdjacentThreadId<T>(input: {
715 threadIds: readonly T[];
716 currentThreadId: T | null;
717 direction: ThreadTraversalDirection;
718}): T | null {
719 const { currentThreadId, direction, threadIds } = input;
720​
721 if (threadIds.length === 0) {
722 return null;
723 }
724​
725 if (currentThreadId === null) {
726 return direction === "previous" ? (threadIds.at(-1) ?? null) : (threadIds[0] ?? null);
727 }
728​
729 const currentIndex = threadIds.indexOf(currentThreadId);
730 if (currentIndex === -1) {
731 return null;
732 }
733​
734 if (direction === "previous") {
735 return currentIndex > 0 ? (threadIds[currentIndex - 1] ?? null) : null;
736 }
737​
738 return currentIndex < threadIds.length - 1 ? (threadIds[currentIndex + 1] ?? null) : null;
740​
741export function isContextMenuPointerDown(input: {
742 button: number;
743 ctrlKey: boolean;
744 isMac: boolean;
745}): boolean {
746 if (input.button === 2) return true;
747 return input.isMac && input.button === 0 && input.ctrlKey;
749​
750export function resolveThreadRowClassName(input: {
751 isActive: boolean;
752 isSelected: boolean;
753}): string {
754 const baseClassName =
755 "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";
756​
757 if (input.isSelected && input.isActive) {
758 return cn(
759 baseClassName,
760 "bg-sidebar-row-active text-sidebar-foreground font-medium hover:bg-sidebar-row-active hover:text-sidebar-foreground",
761 );
762 }
763​
764 if (input.isSelected) {
765 return cn(
766 baseClassName,
767 "bg-sidebar-row-selected text-sidebar-foreground hover:bg-sidebar-row-active hover:text-sidebar-foreground",
768 );
769 }
770​
771 if (input.isActive) {
772 return cn(
773 baseClassName,
774 "bg-sidebar-row-active text-sidebar-foreground font-medium hover:bg-sidebar-row-active hover:text-sidebar-foreground",
775 );
776 }
777​
778 return cn(
779 baseClassName,
780 "text-sidebar-muted-foreground/80 hover:bg-sidebar-row-hover hover:text-sidebar-foreground",
781 );
783​
784// ── Sidebar thread status model ─────────────────────────────────────
785// Five visual states, three colors: color is reserved for "act now"
786// (approval), "in motion" (working), and "broken" (failed). Ready is the
787// unlabeled resting state — the agent stopped and is waiting on the user,
788// whether it finished, asked a question, or proposed a plan.
789// Unread completion is tracked separately: it describes whether a ready
790// thread needs attention, not what the thread is currently doing.
791export type SidebarThreadStatus =
792 | "approval"
793 | "input"
794 | "working"
795 | "monitoring"
796 | "failed"
797 | "ready";
798​
799export function shouldRecedeSidebarThread(input: {
800 status: SidebarThreadStatus;
801 isUnread: boolean;
802 isWoke: boolean;
803 isActive: boolean;
804 isSelected: boolean;
805}): boolean {
806 if (input.isActive || input.isSelected) return false;
807 if (input.status === "working" || input.status === "monitoring") return true;
808 if (input.status === "ready" || input.status === "approval" || input.status === "input") {
809 return !input.isUnread && !input.isWoke;
810 }
811 return false;
813​
814type SidebarThreadStatusInput = Pick<
815 SidebarThreadSummary,
816 "hasPendingApprovals" | "hasPendingUserInput" | "session" | "backgroundLiveness"
817>;
818​
819export function resolveSidebarThreadStatus(thread: SidebarThreadStatusInput): SidebarThreadStatus {
820 if (thread.hasPendingApprovals) {
821 return "approval";
822 }
823 if (thread.hasPendingUserInput) {
824 return "input";
825 }
826 if (thread.session?.status === "running" || thread.session?.status === "starting") {
827 return "working";
828 }
829 // A failed session outranks lingering background liveness: the user must
830 // see the failure, not a stale Working (review finding).
831 if (thread.session?.status === "error") {
832 return "failed";
833 }
834 // Background work outlives the turn: fleets read as working; monitoring
835 // only when watch loops are the sole live work.
836 if (thread.backgroundLiveness === "working") {
837 return "working";
838 }
839 if (thread.backgroundLiveness === "monitoring") {
840 return "monitoring";
841 }
842 return "ready";
844​
845/** First VALID timestamp wins: `a ?? b` falls through on null, but a present-
846 yet-malformed string must also fall through to the next candidate rather
847 than sink the row to the epoch. */
848export function firstValidTimestampMs(
849 ...candidates: ReadonlyArray<string | null | undefined>
850): number {
851 for (const candidate of candidates) {
852 if (candidate == null) continue;
853 const parsed = Date.parse(candidate);
854 if (!Number.isNaN(parsed)) return parsed;
855 }
856 return 0;
858​
859/** String twin of firstValidTimestampMs for callers that need the ISO string
860 (display labels, tick anchors) rather than epoch ms. */
861function firstValidTimestamp(
862 ...candidates: ReadonlyArray<string | null | undefined>
863): string | null {
864 for (const candidate of candidates) {
865 if (candidate == null) continue;
866 if (!Number.isNaN(Date.parse(candidate))) return candidate;
867 }
868 return null;
870​
871export { sortActiveThreadsByOrderKey as sortThreadsForSidebar } from "@t3tools/client-runtime/state/thread-sort";
872​
873// Pinned-reorder key math and the keyed sort live in client-runtime
874// (state/thread-sort) so web and mobile compute identical pinned orders.
875export { pinOrderKeyBetween, planPinnedReorder } from "@t3tools/client-runtime/state/thread-sort";
876export { sortPinnedThreadsByOrderKey as sortPinnedThreadsForSidebar } from "@t3tools/client-runtime/state/thread-sort";
877​
878/**
879 * Search the already-ordered sidebar thread collection by title or linked PR.
880 * Keeping the input order means lifecycle ordering (active, snoozed, settled)
881 * remains stable while the user narrows the list.
882 */
883export function searchSidebarThreads<
884 T extends { readonly title: string } & Parameters<typeof threadPullRequestSearchTerms>[0],
885>(threads: readonly T[], query: string): T[] {
886 const normalizedQuery = query.trim().toLowerCase();
887 if (normalizedQuery.length === 0) return [];
888 return threads.filter((thread) =>
889 [thread.title, ...threadPullRequestSearchTerms(thread)].some((term) =>
890 term.toLowerCase().includes(normalizedQuery),
891 ),
892 );
894​
895export function filterSidebarProjectScopeItems<TItem extends { readonly value: string }>(input: {
896 items: readonly TItem[];
897 activeScopeKey: string | null;
898 query: string;
899 matches: (item: TItem, query: string) => boolean;
900}): readonly TItem[] {
901 const projectItems = input.items.filter((item) => item.value !== "all");
902 const query = input.query.trim();
903 if (query.length > 0) {
904 return projectItems.filter((item) => input.matches(item, query));
905 }
906 return input.activeScopeKey === null ? projectItems : input.items;
908​
909export interface SidebarProjectScopeMenuState {
910 readonly open: boolean;
911 readonly query: string;
913​
914export type SidebarProjectScopeMenuAction =
915 | { readonly type: "query-changed"; readonly query: string }
916 | { readonly type: "open-changed"; readonly open: boolean }
917 | { readonly type: "project-settings-opened" };
918​
919export function reduceSidebarProjectScopeMenuState(
920 state: SidebarProjectScopeMenuState,
921 action: SidebarProjectScopeMenuAction,
922): SidebarProjectScopeMenuState {
923 switch (action.type) {
924 case "query-changed":
925 return { ...state, query: action.query };
926 case "open-changed":
927 return { open: action.open, query: "" };
928 case "project-settings-opened":
929 return { open: false, query: "" };
930 }
932​
933// Settled rows are history, so they order by when the work ENDED, not when
934// the thread was created or last touched.
935export function sortSettledThreadsForSidebar<
936 T extends SettledThreadTimestampInput & { readonly id: string },
937>(threads: readonly T[]): T[] {
938 const timestampMs = (thread: T) => {
939 const timestamp = resolveSettledThreadTimestamp(thread);
940 return timestamp === null ? 0 : Date.parse(timestamp);
941 };
942 return [...threads].toSorted(
943 (left, right) => timestampMs(right) - timestampMs(left) || left.id.localeCompare(right.id),
944 );
946​
947/** The timestamp a working thread's elapsed label counts from: the running
948 turn's start (request time until adoption), falling back to the session's
949 last transition when the turn projection lags behind. Malformed
950 timestamps fall through to the next candidate, not just missing ones. */
951export function resolveWorkingStartedAt(
952 thread: Pick<SidebarThreadSummary, "latestTurn" | "session">,
953): string | null {
954 const turn = thread.latestTurn;
955 if (turn && turn.completedAt === null) {
956 return firstValidTimestamp(turn.startedAt, turn.requestedAt, thread.session?.updatedAt);
957 }
958 return firstValidTimestamp(thread.session?.updatedAt);
960​
961export function formatWorkingDurationLabel(elapsedMs: number): string {
962 const seconds = Number.isFinite(elapsedMs) ? Math.max(0, Math.floor(elapsedMs / 1000)) : 0;
963 if (seconds < 60) return `${seconds}s`;
964 const minutes = Math.floor(seconds / 60);
965 if (minutes < 60) return `${minutes}m`;
966 return `${Math.floor(minutes / 60)}h ${minutes % 60}m`;
968​
969export function resolveThreadStatusPill(input: {
970 thread: ThreadStatusInput;
971}): ThreadStatusPill | null {
972 const { thread } = input;
973​
974 if (thread.hasPendingApprovals) {
975 return {
976 label: "Pending Approval",
977 colorClass: "text-amber-600 dark:text-amber-300/90",
978 dotClass: "bg-amber-500 dark:bg-amber-300/90",
979 pulse: false,
980 };
981 }
982​
983 if (thread.hasPendingUserInput) {
984 return {
985 label: "Awaiting Input",
986 colorClass: "text-indigo-600 dark:text-indigo-300/90",
987 dotClass: "bg-indigo-500 dark:bg-indigo-300/90",
988 pulse: false,
989 };
990 }
991​
992 if (thread.session?.status === "running") {
993 return {
994 label: "Working",
995 colorClass: "text-sky-600 dark:text-sky-300/80",
996 dotClass: "bg-sky-500 dark:bg-sky-300/80",
997 pulse: true,
998 };
999 }
1000​
1001 if (thread.session?.status === "starting") {
1002 return {
1003 label: "Connecting",
1004 colorClass: "text-sky-600 dark:text-sky-300/80",
1005 dotClass: "bg-sky-500 dark:bg-sky-300/80",
1006 pulse: true,
1007 };
1009​
1010 // An actionable plan prompt outranks lingering background work: it needs
1011 // the user's decision, while liveness merely reports (review finding).
1012 const hasPlanReadyPrompt =
1013 !thread.hasPendingUserInput &&
1014 thread.interactionMode === "plan" &&
1015 isLatestTurnSettled(thread.latestTurn, thread.session) &&
1016 thread.hasActionableProposedPlan;
1017 if (hasPlanReadyPrompt) {
1018 return {
1019 label: "Plan Ready",
1020 colorClass: "text-violet-600 dark:text-violet-300/90",
1021 dotClass: "bg-violet-500 dark:bg-violet-300/90",
1022 pulse: false,
1023 };
1025​
1026 // The turn can settle while native background work runs on. Subagent and
1027 // workflow fleets read as plain Working; Monitoring is reserved for watch
1028 // loops (a parent agent babysitting a PR, tailing checks) with no other
1029 // live work. Same recede treatment as Working per inbox-zero.
1030 if (thread.backgroundLiveness === "working") {
1031 return {
1032 label: "Working",
1033 colorClass: "text-sky-600 dark:text-sky-300/80",
1034 dotClass: "bg-sky-500 dark:bg-sky-300/80",
1035 pulse: true,
1036 };
1038​
1039 if (thread.backgroundLiveness === "monitoring") {
1040 return {
1041 label: "Monitoring",
1042 colorClass: "text-sky-600 dark:text-sky-300/80",
1043 dotClass: "bg-sky-500 dark:bg-sky-300/80",
1044 pulse: false,
1045 };
1047​
1048 if (hasUnseenCompletion(thread)) {
1049 return {
1050 label: "Completed",
1051 colorClass: "text-emerald-600 dark:text-emerald-300/90",
1052 dotClass: "bg-emerald-500 dark:bg-emerald-300/90",
1053 pulse: false,
1054 };
1056​
1057 return null;
1059​
1060export function resolveProjectStatusIndicator(
1061 statuses: ReadonlyArray<ThreadStatusPill | null>,
1062): ThreadStatusPill | null {
1063 let highestPriorityStatus: ThreadStatusPill | null = null;
1064​
1065 for (const status of statuses) {
1066 if (status === null) continue;
1067 if (
1068 highestPriorityStatus === null ||
1069 THREAD_STATUS_PRIORITY[status.label] > THREAD_STATUS_PRIORITY[highestPriorityStatus.label]
1070 ) {
1071 highestPriorityStatus = status;
1074​
1075 return highestPriorityStatus;
1077​
1078export function getFallbackThreadIdAfterDelete<
1079 T extends Pick<Thread, "id" | "projectId" | "createdAt" | "updatedAt"> & ThreadSortInput,
1080>(input: {
1081 threads: readonly T[];
1082 deletedThreadId: T["id"];
1083 sortOrder: SidebarThreadSortOrder;
1084 deletedThreadIds?: ReadonlySet<T["id"]>;
1085}): T["id"] | null {
1086 const { deletedThreadId, deletedThreadIds, sortOrder, threads } = input;
1087 const deletedThread = threads.find((thread) => thread.id === deletedThreadId);
1088 if (!deletedThread) {
1089 return null;
1091​
1092 return (
1093 sortThreads(
1094 threads.filter(
1095 (thread) =>
1096 thread.projectId === deletedThread.projectId &&
1097 thread.id !== deletedThreadId &&
1098 !deletedThreadIds?.has(thread.id),
1099 ),
1100 sortOrder,
1101 )[0]?.id ?? null
1102 );
1104export function getProjectSortTimestamp(
1105 project: SidebarProject,
1106 projectThreads: readonly ThreadSortInput[],
1107 sortOrder: Exclude<SidebarProjectSortOrder, "manual">,
1108): number {
1109 if (projectThreads.length > 0) {
1110 return projectThreads.reduce(
1111 (latest, thread) => Math.max(latest, getThreadSortTimestamp(thread, sortOrder)),
1112 Number.NEGATIVE_INFINITY,
1113 );
1115​
1116 if (sortOrder === "created_at") {
1117 return toSortableTimestamp(project.createdAt) ?? Number.NEGATIVE_INFINITY;
1119 return toSortableTimestamp(project.updatedAt ?? project.createdAt) ?? Number.NEGATIVE_INFINITY;
1121​
1122function sortProjectsByActivity<TProject extends SidebarProject>(
1123 projects: readonly TProject[],
1124 sortOrder: SidebarProjectSortOrder,
1125 getProjectThreads: (project: TProject) => readonly ThreadSortInput[],
1126 compareTies: (left: TProject, right: TProject) => number,
1127): TProject[] {
1128 if (sortOrder === "manual") {
1129 return [...projects];
1131​
1132 return [...projects].toSorted((left, right) => {
1133 const rightTimestamp = getProjectSortTimestamp(right, getProjectThreads(right), sortOrder);
1134 const leftTimestamp = getProjectSortTimestamp(left, getProjectThreads(left), sortOrder);
1135 const byTimestamp =
1136 rightTimestamp === leftTimestamp ? 0 : rightTimestamp > leftTimestamp ? 1 : -1;
1137 return byTimestamp || compareTies(left, right);
1138 });
1140​
1141export function sortProjectsForSidebar<
1142 TProject extends SidebarProject,
1143 TThread extends Pick<Thread, "projectId" | "createdAt" | "updatedAt"> & ThreadSortInput,
1145 projects: readonly TProject[],
1146 threads: readonly TThread[],
1147 sortOrder: SidebarProjectSortOrder,
1148): TProject[] {
1149 const threadsByProjectId = new Map<string, TThread[]>();
1150 for (const thread of threads) {
1151 const existing = threadsByProjectId.get(thread.projectId) ?? [];
1152 existing.push(thread);
1153 threadsByProjectId.set(thread.projectId, existing);
1155​
1156 return sortProjectsByActivity(
1157 projects,
1158 sortOrder,
1159 (project) => threadsByProjectId.get(project.id) ?? [],
1160 (left, right) => left.title.localeCompare(right.title) || left.id.localeCompare(right.id),
1161 );
1163​
1164export function sortLogicalProjectsForSidebar<
1165 TProject extends LogicalSidebarProject,
1166 TThread extends ScopedSidebarThread,
1168 projects: readonly TProject[],
1169 threads: readonly TThread[],
1170 sortOrder: SidebarProjectSortOrder,
1171): TProject[] {
1172 const groupKeyByProjectRef = new Map(
1173 projects.flatMap((project) =>
1174 project.memberProjectRefs.map(
1175 (projectRef) =>
1176 [`${projectRef.environmentId}\0${projectRef.projectId}`, project.projectKey] as const,
1177 ),
1178 ),
1179 );
1180 const threadsByProjectKey = new Map<string, TThread[]>();
1181 for (const thread of threads) {
1182 if (thread.archivedAt !== null) continue;
1183 const projectKey = groupKeyByProjectRef.get(`${thread.environmentId}\0${thread.projectId}`);
1184 if (!projectKey) continue;
1185 const existing = threadsByProjectKey.get(projectKey);
1186 if (existing) {
1187 existing.push(thread);
1188 } else {
1189 threadsByProjectKey.set(projectKey, [thread]);
1192​
1193 return sortProjectsByActivity(
1194 projects,
1195 sortOrder,
1196 (project) => threadsByProjectKey.get(project.projectKey) ?? [],
1197 (left, right) =>
1198 left.title.localeCompare(right.title) || left.projectKey.localeCompare(right.projectKey),
1199 );
1201​
1202/**
1203 * Sorts the cross-environment project collection used by landing surfaces.
1204 * Project ids are only unique within an environment, and archived threads
1205 * must not make a project appear recently active.
1206 */
1207export function sortScopedProjectsForSidebar<
1208 TProject extends ScopedSidebarProject,
1209 TThread extends ScopedSidebarThread,
1211 projects: readonly TProject[],
1212 threads: readonly TThread[],
1213 sortOrder: SidebarProjectSortOrder,
1214): TProject[] {
1215 const scopedKey = (environmentId: string, projectId: string) =>
1216 `${environmentId}\u0000${projectId}`;
1217 const threadsByProject = new Map<string, TThread[]>();
1218 for (const thread of threads) {
1219 if (thread.archivedAt !== null) {
1220 continue;
1222 const key = scopedKey(thread.environmentId, thread.projectId);
1223 const existing = threadsByProject.get(key) ?? [];
1224 existing.push(thread);
1225 threadsByProject.set(key, existing);
1227​
1228 return sortProjectsByActivity(
1229 projects,
1230 sortOrder,
1231 (project) => threadsByProject.get(scopedKey(project.environmentId, project.id)) ?? [],
1232 (left, right) =>
1233 left.title.localeCompare(right.title) ||
1234 left.environmentId.localeCompare(right.environmentId) ||
1235 left.id.localeCompare(right.id),
1236 );