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

Sidebar.logic.ts

1,267 lines42.4 KB

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