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

Sidebar.logic.ts

1,353 lines42.7 KB

1import { resolveThreadWorkingStartedAt } from "@t3tools/client-runtime/state/models";
2import { backgroundWorkHoldsCompletion } from "@t3tools/shared/orchestrationV2PendingBackgroundWork";
3import { threadPullRequestSearchTerms } from "@t3tools/shared/threadPullRequests";
4import * as React from "react";
5import {
6 isAtomCommandInterrupted,
7 type AtomCommandResult,
8} from "@t3tools/client-runtime/state/runtime";
9import { defaultAnimateLayoutChanges, type AnimateLayoutChanges } from "@dnd-kit/sortable";
10import { threadSearchMatchKey } from "@t3tools/client-runtime/state/thread-search";
11import type { ContextMenuItem, EnvironmentId, ThreadId } from "@t3tools/contracts";
12import type { SidebarProjectSortOrder, SidebarThreadSortOrder } from "@t3tools/contracts/settings";
13import type { AsyncResult } from "effect/reactivity";
14import { planPinnedReorder } from "@t3tools/client-runtime/state/thread-sort";
15import {
16 effectiveSnoozed,
17 type ThreadSnoozeShell,
18} from "@t3tools/client-runtime/state/thread-settled";
19import {
20 getThreadSortTimestamp,
21 sortThreads,
22 toSortableTimestamp,
23 type ThreadSortInput,
24} from "../lib/threadSort";
25import type { SidebarThreadSummary, Thread } from "../types";
26import { cn, normalizeSearchText } from "../lib/utils";
27import { isLatestRunSettled } from "../session-logic";
28import { resolveServerBackedAppStageLabel } from "../branding.logic";
29​
30export function shouldNavigateAfterThreadPark(input: {
31 readonly threadKey: string;
32 readonly currentThreadKey: string | null;
33 readonly action: "settle" | "snooze";
34 readonly now: string;
35 readonly thread: (ThreadSnoozeShell & Pick<SidebarThreadSummary, "settledOverride">) | null;
36}): boolean {
37 return (
38 input.threadKey === input.currentThreadKey &&
39 input.thread !== null &&
40 (input.action === "settle"
41 ? input.thread.settledOverride === "settled"
42 : effectiveSnoozed(input.thread, { now: input.now }))
43 );
45​
46const THREAD_SELECTION_SAFE_SELECTOR = "[data-thread-item], [data-thread-selection-safe]";
47export const THREAD_JUMP_HINT_SHOW_DELAY_MS = 200;
48​
49export function resolveSidebarRowAccessibility(input: {
50 readonly title: string;
51 readonly statusLabel: string | null;
52 readonly projectDisplayName: string | null;
53 readonly isActive: boolean;
54}): { readonly label: string; readonly current: "page" | undefined } {
55 return {
56 label: [input.title, input.statusLabel, input.projectDisplayName].filter(Boolean).join(", "),
57 current: input.isActive ? "page" : undefined,
58 };
60​
61// Each prewarmed thread holds a live, fully hydrated detail subscription (all
62// messages and activities, growing as agents work) for as long as the row stays
63// visible, so this limit is a direct renderer-heap and server-load multiplier —
64// keep it small; cold opens still render instantly from the cached snapshot.
65const SIDEBAR_THREAD_PREWARM_LIMIT = 3;
66const SIDEBAR_ROW_SUBSCRIPTION_OVERSCAN_PX = 160;
67​
68export function useSidebarRowSubscriptionLease(isActive: boolean): {
69 readonly leaseLiveStatus: boolean;
70 readonly rowRef: React.Dispatch<React.SetStateAction<HTMLElement | null>>;
71} {
72 const [row, setRow] = React.useState<HTMLElement | null>(null);
73 const [isNearViewport, setIsNearViewport] = React.useState(isActive);
74 // The active row stays leased after it deactivates until the observer reports.
75 if (isActive && !isNearViewport) setIsNearViewport(true);
76 const canObserve = typeof IntersectionObserver !== "undefined";
77​
78 React.useEffect(() => {
79 if (isActive || row === null || !canObserve) return;
80​
81 const scrollRoot = row.closest<HTMLElement>('[data-slot="scroll-area-viewport"]');
82 const observer = new IntersectionObserver(
83 ([entry]) => setIsNearViewport(entry?.isIntersecting === true),
84 {
85 root: scrollRoot,
86 rootMargin: `${SIDEBAR_ROW_SUBSCRIPTION_OVERSCAN_PX}px 0px`,
87 },
88 );
89 observer.observe(row);
90 return () => observer.disconnect();
91 }, [canObserve, isActive, row]);
92​
93 return {
94 leaseLiveStatus: isActive || isNearViewport || !canObserve,
95 rowRef: setRow,
96 };
98​
99export function useRetainedValue<T>(key: string | null, value: T | null): T | null {
100 const [retained, setRetained] = React.useState<{
101 readonly key: string;
102 readonly value: T;
103 } | null>(null);
104 if (key !== null && value !== null && (retained?.key !== key || retained.value !== value)) {
105 setRetained({ key, value });
106 }
107 if (value !== null) return value;
108 return key !== null && retained?.key === key ? retained.value : null;
110​
111// Sidebar.motion handles ordinary section changes. Sortable transforms own
112// dragging; replaying their committed DOM order would animate the drop twice.
113export const animateSidebarLayoutChanges: AnimateLayoutChanges = (args) =>
114 args.isSorting ? defaultAnimateLayoutChanges(args) : false;
115​
116// Snoozed rows can leave the shelf, but dropping into it is not supported
117// because snoozing requires a wake time. The Working shelf (beta) follows live
118// status, so it is neither a drag source nor a destination.
119​
120export type SidebarSection = "pinned" | "active" | "working" | "snoozed" | "settled";
121​
122export function resolveSidebarThreadSection(input: {
123 readonly snoozed: boolean;
124 readonly settled: boolean;
125 readonly pinned: boolean;
126}): SidebarSection {
127 if (input.snoozed) return "snoozed";
128 if (input.settled) return "settled";
129 if (input.pinned) return "pinned";
130 return "active";
132​
133const SIDEBAR_MARKER_PREFIX = "sidebar-marker-";
134​
135export type SidebarListMarker =
136 | "pinned-header"
137 | "active-placeholder"
138 | "settled-placeholder"
139 | "pinned-divider"
140 | "working-header"
141 | "snoozed-header"
142 | "settled-header";
143​
144export function sidebarMarkerId(marker: SidebarListMarker): string {
145 return `${SIDEBAR_MARKER_PREFIX}${marker}`;
147​
148export type SidebarListItem =
149 | { readonly kind: "thread"; readonly key: string; readonly section: SidebarSection }
150 | { readonly kind: "marker"; readonly marker: SidebarListMarker };
151​
152export function sidebarListItemId(item: SidebarListItem): string {
153 return item.kind === "thread" ? item.key : sidebarMarkerId(item.marker);
155​
156function sectionAtSidebarSlot(items: readonly SidebarListItem[], index: number): SidebarSection {
157 let section: SidebarSection = "pinned";
158 for (let i = 0; i < index && i < items.length; i += 1) {
159 const item = items[i]!;
160 if (item.kind !== "marker") continue;
161 if (item.marker === "pinned-divider") section = "active";
162 else if (item.marker === "working-header") section = "working";
163 else if (item.marker === "snoozed-header") section = "snoozed";
164 else if (item.marker === "settled-header") section = "settled";
165 }
166 return section;
168​
169export type SidebarDropTarget = {
170 readonly section: "pinned" | "active" | "settled";
171 readonly pinnedOrder: readonly string[];
172 readonly activeOrder: readonly string[];
173};
174​
175export function resolveSidebarDropTarget(
176 items: readonly SidebarListItem[],
177 activeKey: string,
178 overId: string,
179): SidebarDropTarget | null {
180 const activeIndex = items.findIndex((item) => sidebarListItemId(item) === activeKey);
181 const overIndex = items.findIndex((item) => sidebarListItemId(item) === overId);
182 if (activeIndex === -1 || overIndex === -1 || items[activeIndex]?.kind !== "thread") return null;
183 const moved = items.filter((_, index) => index !== activeIndex);
184 moved.splice(overIndex, 0, items[activeIndex]!);
185 const section = sectionAtSidebarSlot(moved, overIndex);
186 if (section === "working" || section === "snoozed") return null;
187 const pinnedOrder: string[] = [];
188 const activeOrder: string[] = [];
189 let currentSection: SidebarSection = "pinned";
190 for (const item of moved) {
191 if (item.kind === "marker") {
192 if (item.marker === "pinned-divider") currentSection = "active";
193 else if (
194 item.marker === "working-header" ||
195 item.marker === "snoozed-header" ||
196 item.marker === "settled-header"
197 )
198 break;
199 } else if (currentSection === "pinned") pinnedOrder.push(item.key);
200 else activeOrder.push(item.key);
201 }
202 return { section, pinnedOrder, activeOrder };
204​
205export type SidebarThreadDropPlan =
206 | { readonly kind: "none" }
207 | {
208 readonly kind: "reorder-pinned";
209 readonly order: readonly string[];
210 readonly assignments: ReadonlyArray<{ readonly id: string; readonly orderKey: string }>;
211 }
212 | {
213 readonly kind: "pin";
214 readonly order: readonly string[];
215 readonly orderKey: string | undefined;
216 readonly extraAssignments: ReadonlyArray<{ readonly id: string; readonly orderKey: string }>;
217 }
218 | {
219 readonly kind: "move-active";
220 readonly order: readonly string[] | null;
221 readonly assignments: ReadonlyArray<{ readonly id: string; readonly orderKey: string }>;
222 readonly unpin: boolean;
223 readonly unsettle: boolean;
224 readonly unsnooze: boolean;
225 }
226 | { readonly kind: "settle" };
227​
228export type SidebarDropVerb = "pin" | "unpin" | "settle" | "unsettle" | "wake";
229​
230export function resolveSidebarDropVerb(
231 from: SidebarSection,
232 to: SidebarSection | null,
233): SidebarDropVerb | null {
234 if (to === null || to === from || to === "working" || to === "snoozed") return null;
235 if (to === "pinned") return "pin";
236 if (to === "settled") return "settle";
237 if (from === "pinned") return "unpin";
238 if (from === "settled") return "unsettle";
239 return "wake";
241​
242export function resolveSidebarSweepKeys(
243 orderedKeys: readonly string[],
244 originKey: string,
245 targetKey: string,
246 canApply: (key: string) => boolean,
247): string[] {
248 const origin = orderedKeys.indexOf(originKey);
249 const target = orderedKeys.indexOf(targetKey);
250 if (origin === -1 || target === -1) return [];
251 return orderedKeys.slice(Math.min(origin, target), Math.max(origin, target) + 1).filter(canApply);
253​
254export function sidebarThreadKeyAtY(list: HTMLElement, y: number): string | null {
255 const viewport = list.closest('[data-slot="scroll-area-viewport"]')?.getBoundingClientRect();
256 const visibleY = viewport ? Math.min(Math.max(y, viewport.top), viewport.bottom - 1) : y;
257 let key: string | null = null;
258 for (const row of list.querySelectorAll<HTMLElement>("li[data-thread-item]")) {
259 if (key !== null && row.getBoundingClientRect().top > visibleY) break;
260 key = row.dataset.threadItem ?? null;
261 }
262 return key;
264​
265export function planSidebarThreadDrop(input: {
266 readonly activeKey: string;
267 readonly activeSection: SidebarSection;
268 readonly activePinned?: boolean;
269 readonly activeSettled?: boolean;
270 readonly supportsSettlement?: boolean;
271 readonly target: SidebarDropTarget;
272 readonly pinnedOrder: readonly string[];
273 readonly pinnedKeysById: ReadonlyMap<string, string | null | undefined>;
274 readonly reorderableKeys?: ReadonlySet<string>;
275 readonly activeOrder: readonly string[];
276 readonly activeKeysById: ReadonlyMap<string, string | null | undefined>;
277 readonly activeReorderableKeys?: ReadonlySet<string>;
278 readonly activeTimeOrdered?: boolean;
279}): SidebarThreadDropPlan {
280 const {
281 activeKey,
282 activeSection,
283 activePinned = activeSection === "pinned",
284 activeSettled = activeSection === "settled",
285 target,
286 pinnedOrder,
287 pinnedKeysById,
288 reorderableKeys,
289 activeOrder,
290 activeKeysById,
291 activeReorderableKeys,
292 } = input;
293 if (input.supportsSettlement === false && (target.section === "settled" || activeSettled)) {
294 return { kind: "none" };
295 }
296 const arrange = (
297 order: readonly string[],
298 keysById: ReadonlyMap<string, string | null | undefined>,
299 writable: ReadonlySet<string> | undefined,
300 ) => {
301 if (!writable) return planPinnedReorder({ orderedIds: order, keysById, movedId: activeKey });
302 if (!writable.has(activeKey)) return null;
303 const assignments = planPinnedReorder({
304 orderedIds: order.filter((key) => writable.has(key) || keysById.get(key) != null),
305 keysById,
306 movedId: activeKey,
307 });
308 return assignments.every(({ id }) => writable.has(id)) ? assignments : null;
309 };
310 switch (target.section) {
311 case "active": {
312 if (input.activeTimeOrdered) {
313 return activeSection === "active"
314 ? { kind: "none" }
315 : {
316 kind: "move-active",
317 order: null,
318 assignments: [],
319 unpin: activePinned,
320 unsettle: activeSettled,
321 unsnooze: activeSection === "snoozed",
322 };
323 }
324 const order = target.activeOrder;
325 if (
326 activeSection === "active" &&
327 order.length === activeOrder.length &&
328 order.every((key, index) => key === activeOrder[index])
329 ) {
330 return { kind: "none" };
331 }
332 const assignments = arrange(order, activeKeysById, activeReorderableKeys);
333 if (assignments === null) return { kind: "none" };
334 return {
335 kind: "move-active",
336 order,
337 assignments,
338 unpin: activePinned,
339 unsettle: activeSettled,
340 unsnooze: activeSection === "snoozed",
341 };
342 }
343 case "settled":
344 return activeSection === "settled" ? { kind: "none" } : { kind: "settle" };
345 case "pinned": {
346 const order = target.pinnedOrder;
347 if (
348 activeSection === "pinned" &&
349 order.length === pinnedOrder.length &&
350 order.every((key, index) => key === pinnedOrder[index])
351 ) {
352 return { kind: "none" };
353 }
354 const assignments = arrange(order, pinnedKeysById, reorderableKeys);
355 if (assignments === null) return { kind: "none" };
356 if (activeSection === "pinned") {
357 return assignments.length === 0
358 ? { kind: "none" }
359 : { kind: "reorder-pinned", order, assignments };
360 }
361 return {
362 kind: "pin",
363 order,
364 orderKey: assignments.find((assignment) => assignment.id === activeKey)?.orderKey,
365 extraAssignments: activePinned
366 ? assignments
367 : assignments.filter((assignment) => assignment.id !== activeKey),
368 };
369 }
370 }
372​
373export function applySidebarThreadDrop<
374 T extends Pick<
375 SidebarThreadSummary,
376 | "pinnedAt"
377 | "pinOrderKey"
378 | "activeOrderKey"
379 | "snoozedAt"
380 | "snoozedUntil"
381 | "settledAt"
382 | "settledOverride"
383 | "unsettledAt"
384 >,
385>(thread: T, section: "pinned" | "active" | "settled", now: string, orderKey?: string): T {
386 const wasSettled = thread.settledOverride === "settled";
387 const awake = { ...thread, snoozedAt: null, snoozedUntil: null };
388 if (section === "settled") {
389 return {
390 ...awake,
391 pinnedAt: null,
392 pinOrderKey: null,
393 activeOrderKey: null,
394 settledOverride: "settled",
395 settledAt: wasSettled ? (thread.settledAt ?? now) : now,
396 unsettledAt: null,
397 };
398 }
399 const resumed = wasSettled
400 ? { ...awake, settledOverride: "active" as const, settledAt: null, unsettledAt: now }
401 : awake;
402 return {
403 ...resumed,
404 pinnedAt: section === "pinned" ? (thread.pinnedAt ?? now) : null,
405 pinOrderKey: section === "pinned" ? (orderKey ?? thread.pinOrderKey) : null,
406 ...(section === "active" && orderKey !== undefined ? { activeOrderKey: orderKey } : {}),
407 };
409​
410type SidebarProject = {
411 id: string;
412 title: string;
413 createdAt?: string | undefined;
414 updatedAt?: string | undefined;
415};
416​
417type ScopedSidebarProject = SidebarProject & {
418 environmentId: string;
419};
420​
421type ScopedSidebarThread = ThreadSortInput & {
422 environmentId: string;
423 projectId: string;
424 archivedAt: string | null;
425};
426​
427type LogicalSidebarProject = SidebarProject & {
428 projectKey: string;
429 memberProjectRefs: readonly {
430 environmentId: string;
431 projectId: string;
432 }[];
433};
434​
435export type ThreadTraversalDirection = "previous" | "next";
436​
437/**
438 * Shared-worktree checks must exclude only successful deletions, never the
439 * whole batch.
440 */
441export async function deleteSelectedThreadEntries<
442 TEntry extends { readonly threadKey: string },
443>(input: {
444 entries: readonly TEntry[];
445 delete: (
446 entry: TEntry,
447 deletedThreadKeys: ReadonlySet<string>,
448 ) => Promise<AtomCommandResult<unknown, unknown> | null>;
449}) {
450 const deletedThreadKeys = new Set<string>();
451 let firstFailure: AsyncResult.Failure<unknown, unknown> | null = null;
452​
453 for (const entry of input.entries) {
454 const result = await input.delete(entry, deletedThreadKeys);
455 if (result === null) continue;
456 if (result._tag === "Failure") {
457 if (isAtomCommandInterrupted(result)) break;
458 firstFailure ??= result;
459 continue;
460 }
461 deletedThreadKeys.add(entry.threadKey);
462 }
463​
464 return { deletedThreadKeys, firstFailure };
466​
467export async function archiveSelectedThreadEntries<
468 TEntry extends { readonly threadKey: string },
469 TResult extends { readonly _tag: "Success" | "Failure" },
470>(input: {
471 entries: readonly TEntry[];
472 archive: (entry: TEntry, onArchived: () => void) => Promise<TResult>;
473}): Promise<{
474 archivedThreadKeys: readonly string[];
475 mutationFailure: Extract<TResult, { readonly _tag: "Failure" }> | null;
476 followupFailures: readonly Extract<TResult, { readonly _tag: "Failure" }>[];
477}> {
478 const archivedThreadKeys: string[] = [];
479 const followupFailures: Extract<TResult, { readonly _tag: "Failure" }>[] = [];
480​
481 for (const entry of input.entries) {
482 let didArchive = false;
483 const result = await input.archive(entry, () => {
484 didArchive = true;
485 });
486 if (didArchive || result._tag === "Success") archivedThreadKeys.push(entry.threadKey);
487 if (result._tag === "Success") continue;
488 const failure = result as Extract<TResult, { readonly _tag: "Failure" }>;
489 if (didArchive) {
490 followupFailures.push(failure);
491 continue;
492 }
493 return { archivedThreadKeys, mutationFailure: failure, followupFailures };
494 }
495​
496 return { archivedThreadKeys, mutationFailure: null, followupFailures };
498​
499export function buildMultiSelectThreadContextMenuItems(input: {
500 count: number;
501 hasRunningThread: boolean;
502}): readonly ContextMenuItem<"mark-unread" | "archive" | "delete">[] {
503 return [
504 { id: "mark-unread", label: `Mark unread (${input.count})` },
505 {
506 id: "archive",
507 label: `Archive (${input.count})`,
508 disabled: input.hasRunningThread,
509 },
510 { id: "delete", label: `Delete (${input.count})`, destructive: true },
511 ];
513​
514export function isSidebarSubagentThread(thread: Pick<SidebarThreadSummary, "lineage">): boolean {
515 return thread.lineage.relationshipToParent === "subagent";
517​
518export function filterSidebarV2VisibleThreads<
519 T extends Pick<SidebarThreadSummary, "archivedAt" | "lineage"> & {
520 environmentId: string;
521 projectId: string;
522 },
523>(threads: readonly T[], scopedProjectKeys: ReadonlySet<string> | null): T[] {
524 return threads.filter(
525 (thread) =>
526 thread.archivedAt === null &&
527 !isSidebarSubagentThread(thread) &&
528 (scopedProjectKeys === null ||
529 scopedProjectKeys.has(`${thread.environmentId}:${thread.projectId}`)),
530 );
532​
533export function getSidebarForkParentThreadId(
534 thread: Pick<SidebarThreadSummary, "forkedFrom" | "lineage">,
535) {
536 if (thread.lineage.relationshipToParent !== "fork") {
537 return null;
538 }
539 return thread.forkedFrom?.type === "run"
540 ? thread.forkedFrom.threadId
541 : thread.lineage.parentThreadId;
543​
544export function buildBulkTitleRegenerationContextMenuItem(input: {
545 supportedCount: number;
546 actionableCount: number;
547}): ContextMenuItem<"regenerate-title"> | null {
548 if (input.supportedCount === 0) return null;
549 if (input.actionableCount === 0) {
550 return {
551 id: "regenerate-title",
552 label: `Regenerating… (${input.supportedCount})`,
553 disabled: true,
554 };
555 }
556 return {
557 id: "regenerate-title",
558 label: `Regenerate titles (${input.actionableCount})`,
559 };
561​
562export function buildBulkUnpinContextMenuItem(input: {
563 pinnedCount: number;
564}): ContextMenuItem<"unpin"> | null {
565 if (input.pinnedCount === 0) return null;
566 return { id: "unpin", label: `Unpin (${input.pinnedCount})` };
568​
569export interface ThreadStatusPill {
570 label:
571 | "Working"
572 | "Connecting"
573 | "Completed"
574 | "Pending Approval"
575 | "Awaiting Input"
576 | "Waiting"
577 | "Plan Ready";
578 colorClass: string;
579 dotClass: string;
580 pulse: boolean;
582​
583const THREAD_STATUS_PRIORITY: Record<ThreadStatusPill["label"], number> = {
584 "Pending Approval": 5,
585 "Awaiting Input": 4,
586 Working: 3,
587 Connecting: 3,
588 Waiting: 2.5,
589 "Plan Ready": 2,
590 Completed: 1,
591};
592​
593type ThreadStatusInput = Pick<
594 SidebarThreadSummary,
595 | "hasActionableProposedPlan"
596 | "hasPendingApprovals"
597 | "hasPendingUserInput"
598 | "pendingSubagentRequest"
599 | "interactionMode"
600 | "latestRun"
601 | "runtime"
602> & {
603 lastVisitedAt?: string | null | undefined;
604 pendingBackgroundTasks?: SidebarThreadSummary["pendingBackgroundTasks"] | undefined;
605};
606​
607export interface ThreadJumpHintVisibilityController {
608 sync: (shouldShow: boolean) => void;
609 dispose: () => void;
611​
612export function resolveSidebarStageBadgeLabel(input: {
613 primaryServerVersion: string | null | undefined;
614 fallbackStageLabel: string;
615}): string {
616 return resolveServerBackedAppStageLabel(input);
618​
619export function createThreadJumpHintVisibilityController(input: {
620 delayMs: number;
621 onVisibilityChange: (visible: boolean) => void;
622 setTimeoutFn?: typeof globalThis.setTimeout;
623 clearTimeoutFn?: typeof globalThis.clearTimeout;
624}): ThreadJumpHintVisibilityController {
625 const setTimeoutFn = input.setTimeoutFn ?? globalThis.setTimeout;
626 const clearTimeoutFn = input.clearTimeoutFn ?? globalThis.clearTimeout;
627 let isVisible = false;
628 let timeoutId: NodeJS.Timeout | null = null;
629​
630 const clearPendingShow = () => {
631 if (timeoutId === null) {
632 return;
633 }
634 clearTimeoutFn(timeoutId);
635 timeoutId = null;
636 };
637​
638 return {
639 sync: (shouldShow) => {
640 if (!shouldShow) {
641 clearPendingShow();
642 if (isVisible) {
643 isVisible = false;
644 input.onVisibilityChange(false);
645 }
646 return;
647 }
648​
649 if (isVisible || timeoutId !== null) {
650 return;
651 }
652​
653 timeoutId = setTimeoutFn(() => {
654 timeoutId = null;
655 isVisible = true;
656 input.onVisibilityChange(true);
657 }, input.delayMs);
658 },
659 dispose: () => {
660 clearPendingShow();
661 },
662 };
664​
665export function useThreadJumpHintVisibility(): {
666 showThreadJumpHints: boolean;
667 updateThreadJumpHintsVisibility: (shouldShow: boolean) => void;
668} {
669 const [showThreadJumpHints, setShowThreadJumpHints] = React.useState(false);
670 const controllerRef = React.useRef<ThreadJumpHintVisibilityController | null>(null);
671​
672 React.useEffect(() => {
673 const controller = createThreadJumpHintVisibilityController({
674 delayMs: THREAD_JUMP_HINT_SHOW_DELAY_MS,
675 onVisibilityChange: (visible) => {
676 setShowThreadJumpHints(visible);
677 },
678 setTimeoutFn: window.setTimeout.bind(window),
679 clearTimeoutFn: window.clearTimeout.bind(window),
680 });
681 controllerRef.current = controller;
682​
683 return () => {
684 controller.dispose();
685 controllerRef.current = null;
686 };
687 }, []);
688​
689 const updateThreadJumpHintsVisibility = (shouldShow: boolean) => {
690 controllerRef.current?.sync(shouldShow);
691 };
692​
693 return {
694 showThreadJumpHints,
695 updateThreadJumpHintsVisibility,
696 };
698​
699export function resolveThreadLastVisitedAt(
700 serverLastVisitedAt: string | null | undefined,
701 localLastVisitedAt: string | undefined,
702): string | undefined {
703 // When the server tracks visits it is authoritative — including explicit
704 // rewinds from mark-unread, which a newer browser-local watermark must not
705 // mask. The local value only carries servers without visited tracking.
706 if (serverLastVisitedAt === undefined) return localLastVisitedAt;
707 return serverLastVisitedAt ?? undefined;
709​
710export function hasUnseenCompletion(thread: ThreadStatusInput): boolean {
711 if (!thread.latestRun?.completedAt) return false;
712 const completedAt = Date.parse(thread.latestRun.completedAt);
713 if (Number.isNaN(completedAt)) return false;
714 if (!thread.lastVisitedAt) return false;
715​
716 const lastVisitedAt = Date.parse(thread.lastVisitedAt);
717 if (Number.isNaN(lastVisitedAt)) return true;
718 return completedAt > lastVisitedAt;
720​
721export function shouldClearThreadSelectionOnMouseDown(target: HTMLElement | null): boolean {
722 if (target === null) return true;
723 return !target.closest(THREAD_SELECTION_SAFE_SELECTOR);
725​
726// A double-click dispatches two `click` events before `dblclick`: the first has
727// `detail === 1`, the second `detail === 2`. The second click must not run the
728// row's single-click navigation, otherwise double-click-to-rename would also
729// navigate. `MouseEvent.detail` is 0 for synthetic/keyboard activations, which
730// still count as a normal single activation.
731export function isTrailingDoubleClick(detail: number): boolean {
732 return detail > 1;
734​
735function nodeClosest(node: object | null, selector: string): unknown {
736 if (node === null || !("closest" in node) || typeof node.closest !== "function") return null;
737 return node.closest(selector);
739​
740export function isSidebarNestedLinkClick(target: EventTarget | null): boolean {
741 if (target == null || typeof target !== "object") return false;
742 if (nodeClosest(target, "a[href]") !== null) return true;
743 const parent =
744 "parentElement" in target &&
745 target.parentElement !== null &&
746 typeof target.parentElement === "object"
747 ? target.parentElement
748 : null;
749 return nodeClosest(parent, "a[href]") !== null;
751​
752export function shouldCreateNewThreadInCurrentProject(
753 shiftKey: boolean,
754 projectGroupCount: number,
755): boolean {
756 return shiftKey || projectGroupCount <= 1;
758​
759export function orderItemsByPreferredIds<TItem, TId>(input: {
760 items: readonly TItem[];
761 preferredIds: readonly TId[];
762 getId: (item: TItem) => TId;
763 getPreferenceIds?: (item: TItem) => readonly TId[];
764}): TItem[] {
765 const { getId, getPreferenceIds, items, preferredIds } = input;
766 if (preferredIds.length === 0) {
767 return [...items];
768 }
769​
770 const indexesByPreferenceId = new Map<TId, number[]>();
771 for (const [index, item] of items.entries()) {
772 const preferenceIds = getPreferenceIds?.(item) ?? [getId(item)];
773 for (const preferenceId of new Set(preferenceIds)) {
774 const indexes = indexesByPreferenceId.get(preferenceId);
775 if (indexes) {
776 indexes.push(index);
777 } else {
778 indexesByPreferenceId.set(preferenceId, [index]);
779 }
780 }
781 }
782​
783 const emittedIndexes = new Set<number>();
784 const ordered = preferredIds.flatMap((id) => {
785 const index = indexesByPreferenceId
786 .get(id)
787 ?.find((candidate) => !emittedIndexes.has(candidate));
788 if (index === undefined) {
789 return [];
790 }
791 emittedIndexes.add(index);
792 return [items[index]!];
793 });
794 const remaining = items.filter((_, index) => !emittedIndexes.has(index));
795 return [...ordered, ...remaining];
797​
798export function getSidebarThreadIdsToPrewarm<TThreadId>(
799 visibleThreadIds: readonly TThreadId[],
800 limit = SIDEBAR_THREAD_PREWARM_LIMIT,
801): TThreadId[] {
802 return visibleThreadIds.slice(0, Math.max(0, limit));
804​
805export function resolveAdjacentThreadId<T>(input: {
806 threadIds: readonly T[];
807 currentThreadId: T | null;
808 direction: ThreadTraversalDirection;
809}): T | null {
810 const { currentThreadId, direction, threadIds } = input;
811​
812 if (threadIds.length === 0) {
813 return null;
814 }
815​
816 if (currentThreadId === null) {
817 return direction === "previous" ? (threadIds.at(-1) ?? null) : (threadIds[0] ?? null);
818 }
819​
820 const currentIndex = threadIds.indexOf(currentThreadId);
821 if (currentIndex === -1) {
822 return null;
823 }
824​
825 if (direction === "previous") {
826 return currentIndex > 0 ? (threadIds[currentIndex - 1] ?? null) : null;
827 }
828​
829 return currentIndex < threadIds.length - 1 ? (threadIds[currentIndex + 1] ?? null) : null;
831​
832export function isContextMenuPointerDown(input: {
833 button: number;
834 ctrlKey: boolean;
835 isMac: boolean;
836}): boolean {
837 if (input.button === 2) return true;
838 return input.isMac && input.button === 0 && input.ctrlKey;
840​
841export function resolveThreadRowClassName(input: {
842 isActive: boolean;
843 isSelected: boolean;
844}): string {
845 const baseClassName =
846 "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";
847​
848 if (input.isSelected && input.isActive) {
849 return cn(
850 baseClassName,
851 "bg-sidebar-row-active text-sidebar-foreground font-medium hover:bg-sidebar-row-active hover:text-sidebar-foreground",
852 );
853 }
854​
855 if (input.isSelected) {
856 return cn(
857 baseClassName,
858 "bg-sidebar-row-selected text-sidebar-foreground hover:bg-sidebar-row-active hover:text-sidebar-foreground",
859 );
860 }
861​
862 if (input.isActive) {
863 return cn(
864 baseClassName,
865 "bg-sidebar-row-active text-sidebar-foreground font-medium hover:bg-sidebar-row-active hover:text-sidebar-foreground",
866 );
867 }
868​
869 return cn(
870 baseClassName,
871 "text-sidebar-muted-foreground/80 hover:bg-sidebar-row-hover hover:text-sidebar-foreground",
872 );
874​
875export type SidebarThreadStatus =
876 | "approval"
877 | "input"
878 | "working"
879 | "waiting"
880 | "failed"
881 | "limited"
882 | "ready";
883​
884export function shouldRecedeSidebarThread(input: {
885 status: SidebarThreadStatus;
886 isUnread: boolean;
887 isWoke: boolean;
888 isActive: boolean;
889 isSelected: boolean;
890}): boolean {
891 if (input.isActive || input.isSelected || input.status === "input") return false;
892 if (input.status === "working" || input.status === "waiting") return true;
893 if (input.status === "ready" || input.status === "approval") {
894 return !input.isUnread && !input.isWoke;
895 }
896 return false;
898​
899type SidebarThreadStatusInput = Pick<
900 SidebarThreadSummary,
901 "hasPendingApprovals" | "hasPendingUserInput" | "pendingSubagentRequest" | "runtime"
902>;
903​
904export function resolveSidebarThreadStatus(thread: SidebarThreadStatusInput): SidebarThreadStatus {
905 if (thread.hasPendingApprovals || thread.pendingSubagentRequest === "approval") {
906 return "approval";
907 }
908 if (thread.hasPendingUserInput || thread.pendingSubagentRequest === "user_input") {
909 return "input";
910 }
911 if (
912 thread.runtime !== null &&
913 ["preparing", "queued", "starting", "running", "waiting"].includes(thread.runtime.status)
914 ) {
915 return "working";
916 }
917 if (thread.runtime?.status === "idle") {
918 return "waiting";
919 }
920 if (thread.runtime?.status === "failed") {
921 return thread.runtime.lastErrorClass === "usage_limit" ? "limited" : "failed";
922 }
923 return "ready";
925​
926export type SidebarV2TopStatusKind =
927 | "approval"
928 | "done"
929 | "failed"
930 | "limited"
931 | "input"
932 | "waiting"
933 | "woke"
934 | "working";
935​
936export function resolveSidebarV2TopStatus(input: {
937 readonly status: SidebarThreadStatus;
938 readonly isUnread: boolean;
939 readonly isWoke: boolean;
940}): SidebarV2TopStatusKind | null {
941 if (input.status === "working") {
942 return "working";
943 }
944 if (input.status === "waiting") {
945 return "waiting";
946 }
947 if (input.status === "approval") {
948 return "approval";
949 }
950 if (input.status === "input") {
951 return "input";
952 }
953 if (input.status === "failed" || input.status === "limited") {
954 return input.status;
955 }
956 if (input.isWoke) {
957 return "woke";
958 }
959 return input.isUnread ? "done" : null;
961​
962export function shouldShowSidebarV2Duration(status: SidebarThreadStatus): boolean {
963 return status === "working";
965​
966export function firstValidTimestampMs(
967 ...candidates: ReadonlyArray<string | null | undefined>
968): number {
969 for (const candidate of candidates) {
970 if (candidate == null) continue;
971 const parsed = Date.parse(candidate);
972 if (!Number.isNaN(parsed)) return parsed;
973 }
974 return 0;
976​
977export { sortActiveThreadsByOrderKey as sortThreadsForSidebar } from "@t3tools/client-runtime/state/thread-sort";
978export {
979 isThreadWorking as isSidebarThreadWorking,
980 sortInboxThreadsByReturn,
981 sortWorkingThreadsBySend,
982} from "@t3tools/client-runtime/state/thread-inbox";
983​
984export { pinOrderKeyBetween } from "@t3tools/client-runtime/state/thread-sort";
985export { sortPinnedThreadsByOrderKey as sortPinnedThreadsForSidebar } from "@t3tools/client-runtime/state/thread-sort";
986​
987const EMPTY_CONTENT_MATCH_KEYS: ReadonlySet<string> = new Set<string>();
988​
989export function searchSidebarThreads<
990 T extends {
991 readonly environmentId: EnvironmentId;
992 readonly id: ThreadId;
993 readonly title: string;
994 } & Parameters<typeof threadPullRequestSearchTerms>[0],
995>(
996 threads: readonly T[],
997 query: string,
998 contentMatchKeys: ReadonlySet<string> = EMPTY_CONTENT_MATCH_KEYS,
999): T[] {
1000 const normalizedQuery = query.trim().toLowerCase();
1001 if (normalizedQuery.length === 0) return [];
1002 const titleMatches: T[] = [];
1003 const contentMatches: T[] = [];
1004 for (const thread of threads) {
1005 const matchesTitle = [thread.title, ...threadPullRequestSearchTerms(thread)].some((term) =>
1006 term.toLowerCase().includes(normalizedQuery),
1007 );
1008 if (matchesTitle) {
1009 titleMatches.push(thread);
1010 } else if (
1011 contentMatchKeys.size > 0 &&
1012 contentMatchKeys.has(
1013 threadSearchMatchKey({ environmentId: thread.environmentId, threadId: thread.id }),
1015 ) {
1016 contentMatches.push(thread);
1019 return [...titleMatches, ...contentMatches];
1021​
1022export function pullRequestMatchesSearchQuery(
1023 pullRequest: Parameters<typeof threadPullRequestSearchTerms>[0],
1024 query: string,
1025): boolean {
1026 const normalizedQuery = normalizeSearchText(query);
1027 if (normalizedQuery.length === 0) return false;
1028 const haystack = normalizeSearchText(threadPullRequestSearchTerms(pullRequest).join(" "));
1029 return normalizedQuery.split(" ").every((token) => haystack.includes(token));
1031​
1032export function filterSidebarProjectScopeItems<TItem extends { readonly value: string }>(input: {
1033 items: readonly TItem[];
1034 query: string;
1035 matches: (item: TItem, query: string) => boolean;
1036}): readonly TItem[] {
1037 const query = input.query.trim();
1038 if (query.length === 0) return input.items;
1039 return input.items.filter((item) => item.value !== "all" && input.matches(item, query));
1041​
1042export interface SidebarProjectScopeMenuState {
1043 readonly open: boolean;
1044 readonly query: string;
1046​
1047export type SidebarProjectScopeMenuAction =
1048 | { readonly type: "query-changed"; readonly query: string }
1049 | { readonly type: "open-changed"; readonly open: boolean }
1050 | { readonly type: "project-settings-opened" };
1051​
1052export function reduceSidebarProjectScopeMenuState(
1053 state: SidebarProjectScopeMenuState,
1054 action: SidebarProjectScopeMenuAction,
1055): SidebarProjectScopeMenuState {
1056 switch (action.type) {
1057 case "query-changed":
1058 return { ...state, query: action.query };
1059 case "open-changed":
1060 return { open: action.open, query: "" };
1061 case "project-settings-opened":
1062 return { open: false, query: "" };
1065​
1066export function resolveWorkingStartedAt(
1067 thread: Pick<SidebarThreadSummary, "latestRun" | "runtime">,
1068): string | null {
1069 return resolveThreadWorkingStartedAt(thread);
1071​
1072export function formatWorkingDurationLabel(elapsedMs: number): string {
1073 const seconds = Number.isFinite(elapsedMs) ? Math.max(0, Math.floor(elapsedMs / 1000)) : 0;
1074 if (seconds < 60) return `${seconds}s`;
1075 const minutes = Math.floor(seconds / 60);
1076 if (minutes < 60) return `${minutes}m`;
1077 return `${Math.floor(minutes / 60)}h ${minutes % 60}m`;
1079​
1080export function resolveThreadStatusPill(input: {
1081 thread: ThreadStatusInput;
1082}): ThreadStatusPill | null {
1083 const { thread } = input;
1084​
1085 if (thread.hasPendingApprovals || thread.pendingSubagentRequest === "approval") {
1086 return {
1087 label: "Pending Approval",
1088 colorClass: "text-amber-600 dark:text-amber-300/90",
1089 dotClass: "bg-amber-500 dark:bg-amber-300/90",
1090 pulse: false,
1091 };
1093​
1094 if (thread.hasPendingUserInput || thread.pendingSubagentRequest === "user_input") {
1095 return {
1096 label: "Awaiting Input",
1097 colorClass: "text-indigo-600 dark:text-indigo-300/90",
1098 dotClass: "bg-indigo-500 dark:bg-indigo-300/90",
1099 pulse: false,
1100 };
1102​
1103 if (thread.runtime?.status === "running" || thread.runtime?.status === "waiting") {
1104 return {
1105 label: "Working",
1106 colorClass: "text-sky-600 dark:text-sky-300/80",
1107 dotClass: "bg-sky-500 dark:bg-sky-300/80",
1108 pulse: true,
1109 };
1111​
1112 if (
1113 thread.runtime?.status === "preparing" ||
1114 thread.runtime?.status === "starting" ||
1115 thread.runtime?.status === "queued"
1116 ) {
1117 return {
1118 label: "Connecting",
1119 colorClass: "text-sky-600 dark:text-sky-300/80",
1120 dotClass: "bg-sky-500 dark:bg-sky-300/80",
1121 pulse: true,
1122 };
1124​
1125 if (backgroundWorkHoldsCompletion(thread.pendingBackgroundTasks ?? [])) {
1126 return {
1127 label: "Waiting",
1128 colorClass: "text-sidebar-muted-foreground",
1129 dotClass: "bg-sidebar-muted-foreground",
1130 pulse: false,
1131 };
1133​
1134 const hasPlanReadyPrompt =
1135 !thread.hasPendingUserInput &&
1136 thread.interactionMode === "plan" &&
1137 isLatestRunSettled(thread.latestRun, thread.runtime) &&
1138 thread.hasActionableProposedPlan;
1139 if (hasPlanReadyPrompt) {
1140 return {
1141 label: "Plan Ready",
1142 colorClass: "text-violet-600 dark:text-violet-300/90",
1143 dotClass: "bg-violet-500 dark:bg-violet-300/90",
1144 pulse: false,
1145 };
1147​
1148 if (hasUnseenCompletion(thread)) {
1149 return {
1150 label: "Completed",
1151 colorClass: "text-emerald-600 dark:text-emerald-300/90",
1152 dotClass: "bg-emerald-500 dark:bg-emerald-300/90",
1153 pulse: false,
1154 };
1156​
1157 return null;
1159​
1160export function resolveProjectStatusIndicator(
1161 statuses: ReadonlyArray<ThreadStatusPill | null>,
1162): ThreadStatusPill | null {
1163 let highestPriorityStatus: ThreadStatusPill | null = null;
1164​
1165 for (const status of statuses) {
1166 if (status === null) continue;
1167 if (
1168 highestPriorityStatus === null ||
1169 THREAD_STATUS_PRIORITY[status.label] > THREAD_STATUS_PRIORITY[highestPriorityStatus.label]
1170 ) {
1171 highestPriorityStatus = status;
1174​
1175 return highestPriorityStatus;
1177​
1178export function getFallbackThreadIdAfterDelete<
1179 T extends Pick<Thread, "id" | "projectId" | "createdAt" | "updatedAt"> & ThreadSortInput,
1180>(input: {
1181 threads: readonly T[];
1182 deletedThreadId: T["id"];
1183 sortOrder: SidebarThreadSortOrder;
1184 deletedThreadIds?: ReadonlySet<T["id"]>;
1185}): T["id"] | null {
1186 const { deletedThreadId, deletedThreadIds, sortOrder, threads } = input;
1187 const deletedThread = threads.find((thread) => thread.id === deletedThreadId);
1188 if (!deletedThread) {
1189 return null;
1191​
1192 return (
1193 sortThreads(
1194 threads.filter(
1195 (thread) =>
1196 thread.projectId === deletedThread.projectId &&
1197 thread.id !== deletedThreadId &&
1198 !deletedThreadIds?.has(thread.id),
1199 ),
1200 sortOrder,
1201 )[0]?.id ?? null
1202 );
1204export function getProjectSortTimestamp(
1205 project: SidebarProject,
1206 projectThreads: readonly ThreadSortInput[],
1207 sortOrder: Exclude<SidebarProjectSortOrder, "manual">,
1208): number {
1209 if (projectThreads.length > 0) {
1210 return projectThreads.reduce(
1211 (latest, thread) => Math.max(latest, getThreadSortTimestamp(thread, sortOrder)),
1212 Number.NEGATIVE_INFINITY,
1213 );
1215​
1216 if (sortOrder === "created_at") {
1217 return toSortableTimestamp(project.createdAt) ?? Number.NEGATIVE_INFINITY;
1219 return toSortableTimestamp(project.updatedAt ?? project.createdAt) ?? Number.NEGATIVE_INFINITY;
1221​
1222function sortProjectsByActivity<TProject extends SidebarProject>(
1223 projects: readonly TProject[],
1224 sortOrder: SidebarProjectSortOrder,
1225 getProjectThreads: (project: TProject) => readonly ThreadSortInput[],
1226 compareTies: (left: TProject, right: TProject) => number,
1227): TProject[] {
1228 if (sortOrder === "manual") {
1229 return [...projects];
1231​
1232 // Each project's timestamp walks all of its threads, so compute it once
1233 // per project instead of once per comparison.
1234 return projects
1235 .map((project) => ({
1236 project,
1237 timestamp: getProjectSortTimestamp(project, getProjectThreads(project), sortOrder),
1238 }))
1239 .sort((left, right) => {
1240 const byTimestamp =
1241 right.timestamp === left.timestamp ? 0 : right.timestamp > left.timestamp ? 1 : -1;
1242 return byTimestamp || compareTies(left.project, right.project);
1243 })
1244 .map(({ project }) => project);
1246​
1247export function sortProjectsForSidebar<
1248 TProject extends SidebarProject,
1249 TThread extends Pick<Thread, "projectId" | "createdAt" | "updatedAt"> & ThreadSortInput,
1251 projects: readonly TProject[],
1252 threads: readonly TThread[],
1253 sortOrder: SidebarProjectSortOrder,
1254): TProject[] {
1255 const threadsByProjectId = new Map<string, TThread[]>();
1256 for (const thread of threads) {
1257 const existing = threadsByProjectId.get(thread.projectId) ?? [];
1258 existing.push(thread);
1259 threadsByProjectId.set(thread.projectId, existing);
1261​
1262 return sortProjectsByActivity(
1263 projects,
1264 sortOrder,
1265 (project) => threadsByProjectId.get(project.id) ?? [],
1266 (left, right) => left.title.localeCompare(right.title) || left.id.localeCompare(right.id),
1267 );
1269​
1270export function sortLogicalProjectsForSidebar<
1271 TProject extends LogicalSidebarProject,
1272 TThread extends ScopedSidebarThread,
1274 projects: readonly TProject[],
1275 threads: readonly TThread[],
1276 sortOrder: SidebarProjectSortOrder,
1277): TProject[] {
1278 const groupKeyByProjectRef = new Map(
1279 projects.flatMap((project) =>
1280 project.memberProjectRefs.map(
1281 (projectRef) =>
1282 [`${projectRef.environmentId}\0${projectRef.projectId}`, project.projectKey] as const,
1283 ),
1284 ),
1285 );
1286 const threadsByProjectKey = new Map<string, TThread[]>();
1287 for (const thread of threads) {
1288 if (thread.archivedAt !== null) continue;
1289 const projectKey = groupKeyByProjectRef.get(`${thread.environmentId}\0${thread.projectId}`);
1290 if (!projectKey) continue;
1291 const existing = threadsByProjectKey.get(projectKey);
1292 if (existing) {
1293 existing.push(thread);
1294 } else {
1295 threadsByProjectKey.set(projectKey, [thread]);
1298​
1299 return sortProjectsByActivity(
1300 projects,
1301 sortOrder,
1302 (project) => threadsByProjectKey.get(project.projectKey) ?? [],
1303 (left, right) =>
1304 left.title.localeCompare(right.title) || left.projectKey.localeCompare(right.projectKey),
1305 );
1307​
1308export function sortSidebarV2ProjectGroups<
1309 TProject extends LogicalSidebarProject,
1310 TThread extends ScopedSidebarThread & Pick<SidebarThreadSummary, "lineage">,
1312 projects: readonly TProject[],
1313 threads: readonly TThread[],
1314 sortOrder: SidebarProjectSortOrder,
1315): TProject[] {
1316 return sortLogicalProjectsForSidebar(
1317 projects,
1318 filterSidebarV2VisibleThreads(threads, null),
1319 sortOrder,
1320 );
1322​
1323export function sortScopedProjectsForSidebar<
1324 TProject extends ScopedSidebarProject,
1325 TThread extends ScopedSidebarThread,
1327 projects: readonly TProject[],
1328 threads: readonly TThread[],
1329 sortOrder: SidebarProjectSortOrder,
1330): TProject[] {
1331 const scopedKey = (environmentId: string, projectId: string) =>
1332 `${environmentId}\u0000${projectId}`;
1333 const threadsByProject = new Map<string, TThread[]>();
1334 for (const thread of threads) {
1335 if (thread.archivedAt !== null) {
1336 continue;
1338 const key = scopedKey(thread.environmentId, thread.projectId);
1339 const existing = threadsByProject.get(key) ?? [];
1340 existing.push(thread);
1341 threadsByProject.set(key, existing);
1343​
1344 return sortProjectsByActivity(
1345 projects,
1346 sortOrder,
1347 (project) => threadsByProject.get(scopedKey(project.environmentId, project.id)) ?? [],
1348 (left, right) =>
1349 left.title.localeCompare(right.title) ||
1350 left.environmentId.localeCompare(right.environmentId) ||
1351 left.id.localeCompare(right.id),
1352 );