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

Sidebar.logic.ts

1,314 lines43.1 KB

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