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

Sidebar.logic.ts

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