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

Sidebar.logic.ts

1,337 lines44.0 KB

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