Open History to see the last commit
1import type { EnvironmentServerConfig } from "@t3tools/client-runtime/connection";
2import { scopeThreadRef, scopedThreadKey } from "@t3tools/client-runtime/environment";
3import { resolveThreadWorkingStartedAt } from "@t3tools/client-runtime/state/models";
4import { isShownUnderParent } from "@t3tools/client-runtime/state/threads";
5import { backgroundWorkHoldsCompletion } from "@t3tools/shared/orchestrationV2PendingBackgroundWork";
6import { threadPullRequestSearchTerms } from "@t3tools/shared/threadPullRequests";
7import * as React from "react";
8import { msg } from "gt-react";
9import { m, type MessageResolver } from "../i18n/messages";
10import {
11 isAtomCommandInterrupted,
12 type AtomCommandResult,
13} from "@t3tools/client-runtime/state/runtime";
14import { defaultAnimateLayoutChanges, type AnimateLayoutChanges } from "@dnd-kit/sortable";
15import {
16 threadSearchMatchKey,
17 threadSearchSubject,
18 type ThreadSearchShell,
19} from "@t3tools/client-runtime/state/thread-search";
20import { foldSearchQuery, rankSearchItems, scoreThreadSearch } from "@t3tools/shared/paletteSearch";
21import {
22 type ContextMenuItem,
23 type EnvironmentId,
24 type ResolvedKeybindingsConfig,
25 type ScopedThreadRef,
26 type ThreadId,
27} from "@t3tools/contracts";
28import type { SidebarProjectSortOrder, SidebarThreadSortOrder } from "@t3tools/contracts/settings";
29import type { AsyncResult } from "effect/reactivity";
30import {
31 effectiveSnoozed,
32 hasUnseenRunFailure,
33 type ThreadSnoozeShell,
34} from "@t3tools/client-runtime/state/thread-settled";
35import {
36 getThreadSortTimestamp,
37 planPinnedReorder,
38 sortThreads,
39 toSortableTimestamp,
40 type ThreadSortInput,
41} from "@t3tools/client-runtime/state/thread-sort";
42import type { SidebarThreadSummary, Thread } from "../types";
43import { normalizeSearchText } from "../lib/utils";
44import { isLatestRunSettled } from "../session-logic";
45import { THREAD_STATUS_TEXT } from "@t3tools/client-runtime/state/thread-activity-announcement";
46import { observeIntersection } from "../lib/observeIntersection";
47import { deadlineAfter, deadlineStore, type ClockStore } from "@t3tools/client-runtime/clock";
48import { useDeadlinePassed } from "../hooks/useDeadline";
49import { legacyProjectCwdPreferenceKey } from "../uiStateStore";
50import { isElectron } from "../env";
51import { shouldShowThreadJumpHintsForModifiers } from "../keybindings";
52import { isTerminalFocused, subscribeToTerminalFocusChanges } from "../lib/terminalFocus";
53import { isPreviewFocused } from "../lib/previewFocus";
54import { isModelPickerOpen, subscribeToModelPickerVisibility } from "../modelPickerVisibility";
55import { shortcutModifierStore } from "../shortcutModifierState";
56import { selectThreadTerminalUiState, useTerminalUiStateStore } from "../terminalUiStateStore";
57import { selectActiveRightPanel, useRightPanelStore } from "../rightPanelStore";
58
59export function shouldNavigateAfterThreadPark(input: {
60 readonly threadKey: string;
61 readonly currentThreadKey: string | null;
62 readonly action: "settle" | "snooze";
63 readonly now: string;
64 readonly thread: (ThreadSnoozeShell & Pick<SidebarThreadSummary, "settledOverride">) | null;
65}): boolean {
66 return (
67 input.threadKey === input.currentThreadKey &&
68 input.thread !== null &&
69 (input.action === "settle"
70 ? input.thread.settledOverride === "settled"
71 : effectiveSnoozed(input.thread, { now: input.now }))
72 );
73}
74
75export const THREAD_JUMP_HINT_SHOW_DELAY_MS = 200;
76
77export function resolveSidebarRowAccessibility(input: {
78 readonly title: string;
79 readonly statusLabel: string | null;
80 readonly projectDisplayName: string | null;
81 readonly isActive: boolean;
82}): { readonly label: string; readonly current: "page" | undefined } {
83 return {
84 label: [input.title, input.statusLabel, input.projectDisplayName].filter(Boolean).join(", "),
85 current: input.isActive ? "page" : undefined,
86 };
87}
88
89// Each prewarm retains growing thread detail and a live subscription, multiplying heap and server load.
90const SIDEBAR_ROW_SUBSCRIPTION_OVERSCAN_PX = 160;
91
92export function useSidebarRowSubscriptionLease(isActive: boolean): {
93 readonly leaseLiveStatus: boolean;
94 readonly rowRef: (row: HTMLElement | null) => (() => void) | undefined;
95} {
96 const [isNearViewport, setIsNearViewport] = React.useState(isActive);
97 if (isActive && !isNearViewport) setIsNearViewport(true);
98 const canObserve = typeof IntersectionObserver !== "undefined";
99
100 return {
101 leaseLiveStatus: isActive || isNearViewport || !canObserve,
102 rowRef: (row) => {
103 if (row === null || isActive || !canObserve) return undefined;
104 // The overscan has to apply to the sidebar's own scroller; a viewport-rooted
105 // margin is still clipped by it.
106 return observeIntersection(row, (entry) => setIsNearViewport(entry.isIntersecting), {
107 root: row.closest('[data-slot="scroll-area-viewport"]'),
108 rootMargin: `${SIDEBAR_ROW_SUBSCRIPTION_OVERSCAN_PX}px 0px`,
109 });
110 },
111 };
112}
113
114const fileDragClears = new Set<(active: false) => void>();
115function clearFileDrags() {
116 const clears = [...fileDragClears];
117 fileDragClears.clear();
118 for (const clear of clears) clear(false);
119}
120
121/**
122 * A file drag that ends outside every drop target (Escape, or a drop elsewhere)
123 * sends no dragleave to the row it last entered, so the window's dragend clears it.
124 */
125export function setFileDragActive(setActive: (active: boolean) => void, active: boolean) {
126 setActive(active);
127 if (typeof window === "undefined") return;
128 if (!active) {
129 if (fileDragClears.delete(setActive) && fileDragClears.size === 0) {
130 window.removeEventListener("dragend", clearFileDrags);
131 }
132 return;
133 }
134 if (fileDragClears.size === 0) window.addEventListener("dragend", clearFileDrags, { once: true });
135 fileDragClears.add(setActive);
136}
137
138/**
139 * A clock that advances exactly when a snooze wake time passes, so a woken
140 * thread leaves the shelf on time without a per-second clock.
141 */
142export function useSnoozeWakeClock(
143 threads: ReadonlyArray<{ readonly snoozedUntil?: string | null | undefined }>,
144): number {
145 const [clockMs, setClockMs] = React.useState(() => Date.now());
146 const wakeTimes: number[] = [];
147 let nextWakeAt: number | null = null;
148 for (const thread of threads) {
149 const wakeAt = thread.snoozedUntil == null ? Number.NaN : Date.parse(thread.snoozedUntil);
150 if (!(wakeAt > clockMs)) continue;
151 wakeTimes.push(wakeAt);
152 if (nextWakeAt === null || wakeAt < nextWakeAt) nextWakeAt = wakeAt;
153 }
154 const woke = useDeadlinePassed(nextWakeAt);
155 // Advancing to the latest wake that has passed skips every wake that elapsed
156 // meanwhile, e.g. across a laptop sleep. Stepping one wake at a time would
157 // re-render once per elapsed wake and hit React's limit.
158 if (woke && nextWakeAt !== null) {
159 let nextClockMs = nextWakeAt;
160 for (const wakeAt of wakeTimes) {
161 if (wakeAt > nextClockMs && deadlineStore(wakeAt).getSnapshot()) nextClockMs = wakeAt;
162 }
163 setClockMs(nextClockMs);
164 return nextClockMs;
165 }
166 return clockMs;
167}
168
169// Live status that says the cwd is not a repository means the checkout was removed. A worktree
170// thread of a project with tracked folders may sit in a plain task folder, which never is one.
171export function withoutRemovedCheckout<
172 T extends { readonly branch: string | null; readonly worktreePath: string | null },
173>(
174 thread: T,
175 gitStatus: { readonly isRepo?: boolean | undefined } | null,
176 project: { readonly trackedFolders?: ReadonlyArray<unknown> | undefined } | null,
177): T {
178 if (gitStatus?.isRepo !== false) return thread;
179 if (thread.worktreePath !== null && (project?.trackedFolders?.length ?? 0) > 0) return thread;
180 return { ...thread, branch: null, worktreePath: null };
181}
182
183export function useRetainedValue<T>(key: string | null, value: T | null): T | null {
184 const [retained, setRetained] = React.useState<{
185 readonly key: string;
186 readonly value: T;
187 } | null>(null);
188 if (key !== null && value !== null && (retained?.key !== key || retained.value !== value)) {
189 setRetained({ key, value });
190 }
191 if (value !== null) return value;
192 return key !== null && retained?.key === key ? retained.value : null;
193}
194
195// Sortable owns drag transforms; replaying committed order would animate drops twice.
196export const animateSidebarLayoutChanges: AnimateLayoutChanges = (args) =>
197 args.isSorting ? defaultAnimateLayoutChanges(args) : false;
198
199// Snoozed rows cannot accept drops without a wake time. Working rows only drag out as chat context.
200
201export type SidebarSection = "pinned" | "active" | "working" | "snoozed" | "settled";
202
203export function resolveSidebarThreadSection(input: {
204 readonly snoozed: boolean;
205 readonly settled: boolean;
206 readonly pinned: boolean;
207}): SidebarSection {
208 if (input.snoozed) return "snoozed";
209 if (input.settled) return "settled";
210 if (input.pinned) return "pinned";
211 return "active";
212}
213
214const SIDEBAR_MARKER_PREFIX = "sidebar-marker-";
215
216export type SidebarListMarker =
217 | "pinned-header"
218 | "active-placeholder"
219 | "settled-placeholder"
220 | "pinned-divider"
221 | "working-header"
222 | "snoozed-header"
223 | "settled-header";
224
225export function sidebarMarkerId(marker: SidebarListMarker): string {
226 return `${SIDEBAR_MARKER_PREFIX}${marker}`;
227}
228
229export type SidebarListItem =
230 | { readonly kind: "thread"; readonly key: string; readonly section: SidebarSection }
231 | { readonly kind: "marker"; readonly marker: SidebarListMarker };
232
233export function sidebarListItemId(item: SidebarListItem): string {
234 return item.kind === "thread" ? item.key : sidebarMarkerId(item.marker);
235}
236
237function sectionAtSidebarSlot(items: readonly SidebarListItem[], index: number): SidebarSection {
238 let section: SidebarSection = "pinned";
239 for (let i = 0; i < index && i < items.length; i += 1) {
240 const item = items[i]!;
241 if (item.kind !== "marker") continue;
242 if (item.marker === "pinned-divider") section = "active";
243 else if (item.marker === "working-header") section = "working";
244 else if (item.marker === "snoozed-header") section = "snoozed";
245 else if (item.marker === "settled-header") section = "settled";
246 }
247 return section;
248}
249
250type SidebarDropTarget = {
251 readonly section: "pinned" | "active" | "settled";
252 readonly pinnedOrder: readonly string[];
253 readonly activeOrder: readonly string[];
254};
255
256export function resolveSidebarDropTarget(
257 items: readonly SidebarListItem[],
258 activeKey: string,
259 overId: string,
260): SidebarDropTarget | null {
261 const activeIndex = items.findIndex((item) => sidebarListItemId(item) === activeKey);
262 const overIndex = items.findIndex((item) => sidebarListItemId(item) === overId);
263 if (activeIndex === -1 || overIndex === -1 || items[activeIndex]?.kind !== "thread") return null;
264 const moved = items.filter((_, index) => index !== activeIndex);
265 moved.splice(overIndex, 0, items[activeIndex]!);
266 const section = sectionAtSidebarSlot(moved, overIndex);
267 if (section === "working" || section === "snoozed") return null;
268 const pinnedOrder: string[] = [];
269 const activeOrder: string[] = [];
270 let currentSection: SidebarSection = "pinned";
271 for (const item of moved) {
272 if (item.kind === "marker") {
273 if (item.marker === "pinned-divider") currentSection = "active";
274 else if (
275 item.marker === "working-header" ||
276 item.marker === "snoozed-header" ||
277 item.marker === "settled-header"
278 )
279 break;
280 } else if (currentSection === "pinned") pinnedOrder.push(item.key);
281 else activeOrder.push(item.key);
282 }
283 return { section, pinnedOrder, activeOrder };
284}
285
286type SidebarThreadDropPlan =
287 | { readonly kind: "none" }
288 | {
289 readonly kind: "reorder-pinned";
290 readonly order: readonly string[];
291 readonly assignments: ReadonlyArray<{ readonly id: string; readonly orderKey: string }>;
292 }
293 | {
294 readonly kind: "pin";
295 readonly order: readonly string[];
296 readonly orderKey: string | undefined;
297 readonly extraAssignments: ReadonlyArray<{ readonly id: string; readonly orderKey: string }>;
298 }
299 | {
300 readonly kind: "move-active";
301 readonly order: readonly string[] | null;
302 readonly assignments: ReadonlyArray<{ readonly id: string; readonly orderKey: string }>;
303 readonly unpin: boolean;
304 readonly unsettle: boolean;
305 readonly unsnooze: boolean;
306 }
307 | { readonly kind: "settle" };
308
309export type SidebarDropVerb = "pin" | "unpin" | "settle" | "unsettle" | "wake";
310
311export function resolveSidebarDropVerb(
312 from: SidebarSection,
313 to: SidebarSection | null,
314): SidebarDropVerb | null {
315 if (to === null || to === from || to === "working" || to === "snoozed") return null;
316 if (to === "pinned") return "pin";
317 if (to === "settled") return "settle";
318 if (from === "pinned") return "unpin";
319 if (from === "settled") return "unsettle";
320 return "wake";
321}
322
323export function resolveSidebarSweepKeys(
324 orderedKeys: readonly string[],
325 originKey: string,
326 targetKey: string,
327 canApply: (key: string) => boolean,
328): string[] {
329 const origin = orderedKeys.indexOf(originKey);
330 const target = orderedKeys.indexOf(targetKey);
331 if (origin === -1 || target === -1) return [];
332 return orderedKeys.slice(Math.min(origin, target), Math.max(origin, target) + 1).filter(canApply);
333}
334
335export function sidebarThreadKeyAtY(list: HTMLElement, y: number): string | null {
336 const viewport = list.closest('[data-slot="scroll-area-viewport"]')?.getBoundingClientRect();
337 const visibleY = viewport ? Math.min(Math.max(y, viewport.top), viewport.bottom - 1) : y;
338 let key: string | null = null;
339 for (const row of list.querySelectorAll<HTMLElement>("li[data-thread-item]")) {
340 if (key !== null && row.getBoundingClientRect().top > visibleY) break;
341 key = row.dataset.threadItem ?? null;
342 }
343 return key;
344}
345
346export function resolveSidebarReorderableThreadKeys(input: {
347 readonly threads: ReadonlyArray<Pick<SidebarThreadSummary, "environmentId" | "id">>;
348 readonly serverConfigs: ReadonlyMap<EnvironmentId, Pick<EnvironmentServerConfig, "environment">>;
349 readonly connectedEnvironmentIds: readonly EnvironmentId[];
350}) {
351 const connectedEnvironmentIds = new Set(input.connectedEnvironmentIds);
352 const draggableThreadKeys = new Set<string>();
353 const activeReorderableThreadKeys = new Set<string>();
354
355 for (const thread of input.threads) {
356 // Config is cached for offline rendering, so its presence does not make a row writable.
357 if (
358 !connectedEnvironmentIds.has(thread.environmentId) ||
359 !input.serverConfigs.has(thread.environmentId)
360 ) {
361 continue;
362 }
363
364 const threadKey = scopedThreadKey(scopeThreadRef(thread.environmentId, thread.id));
365 activeReorderableThreadKeys.add(threadKey);
366 draggableThreadKeys.add(threadKey);
367 }
368
369 return { draggableThreadKeys, activeReorderableThreadKeys };
370}
371
372export function planSidebarThreadDrop(input: {
373 readonly activeKey: string;
374 readonly activeSection: SidebarSection;
375 readonly activePinned?: boolean;
376 readonly activeSettled?: boolean;
377 readonly supportsSettlement?: boolean;
378 readonly target: SidebarDropTarget;
379 readonly pinnedOrder: readonly string[];
380 readonly pinnedKeysById: ReadonlyMap<string, string | null | undefined>;
381 readonly reorderableKeys?: ReadonlySet<string>;
382 readonly activeOrder: readonly string[];
383 readonly activeKeysById: ReadonlyMap<string, string | null | undefined>;
384 readonly activeReorderableKeys?: ReadonlySet<string>;
385 readonly activeTimeOrdered?: boolean;
386}): SidebarThreadDropPlan {
387 const {
388 activeKey,
389 activeSection,
390 activePinned = activeSection === "pinned",
391 activeSettled = activeSection === "settled",
392 target,
393 pinnedOrder,
394 pinnedKeysById,
395 reorderableKeys,
396 activeOrder,
397 activeKeysById,
398 activeReorderableKeys,
399 } = input;
400 if (activeSection === "working") return { kind: "none" };
401 if (input.supportsSettlement === false && (target.section === "settled" || activeSettled)) {
402 return { kind: "none" };
403 }
404 const arrange = (
405 order: readonly string[],
406 keysById: ReadonlyMap<string, string | null | undefined>,
407 writable: ReadonlySet<string> | undefined,
408 ) => {
409 if (!writable) return planPinnedReorder({ orderedIds: order, keysById, movedId: activeKey });
410 if (!writable.has(activeKey)) return null;
411 const assignments = planPinnedReorder({
412 orderedIds: order.filter((key) => writable.has(key) || keysById.get(key) != null),
413 keysById,
414 movedId: activeKey,
415 });
416 if (assignments.some(({ id }) => !writable.has(id))) return null;
417
418 // Keyless Active rows sort before keyed rows; keyless Pinned rows sort after them.
419 // Materializing any row across a frozen keyless boundary cannot persist that position.
420 const assignedIds = new Set(assignments.map(({ id }) => id));
421 let hasFrozenKeylessBefore = false;
422 let hasAssignedBefore = false;
423 for (const id of order) {
424 const isFrozenKeyless = !writable.has(id) && keysById.get(id) == null;
425 const isAssigned = assignedIds.has(id);
426 if (
427 (target.section === "active" && isFrozenKeyless && hasAssignedBefore) ||
428 (target.section === "pinned" && isAssigned && hasFrozenKeylessBefore)
429 ) {
430 return null;
431 }
432
433 hasFrozenKeylessBefore ||= isFrozenKeyless;
434 hasAssignedBefore ||= isAssigned;
435 }
436
437 return assignments;
438 };
439 switch (target.section) {
440 case "active": {
441 if (input.activeTimeOrdered) {
442 return activeSection === "active"
443 ? { kind: "none" }
444 : {
445 kind: "move-active",
446 order: null,
447 assignments: [],
448 unpin: activePinned,
449 unsettle: activeSettled,
450 unsnooze: activeSection === "snoozed",
451 };
452 }
453 const order = target.activeOrder;
454 if (
455 activeSection === "active" &&
456 order.length === activeOrder.length &&
457 order.every((key, index) => key === activeOrder[index])
458 ) {
459 return { kind: "none" };
460 }
461 const assignments = arrange(order, activeKeysById, activeReorderableKeys);
462 if (assignments === null) return { kind: "none" };
463 return {
464 kind: "move-active",
465 order,
466 assignments,
467 unpin: activePinned,
468 unsettle: activeSettled,
469 unsnooze: activeSection === "snoozed",
470 };
471 }
472 case "settled":
473 return activeSection === "settled" ? { kind: "none" } : { kind: "settle" };
474 case "pinned": {
475 const order = target.pinnedOrder;
476 if (
477 activeSection === "pinned" &&
478 order.length === pinnedOrder.length &&
479 order.every((key, index) => key === pinnedOrder[index])
480 ) {
481 return { kind: "none" };
482 }
483 const assignments = arrange(order, pinnedKeysById, reorderableKeys);
484 if (assignments === null) return { kind: "none" };
485 if (activeSection === "pinned") {
486 return assignments.length === 0
487 ? { kind: "none" }
488 : { kind: "reorder-pinned", order, assignments };
489 }
490 return {
491 kind: "pin",
492 order,
493 orderKey: assignments.find((assignment) => assignment.id === activeKey)?.orderKey,
494 extraAssignments: activePinned
495 ? assignments
496 : assignments.filter((assignment) => assignment.id !== activeKey),
497 };
498 }
499 }
500}
501
502export function applySidebarThreadDrop<
503 T extends Pick<
504 SidebarThreadSummary,
505 | "pinnedAt"
506 | "pinOrderKey"
507 | "activeOrderKey"
508 | "snoozedAt"
509 | "snoozedUntil"
510 | "settledAt"
511 | "settledOverride"
512 | "unsettledAt"
513 >,
514>(thread: T, section: "pinned" | "active" | "settled", now: string, orderKey?: string): T {
515 const wasSettled = thread.settledOverride === "settled";
516 const awake = { ...thread, snoozedAt: null, snoozedUntil: null };
517 if (section === "settled") {
518 return {
519 ...awake,
520 pinnedAt: null,
521 pinOrderKey: null,
522 activeOrderKey: null,
523 settledOverride: "settled",
524 settledAt: wasSettled ? (thread.settledAt ?? now) : now,
525 unsettledAt: null,
526 };
527 }
528 const resumed = wasSettled
529 ? { ...awake, settledOverride: "active" as const, settledAt: null, unsettledAt: now }
530 : awake;
531 return {
532 ...resumed,
533 pinnedAt: section === "pinned" ? (thread.pinnedAt ?? now) : null,
534 pinOrderKey: section === "pinned" ? (orderKey ?? thread.pinOrderKey) : null,
535 ...(section === "active" && orderKey !== undefined ? { activeOrderKey: orderKey } : {}),
536 };
537}
538
539type SidebarProject = {
540 id: string;
541 title: string;
542 createdAt?: string | undefined;
543 updatedAt?: string | undefined;
544};
545
546type ScopedSidebarProject = SidebarProject & {
547 environmentId: string;
548};
549
550type ScopedSidebarThread = ThreadSortInput & {
551 environmentId: string;
552 projectId: string;
553 archivedAt: string | null;
554};
555
556type LogicalSidebarProject = SidebarProject & {
557 projectKey: string;
558 memberProjectRefs: readonly {
559 environmentId: string;
560 projectId: string;
561 }[];
562};
563
564type ThreadTraversalDirection = "previous" | "next";
565
566/** Exclude only successful deletions from shared-worktree checks. */
567export async function deleteSelectedThreadEntries<
568 TEntry extends { readonly threadKey: string },
569>(input: {
570 entries: readonly TEntry[];
571 delete: (
572 entry: TEntry,
573 deletedThreadKeys: ReadonlySet<string>,
574 ) => Promise<AtomCommandResult<unknown, unknown> | null>;
575}) {
576 const deletedThreadKeys = new Set<string>();
577 let firstFailure: AsyncResult.Failure<unknown, unknown> | null = null;
578
579 for (const entry of input.entries) {
580 const result = await input.delete(entry, deletedThreadKeys);
581 if (result === null) continue;
582 if (result._tag === "Failure") {
583 if (isAtomCommandInterrupted(result)) break;
584 firstFailure ??= result;
585 continue;
586 }
587 deletedThreadKeys.add(entry.threadKey);
588 }
589
590 return { deletedThreadKeys, firstFailure };
591}
592
593/**
594 * `delegatedUnderParent` holds the tasks linked environments run for a thread
595 * the sidebar lists, by thread key; they show under that thread, as subagents do.
596 */
597export function filterSidebarV2VisibleThreads<
598 T extends Pick<SidebarThreadSummary, "archivedAt" | "environmentId" | "id" | "lineage"> & {
599 projectId: string;
600 },
601>(
602 threads: readonly T[],
603 scopedProjectKeys: ReadonlySet<string> | null,
604 delegatedUnderParent: ReadonlySet<string>,
605): T[] {
606 return threads.filter(
607 (thread) =>
608 thread.archivedAt === null &&
609 !isShownUnderParent(
610 { environmentId: thread.environmentId, threadId: thread.id },
611 thread.lineage,
612 delegatedUnderParent,
613 ) &&
614 (scopedProjectKeys === null ||
615 scopedProjectKeys.has(`${thread.environmentId}:${thread.projectId}`)),
616 );
617}
618
619export function buildBulkTitleRegenerationContextMenuItem(input: {
620 supportedCount: number;
621 actionableCount: number;
622}): ContextMenuItem<"regenerate-title"> | null {
623 if (input.supportedCount === 0) return null;
624 if (input.actionableCount === 0) {
625 return {
626 id: "regenerate-title",
627 label: m(msg("Regenerating… ({count})", { count: input.supportedCount })),
628 disabled: true,
629 };
630 }
631 return {
632 id: "regenerate-title",
633 label: m(msg("Regenerate titles ({count})", { count: input.actionableCount })),
634 };
635}
636
637export function buildBulkUnpinContextMenuItem(input: {
638 pinnedCount: number;
639}): ContextMenuItem<"unpin"> | null {
640 if (input.pinnedCount === 0) return null;
641 return { id: "unpin", label: m(msg("Unpin ({count})", { count: input.pinnedCount })) };
642}
643
644export interface ThreadStatusPill {
645 /** A `msg()` string; render it through `useMessages()`. */
646 label: string;
647 colorClass: string;
648 dotClass: string;
649 pulse: boolean;
650}
651
652type ThreadStatusInput = Pick<
653 SidebarThreadSummary,
654 | "hasActionableProposedPlan"
655 | "hasPendingApprovals"
656 | "hasPendingUserInput"
657 | "pendingSubagentRequest"
658 | "pendingGuestMessageCount"
659 | "interactionMode"
660 | "latestRun"
661 | "runtime"
662> & {
663 lastVisitedAt?: string | null | undefined;
664 pendingBackgroundTasks?: SidebarThreadSummary["pendingBackgroundTasks"] | undefined;
665 blockedOnThreadWait?: boolean | undefined;
666};
667
668// Read at event time: subscribing Sidebar to terminal or modifier state re-renders every row.
669export function threadShortcutContext(routeThreadRef: ScopedThreadRef | null) {
670 return {
671 terminalFocus: isTerminalFocused(),
672 terminalOpen:
673 routeThreadRef !== null &&
674 selectThreadTerminalUiState(
675 useTerminalUiStateStore.getState().terminalUiStateByThreadKey,
676 routeThreadRef,
677 ).terminalOpen,
678 previewFocus: isPreviewFocused(),
679 previewOpen:
680 selectActiveRightPanel(useRightPanelStore.getState().byThreadKey, routeThreadRef) ===
681 "preview",
682 modelPickerOpen: isModelPickerOpen(),
683 isWeb: !isElectron,
684 isDesktop: isElectron,
685 };
686}
687
688/** Whether the current modifier combination, including none, has been held unchanged for `delayMs`. */
689function createModifierHoldStore(delayMs: number): ClockStore<boolean> {
690 const listeners = new Set<() => void>();
691 let held = false;
692 let stopDeadline = () => {};
693 let stopModifiers: (() => void) | null = null;
694
695 const setHeld = (next: boolean) => {
696 if (held === next) return;
697 held = next;
698 for (const listener of listeners) listener();
699 };
700 const onModifiersChange = () => {
701 stopDeadline();
702 const deadline = deadlineStore(deadlineAfter(delayMs));
703 stopDeadline = deadline.subscribe(() => setHeld(true));
704 // A deadline another subscriber already passed never notifies a late joiner.
705 setHeld(deadline.getSnapshot());
706 };
707
708 return {
709 subscribe: (listener) => {
710 listeners.add(listener);
711 if (stopModifiers === null) {
712 stopModifiers = shortcutModifierStore.subscribe(onModifiersChange);
713 onModifiersChange();
714 }
715 return () => {
716 listeners.delete(listener);
717 if (listeners.size > 0) return;
718 stopModifiers?.();
719 stopModifiers = null;
720 stopDeadline();
721 stopDeadline = () => {};
722 held = false;
723 };
724 },
725 getSnapshot: () => held,
726 };
727}
728
729const threadJumpModifierHold = createModifierHoldStore(THREAD_JUMP_HINT_SHOW_DELAY_MS);
730
731function subscribeToThreadJumpHintInputs(listener: () => void): () => void {
732 const unsubscribeHold = threadJumpModifierHold.subscribe(listener);
733 // The snapshot reads the modifiers; the hold stays silent when it is true across a change.
734 const unsubscribeModifiers = shortcutModifierStore.subscribe(listener);
735 const unsubscribeFocus = subscribeToTerminalFocusChanges(listener);
736 const unsubscribeTerminals = useTerminalUiStateStore.subscribe(listener);
737 const unsubscribeRightPanels = useRightPanelStore.subscribe(listener);
738 const unsubscribeModelPicker = subscribeToModelPickerVisibility(listener);
739 return () => {
740 unsubscribeHold();
741 unsubscribeModifiers();
742 unsubscribeFocus();
743 unsubscribeTerminals();
744 unsubscribeRightPanels();
745 unsubscribeModelPicker();
746 };
747}
748
749/**
750 * Thread jump hints appear once the jump modifier has been held for a moment,
751 * so a quick shortcut never flashes them, and hide as soon as it is released.
752 * The snapshot is the visibility itself, so a quick shortcut never re-renders the caller.
753 */
754export function useThreadJumpHintsVisible(
755 keybindings: ResolvedKeybindingsConfig,
756 routeThreadRef: ScopedThreadRef | null,
757): boolean {
758 return React.useSyncExternalStore(
759 subscribeToThreadJumpHintInputs,
760 () =>
761 threadJumpModifierHold.getSnapshot() &&
762 shouldShowThreadJumpHintsForModifiers(shortcutModifierStore.getSnapshot(), keybindings, {
763 platform: navigator.platform,
764 context: threadShortcutContext(routeThreadRef),
765 }),
766 );
767}
768
769export function resolveThreadLastVisitedAt(
770 serverLastVisitedAt: string | null | undefined,
771 localLastVisitedAt: string | undefined,
772): string | undefined {
773 // Server visits override local watermarks, including mark-unread rewinds; use local values only on older
774 // servers.
775 if (serverLastVisitedAt === undefined) return localLastVisitedAt;
776 return serverLastVisitedAt ?? undefined;
777}
778
779export function hasUnseenCompletion(thread: ThreadStatusInput): boolean {
780 if (!thread.latestRun?.completedAt) return false;
781 if (thread.latestRun.status === "interrupted" || thread.latestRun.status === "cancelled") {
782 return false;
783 }
784 const completedAt = Date.parse(thread.latestRun.completedAt);
785 if (Number.isNaN(completedAt)) return false;
786 if (!thread.lastVisitedAt) return false;
787
788 const lastVisitedAt = Date.parse(thread.lastVisitedAt);
789 if (Number.isNaN(lastVisitedAt)) return true;
790 return completedAt > lastVisitedAt;
791}
792
793// Suppress trailing double-click navigation; keyboard and synthetic clicks use detail 0.
794export function isTrailingDoubleClick(detail: number): boolean {
795 return detail > 1;
796}
797
798function nodeClosest(node: object | null, selector: string): unknown {
799 if (node === null || !("closest" in node) || typeof node.closest !== "function") return null;
800 return node.closest(selector);
801}
802
803export function isSidebarNestedLinkClick(target: EventTarget | null): boolean {
804 if (target == null || typeof target !== "object") return false;
805 if (nodeClosest(target, "a[href]") !== null) return true;
806 const parent =
807 "parentElement" in target &&
808 target.parentElement !== null &&
809 typeof target.parentElement === "object"
810 ? target.parentElement
811 : null;
812 return nodeClosest(parent, "a[href]") !== null;
813}
814
815/** The "New thread in" picker opens unless there is one open project or none; then the current context decides. */
816export function shouldCreateNewThreadInCurrentProject(
817 shiftKey: boolean,
818 openProjectGroupCount: number,
819 projectGroupCount: number,
820): boolean {
821 return shiftKey || openProjectGroupCount === 1 || projectGroupCount === 0;
822}
823
824/**
825 * A sidebar filtered to one project already says where the next thread belongs,
826 * so New skips the picker there. A project grouped across environments keeps the
827 * viewed thread's environment when that thread belongs to the group.
828 */
829export function resolveScopedNewThreadProjectRef<
830 TRef extends { readonly environmentId: string; readonly projectId: string },
831>(input: {
832 shiftKey: boolean;
833 scopedProjectGroups: readonly {
834 readonly environmentId: string;
835 readonly id: string;
836 readonly memberProjectRefs: readonly TRef[];
837 }[];
838 viewed: { readonly environmentId: string; readonly projectId: string } | null | undefined;
839}): TRef | null {
840 const [group, ...otherGroups] = input.scopedProjectGroups;
841 if (input.shiftKey || !group || otherGroups.length > 0) return null;
842 const memberAt = (environmentId: string, projectId: string) =>
843 group.memberProjectRefs.find(
844 (ref) => ref.environmentId === environmentId && ref.projectId === projectId,
845 );
846 return (
847 (input.viewed && memberAt(input.viewed.environmentId, input.viewed.projectId)) ??
848 memberAt(group.environmentId, group.id) ??
849 null
850 );
851}
852
853export function orderItemsByPreferredIds<TItem, TId>(input: {
854 items: readonly TItem[];
855 preferredIds: readonly TId[];
856 getId: (item: TItem) => TId;
857 getPreferenceIds?: (item: TItem) => readonly TId[];
858}): TItem[] {
859 const { getId, getPreferenceIds, items, preferredIds } = input;
860 if (preferredIds.length === 0) {
861 return [...items];
862 }
863
864 const indexesByPreferenceId = new Map<TId, number[]>();
865 for (const [index, item] of items.entries()) {
866 const preferenceIds = getPreferenceIds?.(item) ?? [getId(item)];
867 for (const preferenceId of new Set(preferenceIds)) {
868 const indexes = indexesByPreferenceId.get(preferenceId);
869 if (indexes) {
870 indexes.push(index);
871 } else {
872 indexesByPreferenceId.set(preferenceId, [index]);
873 }
874 }
875 }
876
877 const emittedIndexes = new Set<number>();
878 const ordered = preferredIds.flatMap((id) => {
879 const index = indexesByPreferenceId
880 .get(id)
881 ?.find((candidate) => !emittedIndexes.has(candidate));
882 if (index === undefined) {
883 return [];
884 }
885 emittedIndexes.add(index);
886 return [items[index]!];
887 });
888 const remaining = items.filter((_, index) => !emittedIndexes.has(index));
889 return [...ordered, ...remaining];
890}
891
892export function resolveAdjacentThreadId<T>(input: {
893 threadIds: readonly T[];
894 currentThreadId: T | null;
895 direction: ThreadTraversalDirection;
896}): T | null {
897 const { currentThreadId, direction, threadIds } = input;
898
899 if (threadIds.length === 0) {
900 return null;
901 }
902
903 if (currentThreadId === null) {
904 return direction === "previous" ? (threadIds.at(-1) ?? null) : (threadIds[0] ?? null);
905 }
906
907 const currentIndex = threadIds.indexOf(currentThreadId);
908 if (currentIndex === -1) {
909 return null;
910 }
911
912 if (direction === "previous") {
913 return currentIndex > 0 ? (threadIds[currentIndex - 1] ?? null) : null;
914 }
915
916 return currentIndex < threadIds.length - 1 ? (threadIds[currentIndex + 1] ?? null) : null;
917}
918
919export type SidebarThreadStatus =
920 | "approval"
921 | "input"
922 | "request"
923 | "preparing"
924 | "working"
925 | "waiting"
926 | "failed"
927 | "limited"
928 | "ready";
929
930export function shouldRecedeSidebarThread(input: {
931 status: SidebarThreadStatus;
932 isUnread: boolean;
933 isWoke: boolean;
934 isActive: boolean;
935 isSelected: boolean;
936}): boolean {
937 if (
938 input.isActive ||
939 input.isSelected ||
940 input.status === "input" ||
941 input.status === "request"
942 ) {
943 return false;
944 }
945 if (input.status === "preparing" || input.status === "working" || input.status === "waiting") {
946 return true;
947 }
948 if (input.status === "ready" || input.status === "approval") {
949 return !input.isUnread && !input.isWoke;
950 }
951 return false;
952}
953
954type SidebarThreadStatusInput = Pick<
955 SidebarThreadSummary,
956 | "hasPendingApprovals"
957 | "hasPendingUserInput"
958 | "pendingSubagentRequest"
959 | "pendingGuestMessageCount"
960 | "runtime"
961 | "blockedOnThreadWait"
962>;
963
964export function resolveSidebarThreadStatus(thread: SidebarThreadStatusInput): SidebarThreadStatus {
965 if (thread.hasPendingApprovals || thread.pendingSubagentRequest === "approval") {
966 return "approval";
967 }
968 if (thread.hasPendingUserInput || thread.pendingSubagentRequest === "user_input") {
969 return "input";
970 }
971 // A guest is waiting on the owner; the agent's own requests come first.
972 if ((thread.pendingGuestMessageCount ?? 0) > 0) {
973 return "request";
974 }
975 if (thread.runtime?.status === "running" && thread.blockedOnThreadWait === true) {
976 return "waiting";
977 }
978 if (thread.runtime?.status === "preparing") {
979 return "preparing";
980 }
981 if (
982 thread.runtime !== null &&
983 ["queued", "starting", "running", "waiting"].includes(thread.runtime.status)
984 ) {
985 return "working";
986 }
987 if (thread.runtime?.status === "idle") {
988 return "waiting";
989 }
990 if (thread.runtime?.status === "failed") {
991 return thread.runtime.lastErrorClass === "usage_limit" ? "limited" : "failed";
992 }
993 return "ready";
994}
995
996/** Sidebar row status: a failure the user has already opened settles to ready, like Done. */
997export function resolveSidebarRowStatus(
998 thread: ThreadStatusInput & SidebarThreadStatusInput,
999): SidebarThreadStatus {
1000 const status = resolveSidebarThreadStatus(thread);
1001 // A runtime failure without a failed run has nothing to date it, so it stays.
1002 if (status !== "failed" || thread.latestRun?.status !== "failed") return status;
1003 return hasUnseenRunFailure(thread) ? status : "ready";
1004}
1005
1006/** What the window title says the open thread is doing, in the words its announcer uses. */
1007export function resolveWindowTitleThreadStatus(
1008 thread: SidebarThreadStatusInput,
1009 resolve: MessageResolver = m,
1010): string | null {
1011 // A guest waiting doesn't hide that the agent is still working.
1012 switch (resolveSidebarThreadStatus({ ...thread, pendingGuestMessageCount: 0 })) {
1013 case "approval":
1014 return resolve(THREAD_STATUS_TEXT.approval);
1015 case "input":
1016 return resolve(THREAD_STATUS_TEXT.input);
1017 case "preparing":
1018 case "working":
1019 return resolve(THREAD_STATUS_TEXT.working);
1020 case "waiting":
1021 // Waiting on a child thread is still this turn, so it must not read as finished.
1022 return thread.runtime?.status === "running" ? resolve(THREAD_STATUS_TEXT.working) : null;
1023 default:
1024 return null;
1025 }
1026}
1027
1028/**
1029 * The dot on a closed boring-sidebar folder: the most urgent state among its
1030 * hidden threads. Waiting threads stay quiet, like their rows.
1031 */
1032export function resolveSidebarFolderDot(
1033 threads: ReadonlyArray<ThreadStatusInput & SidebarThreadStatusInput>,
1034): "attention" | "failed" | "unread" | "working" | null {
1035 const statuses = new Set(threads.map(resolveSidebarRowStatus));
1036 if (
1037 statuses.has("input") ||
1038 statuses.has("approval") ||
1039 statuses.has("request") ||
1040 statuses.has("limited")
1041 ) {
1042 return "attention";
1043 }
1044 if (statuses.has("failed")) return "failed";
1045 // Rows show Done only for ready threads, so the dot follows the same rule.
1046 const hasUnread = threads.some(
1047 (thread) => resolveSidebarRowStatus(thread) === "ready" && hasUnseenCompletion(thread),
1048 );
1049 if (hasUnread) return "unread";
1050 if (statuses.has("working") || statuses.has("preparing")) return "working";
1051 return null;
1052}
1053
1054/**
1055 * Keys the old per-project sidebar saved folder open state under, most
1056 * specific first, for `resolveProjectExpanded`. Boring folders read and write
1057 * the same keys, so a legacy user's closed folders stay closed after regrouping.
1058 */
1059export function sidebarFolderExpansionKeys(group: {
1060 readonly projectKey: string;
1061 readonly memberProjects: ReadonlyArray<{
1062 readonly physicalProjectKey: string;
1063 readonly workspaceRoot: string;
1064 }>;
1065}): string[] {
1066 return [
1067 group.projectKey,
1068 ...group.memberProjects.map((member) => member.physicalProjectKey),
1069 ...group.memberProjects.map((member) => legacyProjectCwdPreferenceKey(member.workspaceRoot)),
1070 ];
1071}
1072
1073/**
1074 * Boring sidebar folders. Folders follow `groups` order and threads keep their
1075 * input order. A project with no threads gets a folder only when `keepEmpty` says so.
1076 * A thread whose project is in no group has no folder and is left out.
1077 */
1078export function groupSidebarThreadsByProject<
1079 TGroup extends {
1080 readonly memberProjectRefs: ReadonlyArray<{
1081 readonly environmentId: EnvironmentId;
1082 readonly projectId: string;
1083 }>;
1084 },
1085 TThread extends Pick<SidebarThreadSummary, "environmentId" | "projectId">,
1086>(
1087 groups: readonly TGroup[],
1088 threads: readonly TThread[],
1089 keepEmpty: (group: TGroup) => boolean,
1090): Array<{ group: TGroup; threads: TThread[] }> {
1091 const folders = groups.map((group) => ({ group, threads: [] as TThread[] }));
1092 const folderByProject = new Map<string, (typeof folders)[number]>();
1093 for (const folder of folders) {
1094 for (const ref of folder.group.memberProjectRefs) {
1095 folderByProject.set(`${ref.environmentId}:${ref.projectId}`, folder);
1096 }
1097 }
1098 for (const thread of threads) {
1099 folderByProject.get(`${thread.environmentId}:${thread.projectId}`)?.threads.push(thread);
1100 }
1101 return folders.filter((folder) => folder.threads.length > 0 || keepEmpty(folder.group));
1102}
1103
1104export type SidebarV2TopStatusKind =
1105 | "approval"
1106 | "done"
1107 | "failed"
1108 | "limited"
1109 | "input"
1110 | "request"
1111 | "waiting"
1112 | "woke"
1113 | "working";
1114
1115export function firstValidTimestampMs(
1116 ...candidates: ReadonlyArray<string | null | undefined>
1117): number {
1118 for (const candidate of candidates) {
1119 if (candidate == null) continue;
1120 const parsed = Date.parse(candidate);
1121 if (!Number.isNaN(parsed)) return parsed;
1122 }
1123 return 0;
1124}
1125
1126export { sortActiveThreadsByOrderKey as sortThreadsForSidebar } from "@t3tools/client-runtime/state/thread-sort";
1127export {
1128 sortInboxThreadsByReturn,
1129 sortWorkingThreadsBySend,
1130} from "@t3tools/client-runtime/state/thread-inbox";
1131
1132export { pinOrderKeyBetween } from "@t3tools/client-runtime/state/thread-sort";
1133export { sortPinnedThreadsByOrderKey as sortPinnedThreadsForSidebar } from "@t3tools/client-runtime/state/thread-sort";
1134
1135const EMPTY_CONTENT_MATCH_KEYS: ReadonlySet<string> = new Set<string>();
1136
1137/**
1138 * Sidebar search results: title, branch, and pull request matches ranked as
1139 * the command palette ranks them, then threads listed only because their
1140 * messages match, in `contentMatchKeys` order.
1141 */
1142export function searchSidebarThreads<
1143 T extends ThreadSearchShell & {
1144 readonly environmentId: EnvironmentId;
1145 readonly id: ThreadId;
1146 },
1147>(
1148 threads: readonly T[],
1149 query: string,
1150 contentMatchKeys: ReadonlySet<string> = EMPTY_CONTENT_MATCH_KEYS,
1151 now = Date.now(),
1152): { readonly titleMatches: T[]; readonly contentMatches: T[] } {
1153 const normalizedQuery = foldSearchQuery(query);
1154 if (normalizedQuery.length === 0) return { titleMatches: [], contentMatches: [] };
1155 const titleMatches = rankSearchItems(threads, (thread, options) =>
1156 scoreThreadSearch(normalizedQuery, threadSearchSubject(thread, null), now, {
1157 ...options,
1158 picks: false,
1159 }),
1160 ).map(({ item }) => item);
1161 const listed = new Set(titleMatches);
1162 // In the order the server ranked their messages, as the palette lists them.
1163 const threadByKey = new Map(
1164 threads.map((thread) => [
1165 threadSearchMatchKey({ environmentId: thread.environmentId, threadId: thread.id }),
1166 thread,
1167 ]),
1168 );
1169 const contentMatches = [...contentMatchKeys].flatMap((key) => {
1170 const thread = threadByKey.get(key);
1171 return thread && !listed.has(thread) ? [thread] : [];
1172 });
1173 return { titleMatches, contentMatches };
1174}
1175
1176export function pullRequestMatchesSearchQuery(
1177 pullRequest: Parameters<typeof threadPullRequestSearchTerms>[0],
1178 query: string,
1179): boolean {
1180 const normalizedQuery = normalizeSearchText(query);
1181 if (normalizedQuery.length === 0) return false;
1182 const haystack = normalizeSearchText(threadPullRequestSearchTerms(pullRequest).join(" "));
1183 return normalizedQuery.split(" ").every((token) => haystack.includes(token));
1184}
1185
1186export function filterSidebarProjectScopeItems<TItem extends { readonly value: string }>(input: {
1187 items: readonly TItem[];
1188 query: string;
1189 matches: (item: TItem, query: string) => boolean;
1190}): readonly TItem[] {
1191 const query = input.query.trim();
1192 if (query.length === 0) return input.items;
1193 return input.items.filter((item) => item.value !== "all" && input.matches(item, query));
1194}
1195
1196interface SidebarProjectScopeMenuState {
1197 readonly open: boolean;
1198 readonly query: string;
1199}
1200
1201type SidebarProjectScopeMenuAction =
1202 | { readonly type: "query-changed"; readonly query: string }
1203 | { readonly type: "open-changed"; readonly open: boolean }
1204 | { readonly type: "project-settings-opened" };
1205
1206export function reduceSidebarProjectScopeMenuState(
1207 state: SidebarProjectScopeMenuState,
1208 action: SidebarProjectScopeMenuAction,
1209): SidebarProjectScopeMenuState {
1210 switch (action.type) {
1211 case "query-changed":
1212 return { ...state, query: action.query };
1213 case "open-changed":
1214 return { open: action.open, query: "" };
1215 case "project-settings-opened":
1216 return { open: false, query: "" };
1217 }
1218}
1219
1220export function resolveWorkingStartedAt(
1221 thread: Pick<SidebarThreadSummary, "latestRun" | "runtime">,
1222): string | null {
1223 return resolveThreadWorkingStartedAt(thread);
1224}
1225
1226export function resolveThreadStatusPill(input: {
1227 thread: ThreadStatusInput;
1228}): ThreadStatusPill | null {
1229 const { thread } = input;
1230
1231 if (thread.hasPendingApprovals || thread.pendingSubagentRequest === "approval") {
1232 return {
1233 label: msg("Pending Approval"),
1234 colorClass: "text-amber-600 dark:text-amber-300/90",
1235 dotClass: "bg-amber-500 dark:bg-amber-300/90",
1236 pulse: false,
1237 };
1238 }
1239
1240 if (thread.hasPendingUserInput || thread.pendingSubagentRequest === "user_input") {
1241 return {
1242 label: msg("Awaiting Input"),
1243 colorClass: "text-indigo-600 dark:text-indigo-300/90",
1244 dotClass: "bg-indigo-500 dark:bg-indigo-300/90",
1245 pulse: false,
1246 };
1247 }
1248
1249 if ((thread.pendingGuestMessageCount ?? 0) > 0) {
1250 return {
1251 label: msg("Guest Request"),
1252 colorClass: "text-guest-foreground",
1253 dotClass: "bg-guest",
1254 pulse: false,
1255 };
1256 }
1257
1258 if (
1259 (thread.runtime?.status === "running" && thread.blockedOnThreadWait !== true) ||
1260 thread.runtime?.status === "waiting"
1261 ) {
1262 return {
1263 label: msg("Working"),
1264 colorClass: "text-sky-600 dark:text-sky-300/80",
1265 dotClass: "bg-sky-500 dark:bg-sky-300/80",
1266 pulse: true,
1267 };
1268 }
1269
1270 if (
1271 thread.runtime?.status === "preparing" ||
1272 thread.runtime?.status === "starting" ||
1273 thread.runtime?.status === "queued"
1274 ) {
1275 return {
1276 label: msg("Connecting"),
1277 colorClass: "text-sky-600 dark:text-sky-300/80",
1278 dotClass: "bg-sky-500 dark:bg-sky-300/80",
1279 pulse: true,
1280 };
1281 }
1282
1283 const waiting = {
1284 label: msg("Waiting"),
1285 colorClass: "text-sidebar-muted-foreground",
1286 dotClass: "bg-sidebar-muted-foreground",
1287 pulse: false,
1288 };
1289 if (thread.runtime?.status === "running" && thread.blockedOnThreadWait === true) return waiting;
1290
1291 // A failed run goes to the inbox even while background work holds the thread.
1292 if (hasUnseenRunFailure(thread)) {
1293 return {
1294 label: msg("Failed"),
1295 colorClass: "text-red-600 dark:text-red-300/90",
1296 dotClass: "bg-red-500 dark:bg-red-300/90",
1297 pulse: false,
1298 };
1299 }
1300
1301 if (backgroundWorkHoldsCompletion(thread.pendingBackgroundTasks ?? [])) return waiting;
1302
1303 const hasPlanReadyPrompt =
1304 !thread.hasPendingUserInput &&
1305 thread.interactionMode === "plan" &&
1306 isLatestRunSettled(thread.latestRun, thread.runtime) &&
1307 thread.hasActionableProposedPlan;
1308 if (hasPlanReadyPrompt) {
1309 return {
1310 label: msg("Plan Ready"),
1311 colorClass: "text-violet-600 dark:text-violet-300/90",
1312 dotClass: "bg-violet-500 dark:bg-violet-300/90",
1313 pulse: false,
1314 };
1315 }
1316
1317 if (hasUnseenCompletion(thread)) {
1318 return {
1319 label: msg("Completed"),
1320 colorClass: "text-emerald-600 dark:text-emerald-300/90",
1321 dotClass: "bg-emerald-500 dark:bg-emerald-300/90",
1322 pulse: false,
1323 };
1324 }
1325
1326 return null;
1327}
1328
1329export function getFallbackThreadIdAfterDelete<
1330 T extends Pick<
1331 Thread,
1332 "id" | "projectId" | "createdAt" | "updatedAt" | "settledOverride" | "lineage"
1333 > &
1334 ThreadSortInput &
1335 ThreadSnoozeShell &
1336 Pick<Thread, "environmentId">,
1337>(input: {
1338 threads: readonly T[];
1339 deletedThreadId: T["id"];
1340 sortOrder: SidebarThreadSortOrder;
1341 now: string;
1342 deletedThreadIds?: ReadonlySet<T["id"]>;
1343 delegatedUnderParent: ReadonlySet<string>;
1344}): T["id"] | null {
1345 const { deletedThreadId, deletedThreadIds, sortOrder, now, threads, delegatedUnderParent } =
1346 input;
1347 const deletedThread = threads.find((thread) => thread.id === deletedThreadId);
1348 if (!deletedThread) {
1349 return null;
1350 }
1351
1352 return (
1353 sortThreads(
1354 threads.filter(
1355 (thread) =>
1356 thread.projectId === deletedThread.projectId &&
1357 thread.id !== deletedThreadId &&
1358 !deletedThreadIds?.has(thread.id) &&
1359 thread.settledOverride !== "settled" &&
1360 !effectiveSnoozed(thread, { now }) &&
1361 !isShownUnderParent(
1362 { environmentId: thread.environmentId, threadId: thread.id },
1363 thread.lineage,
1364 delegatedUnderParent,
1365 ),
1366 ),
1367 sortOrder,
1368 )[0]?.id ?? null
1369 );
1370}
1371function getProjectSortTimestamp(
1372 project: SidebarProject,
1373 projectThreads: readonly ThreadSortInput[],
1374 sortOrder: Exclude<SidebarProjectSortOrder, "manual">,
1375): number {
1376 if (projectThreads.length > 0) {
1377 return projectThreads.reduce(
1378 (latest, thread) => Math.max(latest, getThreadSortTimestamp(thread, sortOrder)),
1379 Number.NEGATIVE_INFINITY,
1380 );
1381 }
1382
1383 if (sortOrder === "created_at") {
1384 return toSortableTimestamp(project.createdAt) ?? Number.NEGATIVE_INFINITY;
1385 }
1386 return toSortableTimestamp(project.updatedAt ?? project.createdAt) ?? Number.NEGATIVE_INFINITY;
1387}
1388
1389function sortProjectsByActivity<TProject extends SidebarProject>(
1390 projects: readonly TProject[],
1391 sortOrder: SidebarProjectSortOrder,
1392 getProjectThreads: (project: TProject) => readonly ThreadSortInput[],
1393 compareTies: (left: TProject, right: TProject) => number,
1394): TProject[] {
1395 if (sortOrder === "manual") {
1396 return [...projects];
1397 }
1398
1399 // Project timestamps scan all threads; compute once per project instead of per comparison.
1400 return projects
1401 .map((project) => ({
1402 project,
1403 timestamp: getProjectSortTimestamp(project, getProjectThreads(project), sortOrder),
1404 }))
1405 .sort((left, right) => {
1406 const byTimestamp =
1407 right.timestamp === left.timestamp ? 0 : right.timestamp > left.timestamp ? 1 : -1;
1408 return byTimestamp || compareTies(left.project, right.project);
1409 })
1410 .map(({ project }) => project);
1411}
1412
1413export function sortLogicalProjectsForSidebar<
1414 TProject extends LogicalSidebarProject,
1415 TThread extends ScopedSidebarThread,
1416>(
1417 projects: readonly TProject[],
1418 threads: readonly TThread[],
1419 sortOrder: SidebarProjectSortOrder,
1420): TProject[] {
1421 const groupKeyByProjectRef = new Map(
1422 projects.flatMap((project) =>
1423 project.memberProjectRefs.map(
1424 (projectRef) =>
1425 [`${projectRef.environmentId}\0${projectRef.projectId}`, project.projectKey] as const,
1426 ),
1427 ),
1428 );
1429 const threadsByProjectKey = new Map<string, TThread[]>();
1430 for (const thread of threads) {
1431 if (thread.archivedAt !== null) continue;
1432 const projectKey = groupKeyByProjectRef.get(`${thread.environmentId}\0${thread.projectId}`);
1433 if (!projectKey) continue;
1434 const existing = threadsByProjectKey.get(projectKey);
1435 if (existing) {
1436 existing.push(thread);
1437 } else {
1438 threadsByProjectKey.set(projectKey, [thread]);
1439 }
1440 }
1441
1442 return sortProjectsByActivity(
1443 projects,
1444 sortOrder,
1445 (project) => threadsByProjectKey.get(project.projectKey) ?? [],
1446 (left, right) =>
1447 left.title.localeCompare(right.title) || left.projectKey.localeCompare(right.projectKey),
1448 );
1449}
1450
1451export function sortSidebarV2ProjectGroups<
1452 TProject extends LogicalSidebarProject,
1453 TThread extends ScopedSidebarThread &
1454 Pick<SidebarThreadSummary, "environmentId" | "id" | "lineage">,
1455>(
1456 projects: readonly TProject[],
1457 threads: readonly TThread[],
1458 sortOrder: SidebarProjectSortOrder,
1459 delegatedUnderParent: ReadonlySet<string>,
1460): TProject[] {
1461 return sortLogicalProjectsForSidebar(
1462 projects,
1463 filterSidebarV2VisibleThreads(threads, null, delegatedUnderParent),
1464 sortOrder,
1465 );
1466}
1467
1468export function sortScopedProjectsForSidebar<
1469 TProject extends ScopedSidebarProject,
1470 TThread extends ScopedSidebarThread,
1471>(
1472 projects: readonly TProject[],
1473 threads: readonly TThread[],
1474 sortOrder: SidebarProjectSortOrder,
1475): TProject[] {
1476 const scopedKey = (environmentId: string, projectId: string) =>
1477 `${environmentId}\u0000${projectId}`;
1478 const threadsByProject = new Map<string, TThread[]>();
1479 for (const thread of threads) {
1480 if (thread.archivedAt !== null) {
1481 continue;
1482 }
1483 const key = scopedKey(thread.environmentId, thread.projectId);
1484 const existing = threadsByProject.get(key) ?? [];
1485 existing.push(thread);
1486 threadsByProject.set(key, existing);
1487 }
1488
1489 return sortProjectsByActivity(
1490 projects,
1491 sortOrder,
1492 (project) => threadsByProject.get(scopedKey(project.environmentId, project.id)) ?? [],
1493 (left, right) =>
1494 left.title.localeCompare(right.title) ||
1495 left.environmentId.localeCompare(right.environmentId) ||
1496 left.id.localeCompare(right.id),
1497 );
1498}