@devries-cameron20 / t3code Mirror · read-only
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 04:45 UTC

main
tsx 3,728 lines 150 KB
Raw
1 import { thrownErrorMessage } from "@t3tools/client-runtime/errors";
2 import { msg, T, useGT, useMessages } from "gt-react";
3 import { m } from "../i18n/messages";
4 import { attachSidebarTree } from "../lib/sidebarTree";
5 import { type EnvironmentId, type ScopedProjectRef } from "@t3tools/contracts";
6 import type { EnvironmentServerConfig } from "@t3tools/client-runtime/connection";
7 import {
8 dropThreadContext,
9 endThreadContextDrag,
10 moveThreadContextDrag as moveThreadContextDragGhost,
11 } from "./chat/threadContextDrag";
12 import { discardComposerDraft } from "../lib/discardComposerDraft";
13 import { requestCustomSnooze } from "./CustomSnoozeDialog";
14 import { useAtomValue } from "@effect/atom-react";
15 import * as Option from "effect/Option";
16 import { Atom } from "effect/reactivity";
17 import * as Schema from "effect/Schema";
18 import {
19 DndContext,
20 useSensor,
21 useSensors,
22 type AutoScrollOptions,
23 type DragEndEvent,
24 type DragOverEvent,
25 type DragStartEvent,
26 type Modifier,
27 } from "@dnd-kit/core";
28 import { SortableContext } from "@dnd-kit/sortable";
29 import { restrictToFirstScrollableAncestor, restrictToVerticalAxis } from "@dnd-kit/modifiers";
30 import {
31 canSnooze,
32 effectiveSnoozed,
33 threadWokeAt,
34 } from "@t3tools/client-runtime/state/thread-settled";
35 import {
36 asLaunchingThread,
37 createInboxReturnTracker,
38 isThreadWorking,
39 } from "@t3tools/client-runtime/state/thread-inbox";
40 import { sortSettledThreads } from "@t3tools/client-runtime/state/thread-sort";
41 import {
42 nextShownOrder,
43 threadSearchMatchKey,
44 threadSearchSubject,
45 type ShownOrder,
46 } from "@t3tools/client-runtime/state/thread-search";
47 import { foldSearchQuery, rankMessageMatches } from "@t3tools/shared/paletteSearch";
48 import { findForMessageMatch, openThreadFindOnQuery } from "./chat/threadFindStore";
49 import {
50 threadRuntimeCanArchive,
51 type EnvironmentThreadShell,
52 } from "@t3tools/client-runtime/state/models";
53 import {
54 parseScopedThreadKey,
55 scopeProjectRef,
56 scopeThreadRef,
57 scopedThreadKey,
58 } from "@t3tools/client-runtime/environment";
59 import {
60 AuthOrchestrationOperateScope,
61 type ContextMenuSource,
62 ProjectId,
63 type ScopedThreadRef,
64 type ThreadId,
65 } from "@t3tools/contracts";
66 import {
67 resolveListedAncestorThreadRef,
68 type OlderSettledScope,
69 } from "@t3tools/client-runtime/state/threads";
70
71 import {
72 CheckIcon,
73 ChevronDownIcon,
74 FolderIcon,
75 ListFilterIcon,
76 PlusIcon,
77 SettingsIcon,
78 } from "lucide-react";
79 import {
80 useEffect,
81 useLayoutEffect,
82 useReducer,
83 useRef,
84 useState,
85 useSyncExternalStore,
86 type KeyboardEvent as ReactKeyboardEvent,
87 type MouseEvent as ReactMouseEvent,
88 type ReactNode,
89 } from "react";
90 import { type AnyRouter, useRouter } from "@tanstack/react-router";
91
92 import {
93 isAtomCommandInterrupted,
94 settlePromise,
95 squashAtomCommandFailure,
96 type AtomCommandResult,
97 } from "@t3tools/client-runtime/state/runtime";
98 import { isElectron } from "../env";
99 import {
100 resolveShortcutCommand,
101 shortcutLabelForCommand,
102 threadJumpCommandForIndex,
103 threadJumpIndexFromCommand,
104 threadTraversalDirectionFromCommand,
105 } from "../keybindings";
106 import { isModelPickerOpen } from "../modelPickerVisibility";
107 import { isMacPlatform } from "~/lib/utils";
108 import { readLocalApi } from "../localApi";
109 import { configuredHostedAppUrl } from "../hostedPairing";
110 import { useSidebarPendingFileDropStore } from "../sidebarPendingFileDropStore";
111 import { SidebarFolderDrop } from "./sidebar/SidebarFolderDrop";
112 import {
113 pickableProjectGroups,
114 selectProjectGroupingSettings,
115 } from "@t3tools/client-runtime/state/project-grouping";
116 import {
117 projectGroupsSpanEnvironments,
118 resolveSidebarProjectScopeKeys,
119 getSidebarProjectSettingsKey,
120 type SidebarProjectSnapshot,
121 } from "../sidebarProjectGrouping";
122 import { resolveProjectExpanded, useUiStateStore } from "../uiStateStore";
123 import {
124 getThreadKeysToDeselectAfterDelete,
125 useThreadSelectionStore,
126 } from "../threadSelectionStore";
127 import {
128 canTurnThreadIntoProject,
129 useAcknowledgeThreadWoke,
130 useThreadActions,
131 } from "../hooks/useThreadActions";
132 import { useHandleNewThread } from "../hooks/useHandleNewThread";
133 import { useOrderWhileOpen } from "../hooks/useOrderWhileOpen";
134 import { useProjectPin } from "../hooks/useProjectGroupUpdate";
135 import { useSidebarProjectGroups } from "../hooks/useSidebarProjectGroups";
136 import { isCommandPaletteOpen, openCommandPalette } from "../commandPaletteBus";
137 import { registerSettleAndAdvance } from "../settleAndAdvance";
138 import { startNewThreadFromContext } from "../lib/chatThreadActions";
139 import { useClientSettings } from "../hooks/useSettings";
140 import { useCopyToClipboard } from "../hooks/useCopyToClipboard";
141 import { useLocalStorage } from "../hooks/useLocalStorage";
142 import { useNowMinute } from "../hooks/useNowMinute";
143 import {
144 useEnvironmentIdentities,
145 useConnectedEnvironmentIds,
146 useEnvironmentMachines,
147 usePrimaryEnvironmentId,
148 } from "../state/environments";
149 import {
150 readThreadShell,
151 useAllEnvironmentProjectSnapshotsReady,
152 useDelegatedUnderParent,
153 useProjects,
154 useServerConfigs,
155 useQuietThreadShells,
156 } from "../state/entities";
157 import { environmentPresentations } from "../state/presentation";
158 import { primaryServerKeybindingsAtom } from "../state/server";
159 import { environmentProjects } from "../state/projects";
160 import { threadEnvironment } from "../state/threads";
161 import { useOlderSettledShelf, useOlderSettledShelfGrowth } from "../state/olderSettledShelf";
162 import { useThreadSearch } from "../state/queries";
163 import { useOrchestrationCommand } from "../state/use-orchestration-command";
164 import { readEnvironmentScope, useEnvironmentScope } from "../state/session";
165 import { appAtomRegistry } from "../rpc/atomRegistry";
166 import { canShareWithGuestAtom } from "./chat/guestShareAvailability";
167 import { openGuestShareDialog } from "./chat/guestShareDialogState";
168 import {
169 buildThreadRouteParams,
170 resolveActiveThreadRouteRef,
171 resolveThreadRouteTarget,
172 } from "../threadRoutes";
173 import type { SidebarThreadSummary } from "../types";
174 import { isScratchProject } from "@t3tools/client-runtime/state/projects";
175 import { cn } from "~/lib/utils";
176 import { ProjectEnvironmentBadge } from "./ProjectEnvironmentBadge";
177 import { ProjectRowActions } from "./ProjectComboboxRow";
178 import {
179 buildDraftActionMenuItems,
180 buildThreadActionMenuItems,
181 threadActionRequiresOperate,
182 } from "./threadActionMenu.logic";
183 import {
184 applySidebarThreadDrop,
185 filterSidebarV2VisibleThreads,
186 groupSidebarThreadsByProject,
187 sidebarFolderExpansionKeys,
188 buildBulkTitleRegenerationContextMenuItem,
189 buildBulkUnpinContextMenuItem,
190 deleteSelectedThreadEntries,
191 filterSidebarProjectScopeItems,
192 firstValidTimestampMs,
193 isSidebarNestedLinkClick,
194 isTrailingDoubleClick,
195 orderItemsByPreferredIds,
196 planSidebarThreadDrop,
197 reduceSidebarProjectScopeMenuState,
198 resolveAdjacentThreadId,
199 resolveSidebarSweepKeys,
200 resolveSidebarDropTarget,
201 resolveSidebarDropVerb,
202 resolveSidebarThreadSection,
203 resolveSidebarReorderableThreadKeys,
204 searchSidebarThreads,
205 shouldCreateNewThreadInCurrentProject,
206 shouldNavigateAfterThreadPark,
207 sidebarListItemId,
208 sidebarThreadKeyAtY,
209 sortInboxThreadsByReturn,
210 sortPinnedThreadsForSidebar,
211 sortThreadsForSidebar,
212 sortWorkingThreadsBySend,
213 useSnoozeWakeClock,
214 threadShortcutContext,
215 useThreadJumpHintsVisible,
216 type SidebarListItem,
217 type SidebarSection,
218 } from "./Sidebar.logic";
219 import {
220 createSidebarCollisionDetection,
221 createSidebarSortingStrategy,
222 restrictBelowSidebarLabel,
223 } from "./Sidebar.drag";
224 import { SidebarPointerSensor } from "./Sidebar.pointer";
225 import { createSidebarListMotion } from "./Sidebar.motion";
226 import { createSidebarShiftGuard } from "./Sidebar.shiftGuard";
227 import {
228 pickSnoozePreset,
229 resolveSnoozePresets,
230 snoozeWakeLabel,
231 type SnoozePreset,
232 } from "./Sidebar.snooze";
233 import { ProjectFavicon } from "./ProjectFavicon";
234 import { deriveProviderEntriesByEnvironment } from "../providerInstances";
235 import { useStableCallback } from "../hooks/useStableCallback";
236 import {
237 resolveSidebarRouteReveal,
238 type SidebarRouteReveal,
239 useActiveRowReveal,
240 } from "./sidebar/routeReveal";
241 import { stackedThreadToast, toastManager } from "./ui/toast";
242 import { titleRegenerationToast } from "./threadTitleRegenerationToast";
243 import { copyThreadReference } from "../lib/copyThreadReference";
244 import { threadChipCopyTarget } from "@t3tools/client-runtime/thread-reference";
245 import { Button } from "./ui/button";
246 import { isProjectPinShortcut, ProjectPinButton } from "./ProjectPinButton";
247 import {
248 Combobox,
249 ComboboxEmpty,
250 ComboboxSearchInput,
251 ComboboxItem,
252 ComboboxList,
253 ComboboxPopup,
254 ComboboxTrigger,
255 useComboboxFilter,
256 } from "./ui/combobox";
257 import { SidebarContent, SidebarGroup, useSidebar } from "./ui/sidebar";
258 import { SidebarChromeFooter, SidebarChromeHeader } from "./sidebar/SidebarChrome";
259 import { SidebarHeaderIconButton, SidebarThreadHeader } from "./sidebar/SidebarThreadHeader";
260 import { TooltipProvider } from "./ui/tooltip";
261 import {
262 composerDraftHasUserContent,
263 DraftId,
264 useComposerDraftStore,
265 usePromotingDraftThreadKeys,
266 } from "../composerDraftStore";
267 import { useShownThreadRouteTarget } from "../hooks/useShownThreadRouteTarget";
268 import {
269 SidebarSearchResultRow,
270 SortableThreadRow,
271 type SidebarProviderEntry,
272 type SidebarSweepAction,
273 } from "./sidebar/SidebarThreadRow";
274 import { SidebarDraftBlock } from "./sidebar/SidebarDraftBlock";
275 import {
276 SidebarProjectFolderHeader,
277 sidebarFolderRowId,
278 } from "./sidebar/SidebarProjectFolderHeader";
279 import {
280 SidebarDragBoundary,
281 SidebarSectionHeader,
282 SidebarSectionPlaceholder,
283 } from "./sidebar/SidebarListMarkers";
284
285 function sameSidebarProviderEntries(
286 left: ReadonlyMap<string, SidebarProviderEntry>,
287 right: ReadonlyMap<string, SidebarProviderEntry>,
288 ): boolean {
289 if (left.size !== right.size) return false;
290 for (const [instanceId, entry] of right) {
291 const other = left.get(instanceId);
292 if (
293 other === undefined ||
294 other.driverKind !== entry.driverKind ||
295 other.enabled !== entry.enabled ||
296 other.displayName !== entry.displayName ||
297 other.accentColor !== entry.accentColor ||
298 other.acpRegistryAgentId !== entry.acpRegistryAgentId ||
299 other.acpRegistryIconUrl !== entry.acpRegistryIconUrl ||
300 other.models !== entry.models
301 ) {
302 return false;
303 }
304 }
305 return true;
306 }
307
308 // Resolve providers per environment because default instance ids collide across environments.
309 const sidebarProviderEntriesAtom = Atom.make((get) => {
310 const providersByEnvironment = get(environmentPresentations.providersByEnvironmentAtom);
311 const derived = deriveProviderEntriesByEnvironment(
312 [...get(environmentPresentations.serverConfigsAtom)].map(
313 ([environmentId, config]) =>
314 [environmentId, providersByEnvironment.get(environmentId) ?? [], config.settings] as const,
315 ),
316 );
317 const previous = Option.getOrNull(
318 get.self<ReadonlyMap<string, ReadonlyMap<string, SidebarProviderEntry>>>(),
319 );
320 const next = new Map<string, ReadonlyMap<string, SidebarProviderEntry>>();
321 let changed = previous === null || previous.size !== derived.size;
322 for (const [environmentId, entries] of derived) {
323 const prior = previous?.get(environmentId);
324 if (prior !== undefined && sameSidebarProviderEntries(prior, entries)) {
325 next.set(environmentId, prior);
326 } else {
327 next.set(environmentId, entries);
328 changed = true;
329 }
330 }
331 return !changed && previous !== null ? previous : next;
332 }).pipe(Atom.withLabel("sidebar-provider-entries"));
333
334 const EMPTY_PROVIDER_ENTRIES: ReadonlyMap<string, SidebarProviderEntry> = new Map();
335 const EMPTY_THREADS: readonly EnvironmentThreadShell[] = [];
336
337 const SETTLED_TAIL_INITIAL_COUNT = 10;
338 const SETTLED_TAIL_PAGE_COUNT = 25;
339 const SETTLED_SHELF_EXPANDED_KEY = "t3code:sidebar:settled-expanded";
340 const SNOOZED_SHELF_EXPANDED_KEY = "t3code:sidebar:snoozed-expanded";
341 const WORKING_SHELF_EXPANDED_KEY = "t3code:sidebar:working-expanded";
342
343 const inboxReturns = createInboxReturnTracker();
344
345 type SidebarOptimisticDrop = {
346 readonly key: string;
347 readonly sourceSection: SidebarSection;
348 readonly section: "pinned" | "active" | "settled";
349 readonly occurredAt: string;
350 readonly clearsSnooze: boolean;
351 readonly order: readonly string[] | null;
352 readonly keysAtDrop: ReadonlyMap<string, string | null>;
353 readonly assignedKeys: ReadonlyMap<string, string>;
354 };
355
356 interface SidebarThreadPartitionInput {
357 readonly threads: readonly EnvironmentThreadShell[];
358 readonly scopedProjectKeys: ReadonlySet<string> | null;
359 /** Tasks linked environments run for a listed thread; they show under it. */
360 readonly delegatedUnderParent: ReadonlySet<string>;
361 readonly serverConfigs: ReadonlyMap<EnvironmentId, EnvironmentServerConfig>;
362 readonly connectedEnvironmentIds: readonly EnvironmentId[];
363 readonly optimisticDrop: SidebarOptimisticDrop | null;
364 readonly workingShelfEnabled: boolean;
365 /** Boring mode: folders list active threads by the user's latest message. */
366 readonly sortActiveBySend: boolean;
367 // Snooze wakes, the queued-turn grace and the Working shelf's exit grace depend
368 // on the clock, so the minute tick, the precise snooze-wake tick and the inbox
369 // tracker's expiry version are inputs: a new key repartitions.
370 readonly clockKey: string;
371 }
372
373 function scrollSidebarToTop(content: HTMLElement | null) {
374 content?.closest("[data-slot=scroll-area-viewport]")?.scrollTo({ top: 0 });
375 }
376
377 function threadShellKey(thread: Pick<SidebarThreadSummary, "environmentId" | "id">): string {
378 return scopedThreadKey(scopeThreadRef(thread.environmentId, thread.id));
379 }
380
381 const NO_DRAGGED_ORDER: readonly string[] = [];
382 const NO_DRAGGED_ORDERS: {
383 readonly settledOrder: readonly string[];
384 readonly activeOrder: readonly string[] | undefined;
385 } = { settledOrder: NO_DRAGGED_ORDER, activeOrder: undefined };
386
387 function resolveDraggedOrders(input: {
388 readonly drag: { readonly activeKey: string; readonly occurredAt: string };
389 readonly threadByKey: ReadonlyMap<string, EnvironmentThreadShell>;
390 readonly settledThreads: readonly EnvironmentThreadShell[];
391 readonly activeThreads: readonly EnvironmentThreadShell[];
392 readonly workingShelfEnabled: boolean;
393 }): typeof NO_DRAGGED_ORDERS {
394 const { drag, threadByKey, settledThreads, activeThreads, workingShelfEnabled } = input;
395 const thread = threadByKey.get(drag.activeKey);
396 if (thread === undefined) return NO_DRAGGED_ORDERS;
397 const others = (list: readonly EnvironmentThreadShell[]) =>
398 list.filter((candidate) => threadShellKey(candidate) !== drag.activeKey);
399 return {
400 settledOrder: sortSettledThreads([
401 ...others(settledThreads),
402 applySidebarThreadDrop(thread, "settled", drag.occurredAt),
403 ]).map(threadShellKey),
404 activeOrder: workingShelfEnabled
405 ? sortInboxThreadsByReturn(
406 [...others(activeThreads), applySidebarThreadDrop(thread, "active", drag.occurredAt)],
407 inboxReturns.returnedAt,
408 ).map(threadShellKey)
409 : undefined,
410 };
411 }
412
413 function routeThreadOnly(
414 threads: readonly EnvironmentThreadShell[],
415 routeThreadKey: string | null,
416 ): readonly EnvironmentThreadShell[] {
417 if (routeThreadKey === null) return EMPTY_THREADS;
418 const routeThread = threads.find((thread) => threadShellKey(thread) === routeThreadKey);
419 return routeThread === undefined ? EMPTY_THREADS : [routeThread];
420 }
421
422 // Separate hooks cache maps independently of later Sidebar hooks and preserve dnd-kit inputs.
423 function useSidebarThreads(input: {
424 readonly projectScopeKey: string | null;
425 readonly scopedProjectKeys: ReadonlySet<string> | null;
426 readonly serverConfigs: ReadonlyMap<EnvironmentId, EnvironmentServerConfig>;
427 readonly connectedEnvironmentIds: readonly EnvironmentId[];
428 readonly optimisticDrop: SidebarOptimisticDrop | null;
429 readonly threads: readonly EnvironmentThreadShell[];
430 readonly delegatedUnderParent: ReadonlySet<string>;
431 readonly routeRowThreadKey: string | null;
432 // Set in boring mode: the project groups to fold active threads into, in order.
433 readonly folderGroups: readonly SidebarProjectSnapshot[] | null;
434 // Keeps folders with no active threads, so a project the user filtered to or pinned can start one.
435 readonly keepEmptyFolders: (group: SidebarProjectSnapshot) => boolean;
436 }) {
437 const {
438 projectScopeKey,
439 scopedProjectKeys,
440 serverConfigs,
441 connectedEnvironmentIds,
442 optimisticDrop,
443 threads,
444 delegatedUnderParent,
445 routeRowThreadKey,
446 folderGroups,
447 keepEmptyFolders: keepEmpty,
448 } = input;
449 // Folders already separate the work, so boring mode has no Working shelf.
450 const workingShelfEnabled =
451 useClientSettings((s) => s.sidebarWorkingShelfEnabled) && folderGroups === null;
452 const inboxReturnsVersion = useSyncExternalStore(
453 inboxReturns.subscribe,
454 inboxReturns.getSnapshot,
455 );
456 const nowMinute = useNowMinute();
457 // Minute-quantized clocks would delay second-precise snooze wakes by up to a minute.
458 const snoozeWakeClock = useSnoozeWakeClock(threads);
459 const [settledShelfExpanded, setSettledShelfExpanded] = useLocalStorage(
460 SETTLED_SHELF_EXPANDED_KEY,
461 false,
462 Schema.Boolean,
463 );
464 const [snoozedShelfExpanded, setSnoozedShelfExpanded] = useLocalStorage(
465 SNOOZED_SHELF_EXPANDED_KEY,
466 false,
467 Schema.Boolean,
468 );
469 const [workingShelfExpanded, setWorkingShelfExpanded] = useLocalStorage(
470 WORKING_SHELF_EXPANDED_KEY,
471 false,
472 Schema.Boolean,
473 );
474 // Shared with the old per-project sidebar, so folders keep their open state.
475 const projectExpandedById = useUiStateStore((store) => store.projectExpandedById);
476 const setProjectExpanded = useUiStateStore((store) => store.setProjectExpanded);
477 const [settledTail, setSettledTail] = useState({
478 scopeKey: projectScopeKey,
479 count: SETTLED_TAIL_INITIAL_COUNT,
480 });
481 if (settledTail.scopeKey !== projectScopeKey) {
482 setSettledTail({ scopeKey: projectScopeKey, count: SETTLED_TAIL_INITIAL_COUNT });
483 }
484 const settledVisibleCount =
485 settledTail.scopeKey === projectScopeKey ? settledTail.count : SETTLED_TAIL_INITIAL_COUNT;
486
487 const partition = partitionSidebarThreads({
488 threads,
489 scopedProjectKeys,
490 delegatedUnderParent,
491 serverConfigs,
492 connectedEnvironmentIds,
493 optimisticDrop,
494 workingShelfEnabled,
495 sortActiveBySend: folderGroups !== null,
496 clockKey: `${nowMinute}:${snoozeWakeClock}:${inboxReturnsVersion}`,
497 });
498
499 const { pinnedThreads, activeThreads, workingThreads, snoozedThreads, settledThreads } =
500 partition;
501 // Older settled threads load in pages; the shelf lists them only as far as they are loaded.
502 const olderSettledShelf = useOlderSettledShelf({
503 scopes: olderSettledScopes([...serverConfigs.keys()], scopedProjectKeys),
504 expanded: settledShelfExpanded,
505 visibleCount: settledVisibleCount,
506 });
507 const listedSettledThreads = settledThreads.filter(olderSettledShelf.isListed);
508 useOlderSettledShelfGrowth(olderSettledShelf, listedSettledThreads);
509 const settledCount =
510 settledThreads.length + olderSettledShelf.unloadedCount(partition.visibleThreads);
511 const visibleSettledThreads = (() => {
512 const visible = listedSettledThreads.slice(0, settledVisibleCount);
513 if (
514 routeRowThreadKey !== null &&
515 !visible.some((thread) => threadShellKey(thread) === routeRowThreadKey)
516 ) {
517 const routeThread = settledThreads.find(
518 (thread) => threadShellKey(thread) === routeRowThreadKey,
519 );
520 if (routeThread !== undefined) visible.push(routeThread);
521 }
522 return visible.length === settledThreads.length ? settledThreads : visible;
523 })();
524 const renderedSettledThreads = settledShelfExpanded
525 ? visibleSettledThreads
526 : routeThreadOnly(visibleSettledThreads, routeRowThreadKey);
527 const visibleSnoozedThreads = snoozedShelfExpanded
528 ? snoozedThreads
529 : routeThreadOnly(snoozedThreads, routeRowThreadKey);
530 const visibleWorkingThreads = workingShelfExpanded
531 ? workingThreads
532 : routeThreadOnly(workingThreads, routeRowThreadKey);
533 const projectFolders =
534 folderGroups === null
535 ? null
536 : groupSidebarThreadsByProject(folderGroups, activeThreads, keepEmpty).map((folder) => {
537 const collapsed = !resolveProjectExpanded(
538 projectExpandedById,
539 sidebarFolderExpansionKeys(folder.group),
540 );
541 return {
542 group: folder.group,
543 collapsed,
544 // A closed folder still shows the open thread, and hints at the rest.
545 threads: collapsed
546 ? routeThreadOnly(folder.threads, routeRowThreadKey)
547 : folder.threads,
548 hiddenThreads: collapsed
549 ? folder.threads.filter((thread) => threadShellKey(thread) !== routeRowThreadKey)
550 : EMPTY_THREADS,
551 };
552 });
553 const orderedThreads = [
554 ...pinnedThreads,
555 ...(projectFolders === null
556 ? activeThreads
557 : projectFolders.flatMap((folder) => folder.threads)),
558 ...visibleWorkingThreads,
559 ...visibleSnoozedThreads,
560 ...renderedSettledThreads,
561 ];
562 const sectionByThreadKey = new Map<string, SidebarSection>();
563 for (const [list, section] of [
564 [pinnedThreads, "pinned"],
565 [activeThreads, "active"],
566 [workingThreads, "working"],
567 [snoozedThreads, "snoozed"],
568 [settledThreads, "settled"],
569 ] as const) {
570 for (const thread of list) sectionByThreadKey.set(threadShellKey(thread), section);
571 }
572 return {
573 ...partition,
574 threads,
575 workingShelfEnabled,
576 searchableThreads: [
577 ...pinnedThreads,
578 ...activeThreads,
579 ...workingThreads,
580 ...snoozedThreads,
581 ...settledThreads,
582 ],
583 settledVisibleCount,
584 settledCount,
585 olderSettledShelf,
586 hiddenSettledCount: Math.max(0, settledCount - visibleSettledThreads.length),
587 showMoreSettled: () =>
588 setSettledTail((current) => ({
589 scopeKey: current.scopeKey,
590 count: current.count + SETTLED_TAIL_PAGE_COUNT,
591 })),
592 settledShelfExpanded,
593 toggleSettledShelf: () => setSettledShelfExpanded((value) => !value),
594 snoozedShelfExpanded,
595 toggleSnoozedShelf: () => setSnoozedShelfExpanded((value) => !value),
596 workingShelfExpanded,
597 toggleWorkingShelf: () => setWorkingShelfExpanded((value) => !value),
598 projectFolders,
599 toggleProjectFolder: (group: SidebarProjectSnapshot) => {
600 const keys = sidebarFolderExpansionKeys(group);
601 setProjectExpanded(keys, !resolveProjectExpanded(projectExpandedById, keys));
602 },
603 renderedSettledThreads,
604 visibleSnoozedThreads,
605 visibleWorkingThreads,
606 orderedThreadKeys: orderedThreads.map(threadShellKey),
607 threadByKey: new Map(orderedThreads.map((thread) => [threadShellKey(thread), thread] as const)),
608 settledThreadKeys: new Set(settledThreads.map(threadShellKey)),
609 snoozedThreadKeys: new Set(snoozedThreads.map(threadShellKey)),
610 sectionByThreadKey,
611 pinnedKeys: pinnedThreads.map(threadShellKey),
612 activeKeys: activeThreads.map(threadShellKey),
613 pinnedKeysById: new Map(
614 threads.map((thread) => [threadShellKey(thread), thread.pinOrderKey ?? null] as const),
615 ),
616 activeKeysById: new Map(
617 threads.map((thread) => [threadShellKey(thread), thread.activeOrderKey ?? null] as const),
618 ),
619 };
620 }
621
622 function partitionSidebarThreads(input: SidebarThreadPartitionInput) {
623 const {
624 threads,
625 scopedProjectKeys,
626 delegatedUnderParent,
627 serverConfigs,
628 optimisticDrop,
629 workingShelfEnabled,
630 sortActiveBySend,
631 } = input;
632 const preciseNow = new Date().toISOString();
633 const visible = filterSidebarV2VisibleThreads(threads, scopedProjectKeys, delegatedUnderParent);
634 const inboxObservation = inboxReturns.observe(workingShelfEnabled ? threads : null);
635 const pinned: EnvironmentThreadShell[] = [];
636 const active: EnvironmentThreadShell[] = [];
637 const working: EnvironmentThreadShell[] = [];
638 const inbox = (thread: EnvironmentThreadShell, manuallyMoved = false) =>
639 workingShelfEnabled &&
640 (manuallyMoved ? isThreadWorking(thread) : inboxObservation.isWorking(thread))
641 ? working
642 : active;
643 const snoozed: EnvironmentThreadShell[] = [];
644 const settled: EnvironmentThreadShell[] = [];
645 const { draggableThreadKeys, activeReorderableThreadKeys } = resolveSidebarReorderableThreadKeys({
646 threads: visible,
647 serverConfigs,
648 connectedEnvironmentIds: input.connectedEnvironmentIds,
649 });
650 for (const thread of visible) {
651 const configLoaded = serverConfigs.has(thread.environmentId);
652 const threadKey = scopedThreadKey(scopeThreadRef(thread.environmentId, thread.id));
653 if (optimisticDrop?.key === threadKey) {
654 const projected = applySidebarThreadDrop(
655 thread,
656 optimisticDrop.section,
657 optimisticDrop.occurredAt,
658 optimisticDrop.assignedKeys.get(threadKey),
659 );
660 (optimisticDrop.section === "pinned"
661 ? pinned
662 : optimisticDrop.section === "settled"
663 ? settled
664 : inbox(projected, true)
665 ).push(
666 optimisticDrop.clearsSnooze
667 ? projected
668 : { ...projected, snoozedAt: thread.snoozedAt, snoozedUntil: thread.snoozedUntil },
669 );
670 } else {
671 const section = resolveSidebarThreadSection({
672 snoozed: configLoaded && effectiveSnoozed(thread, { now: preciseNow }),
673 settled: configLoaded && thread.settledOverride === "settled",
674 pinned: thread.pinnedAt != null,
675 });
676 (section === "snoozed"
677 ? snoozed
678 : section === "settled"
679 ? settled
680 : section === "pinned"
681 ? pinned
682 : inbox(thread)
683 ).push(thread);
684 }
685 }
686 // Availability gates dragging only; sorting must stay consistent across clients.
687 const sortedPinned = sortPinnedThreadsForSidebar(pinned);
688 const sortedActive = sortActiveBySend
689 ? sortWorkingThreadsBySend(active)
690 : workingShelfEnabled
691 ? sortInboxThreadsByReturn(active, inboxObservation.returnedAt)
692 : sortThreadsForSidebar(active);
693 return {
694 pinnedThreads:
695 optimisticDrop?.section !== "pinned" || optimisticDrop.order === null
696 ? sortedPinned
697 : orderItemsByPreferredIds({
698 items: sortedPinned,
699 preferredIds: optimisticDrop.order,
700 getId: (thread) => scopedThreadKey(scopeThreadRef(thread.environmentId, thread.id)),
701 }),
702 draggableThreadKeys,
703 activeReorderableThreadKeys,
704 activeThreads:
705 optimisticDrop?.section !== "active" || optimisticDrop.order === null
706 ? sortedActive
707 : orderItemsByPreferredIds({
708 items: sortedActive,
709 preferredIds: optimisticDrop.order,
710 getId: (thread) => scopedThreadKey(scopeThreadRef(thread.environmentId, thread.id)),
711 }),
712 workingThreads: sortWorkingThreadsBySend(working),
713 snoozedThreads: snoozed.toSorted(
714 (left, right) =>
715 firstValidTimestampMs(left.snoozedUntil ?? null) -
716 firstValidTimestampMs(right.snoozedUntil ?? null),
717 ),
718 settledThreads: sortSettledThreads(settled),
719 visibleThreads: visible,
720 snoozeNow: preciseNow,
721 };
722 }
723
724 /** The sidebar's scope per environment: the scoped projects there, or every project. */
725 function olderSettledScopes(
726 environmentIds: ReadonlyArray<EnvironmentId>,
727 scopedProjectKeys: ReadonlySet<string> | null,
728 ): ReadonlyArray<OlderSettledScope> {
729 if (scopedProjectKeys === null) {
730 return environmentIds.map((environmentId) => ({ environmentId, projectIds: null }));
731 }
732 return environmentIds.flatMap((environmentId) => {
733 const prefix = `${environmentId}:`;
734 const projectIds = [...scopedProjectKeys].flatMap((key) =>
735 key.startsWith(prefix) ? [ProjectId.make(key.slice(prefix.length))] : [],
736 );
737 return projectIds.length === 0 ? [] : [{ environmentId, projectIds }];
738 });
739 }
740
741 function isOptimisticDropReleased(input: {
742 readonly optimisticDrop: SidebarOptimisticDrop;
743 readonly threads: readonly EnvironmentThreadShell[];
744 readonly pinnedKeys: readonly string[];
745 readonly activeKeys: readonly string[];
746 readonly now: string;
747 }): boolean {
748 const { optimisticDrop, threads, pinnedKeys, activeKeys, now } = input;
749 const canonicalByKey = new Map(
750 threads.map((thread) => [
751 scopedThreadKey(scopeThreadRef(thread.environmentId, thread.id)),
752 thread,
753 ]),
754 );
755 const thread = canonicalByKey.get(optimisticDrop.key);
756 if (thread === undefined || thread.archivedAt !== null) {
757 return true;
758 }
759 const canonicalSection = effectiveSnoozed(thread, { now })
760 ? "snoozed"
761 : thread.settledOverride === "settled"
762 ? "settled"
763 : thread.pinnedAt != null
764 ? "pinned"
765 : "active";
766 if (
767 canonicalSection !== optimisticDrop.sourceSection &&
768 canonicalSection !== optimisticDrop.section
769 ) {
770 return true;
771 }
772 if (optimisticDrop.order === null) {
773 // Settle emits unpin/unsnooze too; hold projected fields and sort times until the whole move completes.
774 if (
775 canonicalSection === optimisticDrop.section &&
776 thread.pinnedAt == null &&
777 (!optimisticDrop.clearsSnooze || thread.snoozedUntil == null)
778 ) {
779 return true;
780 }
781 return false;
782 }
783 if (canonicalSection !== optimisticDrop.section) return false;
784 if (optimisticDrop.clearsSnooze && thread.snoozedUntil != null) return false;
785 const destinationKeys = optimisticDrop.section === "pinned" ? pinnedKeys : activeKeys;
786 const canonicalDestination = destinationKeys.flatMap((key) => {
787 const canonical = canonicalByKey.get(key);
788 return canonical === undefined ? [] : [canonical];
789 });
790 const keyByThread = new Map(
791 canonicalDestination.map((thread) => [
792 scopedThreadKey(scopeThreadRef(thread.environmentId, thread.id)),
793 (optimisticDrop.section === "pinned" ? thread.pinOrderKey : thread.activeOrderKey) ?? null,
794 ]),
795 );
796 const heldOrder = optimisticDrop.order;
797 const heldKeys = new Set(heldOrder);
798 const membershipChanged =
799 destinationKeys.length !== heldOrder.length ||
800 destinationKeys.some((key) => !heldKeys.has(key));
801 const foreignKeyLanded = destinationKeys.some((threadKey) => {
802 const currentKey = keyByThread.get(threadKey) ?? null;
803 if (currentKey === (optimisticDrop.keysAtDrop.get(threadKey) ?? null)) return false;
804 return currentKey !== optimisticDrop.assignedKeys.get(threadKey);
805 });
806 const allAssignmentsLanded = [...optimisticDrop.assignedKeys].every(
807 ([threadKey, orderKey]) => keyByThread.get(threadKey) === orderKey,
808 );
809 return membershipChanged || foreignKeyLanded || allAssignmentsLanded;
810 }
811
812 // Build maps in a hook so the compiler can prove they are frozen and cache them.
813 function useSidebarLookups() {
814 const gt = useGT();
815 const projects = useProjects();
816 const environments = useEnvironmentIdentities();
817 const serverConfigs = useServerConfigs();
818 const providerEntriesByEnvironment = useAtomValue(sidebarProviderEntriesAtom);
819 const projectGroups = useSidebarProjectGroups();
820 const environmentLabelById = new Map(
821 environments.map((environment) => [environment.environmentId, environment.label] as const),
822 );
823 const projectByKey = new Map(
824 projects.map((project) => [`${project.environmentId}:${project.id}`, project] as const),
825 );
826 const projectDisplayNameByKey = new Map(
827 projectGroups.flatMap((group) =>
828 group.memberProjects.map(
829 (project) => [`${project.environmentId}:${project.id}`, group.displayName] as const,
830 ),
831 ),
832 );
833 const projectGroupByScopeKey = new Map(
834 projectGroups.map((project) => [project.projectKey, project] as const),
835 );
836 const projectScopeItems = [
837 { value: "all", label: gt("All projects") },
838 ...pickableProjectGroups(projectGroups).map((project) => ({
839 value: project.projectKey,
840 label: project.displayName,
841 })),
842 ];
843 return {
844 projects,
845 serverConfigs,
846 projectGroups,
847 environmentLabelById,
848 providerEntriesByEnvironment,
849 projectByKey,
850 projectDisplayNameByKey,
851 projectGroupByScopeKey,
852 projectScopeItems,
853 };
854 }
855
856 function ProjectScopeRowIcon(props: { isSelected: boolean; children: ReactNode }) {
857 return (
858 <span className="relative flex shrink-0">
859 {props.children}
860 {props.isSelected ? (
861 <span className="pointer-events-none absolute -right-1 -bottom-1 grid size-3 place-items-center rounded-full bg-primary ring-2 ring-popover">
862 <CheckIcon className="size-2 text-primary-foreground" strokeWidth={4} aria-hidden />
863 </span>
864 ) : null}
865 </span>
866 );
867 }
868
869 function canOperateThreads(
870 threads: ReadonlyArray<Pick<SidebarThreadSummary, "environmentId">>,
871 ): boolean {
872 return threads.every((thread) =>
873 readEnvironmentScope(thread.environmentId, AuthOrchestrationOperateScope),
874 );
875 }
876
877 function checkThreadOperations(
878 threads: ReadonlyArray<Pick<SidebarThreadSummary, "environmentId">>,
879 ): boolean {
880 if (canOperateThreads(threads)) return true;
881 toastManager.add({
882 type: "error",
883 title: m(msg("Thread action unavailable")),
884 description: m(msg("This connection cannot change one or more selected threads.")),
885 });
886 return false;
887 }
888
889 const SIDEBAR_DRAG_DISTANCE = 6;
890
891 // dnd-kit's 20% edge zone at full speed runs the list away while the pointer rests near the bottom.
892 const SIDEBAR_AUTO_SCROLL: AutoScrollOptions = { threshold: { x: 0, y: 0.05 }, acceleration: 3 };
893
894 const SIDEBAR_DRAG_LABEL_HEIGHT = 24;
895
896 const threadSearchResultId = (index: number) => `sidebar-thread-search-result-${index}`;
897
898 // Continuations that outlive a render read the open thread from the router.
899 function readRouteThreadKey(router: AnyRouter): string | null {
900 const target = resolveThreadRouteTarget(router.state.matches.at(-1)?.params ?? {});
901 const draft =
902 target?.kind === "draft"
903 ? useComposerDraftStore.getState().getDraftSession(target.draftId)
904 : null;
905 const ref = resolveActiveThreadRouteRef(target, draft);
906 return ref === null ? null : scopedThreadKey(ref);
907 }
908
909 export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReveal }) {
910 const gt = useGT();
911 const messages = useMessages();
912 const {
913 projects,
914 serverConfigs,
915 projectGroups,
916 environmentLabelById,
917 providerEntriesByEnvironment,
918 projectByKey,
919 projectDisplayNameByKey,
920 projectGroupByScopeKey,
921 projectScopeItems: lookupProjectScopeItems,
922 } = useSidebarLookups();
923 const delegatedUnderParent = useDelegatedUnderParent();
924 const router = useRouter();
925 const { isMobile, setOpenMobile } = useSidebar();
926 const keybindings = useAtomValue(primaryServerKeybindingsAtom);
927 const confirmThreadDelete = useClientSettings((s) => s.confirmThreadDelete);
928 const confirmThreadArchive = useClientSettings((s) => s.confirmThreadArchive);
929 const timestampFormat = useClientSettings((s) => s.timestampFormat);
930 const projectGroupingSettings = useClientSettings(selectProjectGroupingSettings);
931 const {
932 settleThread,
933 unsettleThread,
934 snoozeThread,
935 unsnoozeThread,
936 pinThread,
937 unpinThread,
938 confirmAndUnpinThread,
939 setThreadAutoSettle,
940 turnThreadIntoProject,
941 reorderPinnedThread,
942 reorderActiveThread,
943 markThreadUnread,
944 archiveThread,
945 deleteThread,
946 } = useThreadActions();
947 const updateThreadMetadata = useOrchestrationCommand(threadEnvironment.updateMetadata, {
948 reportFailure: false,
949 });
950 const regenerateThreadTitle = useOrchestrationCommand(threadEnvironment.regenerateTitle, {
951 reportFailure: false,
952 });
953 const { copyToClipboard: copyPathToClipboard } = useCopyToClipboard<{ path: string }>({
954 onError: (error) => {
955 toastManager.add(
956 stackedThreadToast({
957 type: "error",
958 title: gt("Failed to copy path"),
959 description: thrownErrorMessage(error, m) ?? gt("An error occurred."),
960 }),
961 );
962 },
963 });
964 const { copyToClipboard: copyBranchToClipboard } = useCopyToClipboard<{ branch: string }>({
965 target: {
966 target: "branch name",
967 unavailableMessage: msg("Clipboard API is unavailable while copying branch name."),
968 failureMessage: msg("Failed to copy branch name to the clipboard."),
969 },
970 onError: (error) => {
971 toastManager.add(
972 stackedThreadToast({
973 type: "error",
974 title: gt("Failed to copy branch"),
975 description: thrownErrorMessage(error, m) ?? gt("An error occurred."),
976 }),
977 );
978 },
979 });
980 const { copyToClipboard: copyThreadIdToClipboard } = useCopyToClipboard<{ threadId: ThreadId }>({
981 onError: (error) => {
982 toastManager.add(
983 stackedThreadToast({
984 type: "error",
985 title: gt("Failed to copy thread ID"),
986 description: thrownErrorMessage(error, m) ?? gt("An error occurred."),
987 }),
988 );
989 },
990 });
991 const boringSidebarEnabled = useClientSettings((settings) => settings.boringSidebarEnabled);
992 const folderRowsMultiline = useClientSettings((settings) => settings.boringSidebarMultilineRows);
993 const newThreadContext = useHandleNewThread();
994 // Row callbacks capture only the handler; the rest of the context changes with the route.
995 const { handleNewThread } = newThreadContext;
996 const primaryEnvironmentId = usePrimaryEnvironmentId();
997 const clearSelection = useThreadSelectionStore((s) => s.clearSelection);
998 const setSelectionAnchor = useThreadSelectionStore((s) => s.setAnchor);
999 const toggleThreadSelection = useThreadSelectionStore((s) => s.toggleThread);
1000 const rangeSelectTo = useThreadSelectionStore((s) => s.rangeSelectTo);
1001 const acknowledgeWoke = useAcknowledgeThreadWoke();
1002 // A Settings or Usage modal keeps the thread behind it current.
1003 const routeTarget = useShownThreadRouteTarget().shownTarget;
1004 const routeDraftThread = useComposerDraftStore((store) =>
1005 routeTarget?.kind === "draft" ? store.getDraftSession(routeTarget.draftId) : null,
1006 );
1007 const routeDraftRedirect = useComposerDraftStore((store) =>
1008 routeTarget?.kind === "draft" ? store.getPromotedDraftRedirect(routeTarget.draftId) : null,
1009 );
1010 const environmentMachineById = useEnvironmentMachines();
1011 const projectGroupsRef = useRef(projectGroups);
1012 const persistedProjectScopeKeys = useUiStateStore((store) => store.sidebarProjectScopeKeys);
1013 const setPersistedProjectScopeKeys = useUiStateStore((store) => store.setSidebarProjectScopeKeys);
1014 const [projectScopeMenuState, dispatchProjectScopeMenu] = useReducer(
1015 reduceSidebarProjectScopeMenuState,
1016 { open: false, query: "" },
1017 );
1018 const projectScopeFilter = useComboboxFilter();
1019 const allProjectSnapshotsReady = useAllEnvironmentProjectSnapshotsReady();
1020 const allProjectConfigsReady = useAtomValue(environmentProjects.projectConfigsReadyAtom);
1021 // Safari may click after Ctrl+click opens settings; suppress that selection until the picker reopens.
1022 const suppressNextScopeChangeRef = useRef(false);
1023 const highlightedProjectScopeKeyRef = useRef<string | null>(null);
1024 // Hold dropped rows until server placement is confirmed; block another pickup from replacing the hold.
1025 const [optimisticDrop, setOptimisticDrop] = useState<SidebarOptimisticDrop | null>(null);
1026 const threadSearchInputRef = useRef<HTMLInputElement>(null);
1027 const [threadSearchQuery, setThreadSearchQuery] = useState("");
1028 const [searchHighlightKey, setSearchHighlightKey] = useState<string | null>(null);
1029 const connectedEnvironmentIds = useConnectedEnvironmentIds();
1030 const queuePendingFileDrop = useSidebarPendingFileDropStore((s) => s.queuePendingFileDrop);
1031 const clearPendingFileDrop = useSidebarPendingFileDropStore((s) => s.clearPendingFileDrop);
1032 const [renamingThreadRef, setRenamingThreadRef] = useState<ScopedThreadRef | null>(null);
1033 const canOperateRenamingThread = useEnvironmentScope(
1034 renamingThreadRef?.environmentId ?? null,
1035 AuthOrchestrationOperateScope,
1036 );
1037 // Losing operate access cancels the rename without committing the title, so
1038 // the editor does not return and take focus when access comes back.
1039 if (renamingThreadRef !== null && !canOperateRenamingThread) setRenamingThreadRef(null);
1040 const renamingThreadKey =
1041 renamingThreadRef !== null && canOperateRenamingThread
1042 ? scopedThreadKey(renamingThreadRef)
1043 : null;
1044 const [renamingTitle, setRenamingTitle] = useState("");
1045 const renamingOriginalTitleRef = useRef("");
1046 const settlingThreadKeysRef = useRef(new Set<string>());
1047 const threadListRef = useRef<HTMLUListElement | null>(null);
1048 const searchResultsListRef = useRef<HTMLUListElement | null>(null);
1049 const sidebarContentRef = useRef<HTMLDivElement | null>(null);
1050 const dragLabelOffsetRef = useRef(0);
1051 const listMotionRef = useRef<ReturnType<typeof createSidebarListMotion> | null>(null);
1052 const shiftGuardRef = useRef<ReturnType<typeof createSidebarShiftGuard> | null>(null);
1053 const [dragState, setDragState] = useState<{
1054 readonly activeKey: string;
1055 readonly activeSection: SidebarSection;
1056 readonly occurredAt: string;
1057 readonly activationY: number | null;
1058 readonly targetSection: SidebarSection | null;
1059 readonly contextDrag: boolean;
1060 } | null>(null);
1061 const dragSensorRef = useRef<SidebarPointerSensor | null>(null);
1062 const contextDragKeyRef = useRef<string | null>(null);
1063 const dragScrollRef = useRef<{ readonly viewport: Element; readonly top: number } | null>(null);
1064 const [actionSweep, setActionSweep] = useState<{
1065 action: SidebarSweepAction;
1066 keys: ReadonlySet<string>;
1067 } | null>(null);
1068 const snoozingThreadKeysRef = useRef(new Set<string>());
1069 const removeFromSelection = useThreadSelectionStore((s) => s.removeFromSelection);
1070 const openAddProjectCommandPalette = () => openCommandPalette({ open: "add-project" });
1071 const routeThreadRef = resolveActiveThreadRouteRef(
1072 routeTarget,
1073 routeDraftThread,
1074 routeDraftRedirect,
1075 );
1076 const routeThreadKey = routeThreadRef ? scopedThreadKey(routeThreadRef) : null;
1077
1078 // A selection made under one scope can hold threads the next scope hides.
1079 // The viewport outlives the scope and does not anchor, so a new list starts at the top.
1080 const setProjectScopeKeys = (keys: readonly string[]) => {
1081 clearSelection();
1082 setPersistedProjectScopeKeys(keys);
1083 scrollSidebarToTop(sidebarContentRef.current);
1084 };
1085 // A scope whose project is gone reads as all projects once every snapshot has
1086 // loaded. The stored keys are left alone, so the scope returns with its project.
1087 // An archived project's scope reads as all projects, matching the menu.
1088 const scopeGroups = pickableProjectGroups(projectGroups);
1089 const archivedProjectKeys = new Set(
1090 projectGroups.filter((project) => project.archived).map((project) => project.projectKey),
1091 );
1092 const chosenProjectScopeKeys = resolveSidebarProjectScopeKeys({
1093 groups: projectGroups,
1094 keys: persistedProjectScopeKeys,
1095 settings: projectGroupingSettings,
1096 canClearMissingScope: allProjectSnapshotsReady && allProjectConfigsReady,
1097 }).filter((key) => !archivedProjectKeys.has(key));
1098 const chosenProjectGroups = scopeGroups.filter((project) =>
1099 chosenProjectScopeKeys.includes(project.projectKey),
1100 );
1101 const chosenScopeProjectKeys =
1102 chosenProjectGroups.length === 0
1103 ? null
1104 : new Set(
1105 chosenProjectGroups.flatMap((project) =>
1106 project.memberProjectRefs.map(
1107 (projectRef) => `${projectRef.environmentId}:${projectRef.projectId}`,
1108 ),
1109 ),
1110 );
1111 const threads = useQuietThreadShells();
1112 const promotingDraftThreadKeys = usePromotingDraftThreadKeys();
1113 const listedThreads =
1114 promotingDraftThreadKeys.length === 0
1115 ? threads
1116 : threads.map((thread) =>
1117 promotingDraftThreadKeys.includes(threadShellKey(thread))
1118 ? asLaunchingThread(thread)
1119 : thread,
1120 );
1121 const routeRowThreadKey =
1122 routeThreadRef === null
1123 ? null
1124 : scopedThreadKey(resolveListedAncestorThreadRef(routeThreadRef, threads));
1125 const isSearchingThreads = threadSearchQuery.trim().length > 0;
1126 // The open draft's first send names its thread in place; a finalized draft reached by
1127 // navigation resolves through its redirect instead, and still reveals.
1128 const routeKeyInPlace = routeDraftThread?.promotedTo != null;
1129
1130 // History, the palette and links can open a thread the scope hides or the list
1131 // scrolled away; a remount starts at the top, so each mount scrolls to the open
1132 // thread once. Render decides the widening, so the first frame of the new route
1133 // already lists the row; the active row's ref callback scrolls to it.
1134 const { widensScope: revealWidensScope } = resolveSidebarRouteReveal({
1135 reveal: routeReveal,
1136 routeKey: routeRowThreadKey,
1137 routeKeyInPlace,
1138 isSearching: isSearchingThreads,
1139 scopedProjectKeys: chosenScopeProjectKeys,
1140 delegatedUnderParent,
1141 findThread: (key) => threads.find((candidate) => threadShellKey(candidate) === key),
1142 });
1143 const projectScopeKeys = revealWidensScope ? [] : chosenProjectScopeKeys;
1144 const projectScopeKey = projectScopeKeys.length === 0 ? null : projectScopeKeys.join("\n");
1145 const toggleProjectScopeKey = (key: string) =>
1146 setProjectScopeKeys(
1147 projectScopeKeys.includes(key)
1148 ? projectScopeKeys.filter((candidate) => candidate !== key)
1149 : [...projectScopeKeys, key],
1150 );
1151 // The widened scope outlives the reveal, so it is written back to the persisted
1152 // scope. Route changes arrive from history, links and the palette, and only this
1153 // component holds the project groups that decide a widening, so no single
1154 // navigation handler can make the write.
1155 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- writes a route reveal's widened project scope back to the persisted sidebar scope and clears selection
1156 useEffect(() => {
1157 if (!revealWidensScope) return;
1158 clearSelection();
1159 setPersistedProjectScopeKeys([]);
1160 }, [clearSelection, revealWidensScope, setPersistedProjectScopeKeys]);
1161 const revealActiveRow = useActiveRowReveal(routeReveal, routeRowThreadKey, routeKeyInPlace);
1162 const showProjectEnvironments = projectGroupsSpanEnvironments(projectGroups);
1163 const scratchMachineLabelFor = (
1164 thread: Pick<SidebarThreadSummary, "environmentId" | "projectId">,
1165 ) => {
1166 if (!showProjectEnvironments) return null;
1167 const project = projectByKey.get(`${thread.environmentId}:${thread.projectId}`);
1168 if (
1169 !project ||
1170 !isScratchProject(project, serverConfigs.get(thread.environmentId)?.scratchWorkspaceRoot)
1171 ) {
1172 return null;
1173 }
1174 return environmentLabelById.get(thread.environmentId) ?? null;
1175 };
1176 // Pinning from a row keeps rows in place while the menu is open.
1177 const projectScopeItems = useOrderWhileOpen(
1178 lookupProjectScopeItems,
1179 (item) => item.value,
1180 projectScopeMenuState.open,
1181 );
1182 const selectedProjectScopeItem =
1183 projectScopeKeys.length > 1
1184 ? null
1185 : (projectScopeItems.find((item) => item.value === (projectScopeKeys[0] ?? "all")) ??
1186 projectScopeItems[0]!);
1187 const filteredProjectScopeItems = filterSidebarProjectScopeItems({
1188 items: projectScopeItems,
1189 query: projectScopeMenuState.query,
1190 matches: (item, query) =>
1191 projectScopeFilter.contains(item, query, (candidate) => candidate.label),
1192 });
1193 const scopedProjectGroups = revealWidensScope ? [] : chosenProjectGroups;
1194 const scopedProjectRefs = scopedProjectGroups.flatMap((project) => project.memberProjectRefs);
1195 const scopedProjectKeys = revealWidensScope ? null : chosenScopeProjectKeys;
1196 const threadSearch = useThreadSearch(
1197 connectedEnvironmentIds,
1198 threadSearchQuery,
1199 scopedProjectGroups.length === 0
1200 ? {}
1201 : { projectIds: scopedProjectRefs.map((projectRef) => projectRef.projectId) },
1202 );
1203 const routeDraftIdForRows = routeTarget?.kind === "draft" ? routeTarget.draftId : null;
1204 const visibleDraftSessionCount = useComposerDraftStore((store) => {
1205 let count = 0;
1206 for (const [draftKey, session] of Object.entries(store.draftThreadsByThreadKey)) {
1207 if (session.promotedTo != null) {
1208 continue;
1209 }
1210 if (!composerDraftHasUserContent(store.draftsByThreadKey[draftKey])) {
1211 continue;
1212 }
1213 if (
1214 scopedProjectKeys !== null &&
1215 !scopedProjectKeys.has(`${session.environmentId}:${session.projectId}`)
1216 ) {
1217 continue;
1218 }
1219 count += 1;
1220 }
1221 return count;
1222 });
1223
1224 const openProjectSettings = useStableCallback(
1225 (projectGroup: SidebarProjectSnapshot, projectRef?: ScopedProjectRef) => {
1226 if (isMobile) {
1227 setOpenMobile(false);
1228 }
1229 void router.navigate({
1230 to: "/projects/$projectKey",
1231 params: {
1232 projectKey: getSidebarProjectSettingsKey(
1233 projectGroup,
1234 projectGroupingSettings,
1235 projects,
1236 projectRef,
1237 ),
1238 },
1239 });
1240 },
1241 );
1242 const {
1243 canPinProjectGroup: canPinProject,
1244 setProjectGroupPinned,
1245 toggleProjectGroupPin,
1246 } = useProjectPin();
1247 const handleProjectSettings = useStableCallback(
1248 (
1249 event: ReactMouseEvent<HTMLElement> | ReactKeyboardEvent<HTMLInputElement>,
1250 projectGroup: SidebarProjectSnapshot,
1251 ) => {
1252 event.preventDefault();
1253 event.stopPropagation();
1254 suppressNextScopeChangeRef.current = true;
1255 dispatchProjectScopeMenu({ type: "project-settings-opened" });
1256 openProjectSettings(projectGroup);
1257 },
1258 );
1259 const startThreadInProjectFolder = useStableCallback((group: SidebarProjectSnapshot) => {
1260 if (isMobile) setOpenMobile(false);
1261 void handleNewThread(scopeProjectRef(group.environmentId, group.id));
1262 });
1263 const handleProjectFolderContextMenu = useStableCallback(
1264 (
1265 group: SidebarProjectSnapshot,
1266 position: { x: number; y: number },
1267 source: ContextMenuSource,
1268 ) => {
1269 const api = readLocalApi();
1270 if (!api) return;
1271 void (async () => {
1272 const clicked = await settlePromise(() =>
1273 api.contextMenu.show(
1274 [
1275 { id: "new-thread", label: gt("New thread") },
1276 { id: "copy-path", label: gt("Copy path") },
1277 ...(canPinProject(group)
1278 ? [
1279 group.pinned
1280 ? { id: "unpin", label: gt("Unpin project"), icon: "pin-off" }
1281 : { id: "pin", label: gt("Pin project"), icon: "pin" },
1282 ]
1283 : []),
1284 { id: "project-settings", label: gt("Project settings"), icon: "settings" },
1285 ],
1286 position,
1287 source,
1288 ),
1289 );
1290 if (clicked._tag === "Failure") return;
1291 switch (clicked.value) {
1292 case "new-thread":
1293 startThreadInProjectFolder(group);
1294 return;
1295 case "copy-path":
1296 copyPathToClipboard(group.workspaceRoot, { path: group.workspaceRoot });
1297 return;
1298 case "pin":
1299 case "unpin":
1300 setProjectGroupPinned(group, clicked.value === "pin");
1301 return;
1302 case "project-settings":
1303 openProjectSettings(group);
1304 return;
1305 }
1306 })();
1307 },
1308 );
1309
1310 const {
1311 workingShelfEnabled,
1312 pinnedThreads,
1313 draggableThreadKeys,
1314 activeReorderableThreadKeys,
1315 activeThreads,
1316 workingThreads,
1317 snoozedThreads,
1318 settledThreads,
1319 snoozeNow,
1320 searchableThreads,
1321 settledVisibleCount,
1322 settledCount,
1323 olderSettledShelf,
1324 hiddenSettledCount,
1325 showMoreSettled,
1326 settledShelfExpanded,
1327 toggleSettledShelf,
1328 snoozedShelfExpanded,
1329 toggleSnoozedShelf,
1330 workingShelfExpanded,
1331 toggleWorkingShelf,
1332 projectFolders,
1333 toggleProjectFolder,
1334 renderedSettledThreads,
1335 visibleSnoozedThreads,
1336 visibleWorkingThreads,
1337 orderedThreadKeys,
1338 threadByKey,
1339 settledThreadKeys,
1340 snoozedThreadKeys,
1341 sectionByThreadKey,
1342 pinnedKeys,
1343 activeKeys,
1344 pinnedKeysById,
1345 activeKeysById,
1346 } = useSidebarThreads({
1347 projectScopeKey,
1348 scopedProjectKeys,
1349 serverConfigs,
1350 connectedEnvironmentIds,
1351 optimisticDrop,
1352 threads: listedThreads,
1353 delegatedUnderParent,
1354 routeRowThreadKey,
1355 folderGroups: boringSidebarEnabled
1356 ? scopedProjectGroups.length === 0
1357 ? // An archived project keeps a folder for its active threads, below the rest.
1358 [...scopeGroups, ...projectGroups.filter((project) => project.archived)]
1359 : scopedProjectGroups
1360 : null,
1361 keepEmptyFolders: (group) =>
1362 scopedProjectGroups.length > 0 || (group.pinned && !group.archived),
1363 });
1364
1365 // Ranked across environments as the palette ranks them, so one
1366 // environment's list does not sit above another's better matches; rows
1367 // already shown keep their places while slower environments answer.
1368 const threadByMatchKey =
1369 threadSearch.matches.length === 0
1370 ? null
1371 : new Map(
1372 searchableThreads.map((thread) => [
1373 threadSearchMatchKey({ environmentId: thread.environmentId, threadId: thread.id }),
1374 thread,
1375 ]),
1376 );
1377 const rankedServerMatches =
1378 threadByMatchKey === null
1379 ? []
1380 : rankMessageMatches(
1381 threadSearch.matches,
1382 (match) => {
1383 const thread = threadByMatchKey.get(threadSearchMatchKey(match));
1384 return thread ? threadSearchSubject(thread, null) : undefined;
1385 },
1386 foldSearchQuery(threadSearchQuery),
1387 // oxlint-disable-next-line react/purity -- Recency ranking samples the clock when the search matches change; the compiler recomputes it only then.
1388 Date.now(),
1389 // A list filter, as on mobile: a pick would move rows unexplained.
1390 { picks: false },
1391 );
1392 const serverMatchByKey = new Map(
1393 rankedServerMatches.map((match) => [threadSearchMatchKey(match), match] as const),
1394 );
1395 const [shownMessageOrder, setShownMessageOrder] = useState<ShownOrder | null>(null);
1396 const messageOrder = nextShownOrder(
1397 shownMessageOrder,
1398 threadSearch.query,
1399 [...serverMatchByKey.keys()],
1400 Number.POSITIVE_INFINITY,
1401 );
1402 if (messageOrder !== shownMessageOrder) setShownMessageOrder(messageOrder);
1403 const { titleMatches: threadTitleResults, contentMatches: threadContentResults } =
1404 searchSidebarThreads(searchableThreads, threadSearchQuery, new Set(messageOrder.keys));
1405 const threadSearchResults = [...threadTitleResults, ...threadContentResults];
1406 // Only rows listed for their messages show one, and open find on it.
1407 const threadSearchMatchByKey = new Map(
1408 threadContentResults.flatMap((thread) => {
1409 const key = threadSearchMatchKey({
1410 environmentId: thread.environmentId,
1411 threadId: thread.id,
1412 });
1413 const match = serverMatchByKey.get(key);
1414 return match ? [[key, match] as const] : [];
1415 }),
1416 );
1417 const threadSearchResultKeys = threadSearchResults.map((thread) =>
1418 scopedThreadKey(scopeThreadRef(thread.environmentId, thread.id)),
1419 );
1420
1421 // The highlight follows its thread, so rows that arrive late do not move
1422 // it under Enter; a new query starts at the top.
1423 const activeSearchResultIndex = Math.max(
1424 0,
1425 searchHighlightKey === null ? 0 : threadSearchResultKeys.indexOf(searchHighlightKey),
1426 );
1427 const setActiveSearchResultIndex = (index: number | ((index: number) => number)) =>
1428 setSearchHighlightKey(
1429 threadSearchResultKeys[
1430 typeof index === "function" ? index(activeSearchResultIndex) : index
1431 ] ?? null,
1432 );
1433 const moveSearchHighlight = (step: 1 | -1) => {
1434 const count = threadSearchResults.length;
1435 setActiveSearchResultIndex((activeSearchResultIndex + step + count) % count);
1436 };
1437
1438 const orderedThreadKeysRef = useRef(orderedThreadKeys);
1439 // Read changing maps/sets through refs so streamed events preserve row callbacks.
1440 const threadByKeyRef = useRef(threadByKey);
1441 const settledThreadKeysRef = useRef(settledThreadKeys);
1442 const snoozedThreadKeysRef = useRef(snoozedThreadKeys);
1443
1444 const jumpLabelByKey = (() => {
1445 const mapping = new Map<string, string>();
1446 for (const [index, threadKey] of orderedThreadKeys.entries()) {
1447 const jumpCommand = threadJumpCommandForIndex(index);
1448 if (!jumpCommand) break;
1449 const label = shortcutLabelForCommand(keybindings, jumpCommand);
1450 if (label) mapping.set(threadKey, label);
1451 }
1452 return mapping;
1453 })();
1454
1455 const navigateToThread = (threadRef: ScopedThreadRef) => {
1456 if (useThreadSelectionStore.getState().selectedThreadKeys.size > 0) {
1457 clearSelection();
1458 }
1459 setSelectionAnchor(scopedThreadKey(threadRef));
1460 if (isMobile) {
1461 setOpenMobile(false);
1462 }
1463 return router.navigate({
1464 to: "/$environmentId/$threadId",
1465 params: buildThreadRouteParams(threadRef),
1466 });
1467 };
1468
1469 const handleThreadFileDrop = async (threadRef: ScopedThreadRef, files: File[]) => {
1470 const dropId = queuePendingFileDrop({ threadRef, files });
1471 const landedBefore =
1472 router.buildLocation({
1473 to: "/$environmentId/$threadId",
1474 params: buildThreadRouteParams(threadRef),
1475 }).pathname === router.state.location.pathname;
1476 if (landedBefore) return;
1477
1478 try {
1479 await navigateToThread(threadRef);
1480 const landed =
1481 router.buildLocation({
1482 to: "/$environmentId/$threadId",
1483 params: buildThreadRouteParams(threadRef),
1484 }).pathname === router.state.location.pathname;
1485 if (!landed) clearPendingFileDrop(dropId);
1486 } catch {
1487 clearPendingFileDrop(dropId);
1488 }
1489 };
1490
1491 const navigateToDraft = (draftId: DraftId) => {
1492 clearSelection();
1493 if (isMobile) {
1494 setOpenMobile(false);
1495 }
1496 void router.navigate({ to: "/draft/$draftId", params: { draftId } });
1497 };
1498
1499 const clearThreadSearch = () => {
1500 setThreadSearchQuery("");
1501 setSearchHighlightKey(null);
1502 };
1503 const selectThreadSearchResult = (thread: EnvironmentThreadShell) => {
1504 const ref = scopeThreadRef(thread.environmentId, thread.id);
1505 // A row listed for a message match opens find on it, as the palette does.
1506 const match = threadSearchMatchByKey.get(
1507 threadSearchMatchKey({ environmentId: thread.environmentId, threadId: thread.id }),
1508 );
1509 const query = threadSearch.query;
1510 clearThreadSearch();
1511 navigateToThread(ref);
1512 if (match) openThreadFindOnQuery(scopedThreadKey(ref), findForMessageMatch(match, query));
1513 };
1514 const handleThreadSearchKeyDown = (event: ReactKeyboardEvent<HTMLInputElement>) => {
1515 if (event.nativeEvent.isComposing || event.keyCode === 229) return;
1516 if (event.key === "Escape" && isSearchingThreads) {
1517 event.preventDefault();
1518 event.stopPropagation();
1519 clearThreadSearch();
1520 return;
1521 }
1522 if (threadSearchResults.length === 0) return;
1523 if (event.key === "ArrowDown") {
1524 event.preventDefault();
1525 moveSearchHighlight(1);
1526 return;
1527 }
1528 if (event.key === "ArrowUp") {
1529 event.preventDefault();
1530 moveSearchHighlight(-1);
1531 return;
1532 }
1533 if (event.key === "Enter") {
1534 event.preventDefault();
1535 const result = threadSearchResults[activeSearchResultIndex];
1536 if (result) selectThreadSearchResult(result);
1537 }
1538 };
1539
1540 // The ref write stops the compiler memoizing this, and every row receives it.
1541 const startThreadRename = useStableCallback((threadRef: ScopedThreadRef, title: string) => {
1542 if (!readEnvironmentScope(threadRef.environmentId, AuthOrchestrationOperateScope)) return;
1543 setRenamingThreadRef(threadRef);
1544 setRenamingTitle(title);
1545 renamingOriginalTitleRef.current = title;
1546 });
1547 const cancelThreadRename = () => setRenamingThreadRef(null);
1548 const commitThreadRename = (threadRef: ScopedThreadRef, title: string) => {
1549 const originalTitle = renamingOriginalTitleRef.current;
1550 void (async () => {
1551 if (!readEnvironmentScope(threadRef.environmentId, AuthOrchestrationOperateScope)) return;
1552 const trimmed = title.trim();
1553 setRenamingThreadRef(null);
1554 if (trimmed.length === 0) {
1555 toastManager.add({ type: "warning", title: gt("Thread title cannot be empty") });
1556 return;
1557 }
1558 if (trimmed === originalTitle) return;
1559 const result = await updateThreadMetadata({
1560 environmentId: threadRef.environmentId,
1561 input: { threadId: threadRef.threadId, title: trimmed },
1562 });
1563 if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) {
1564 const error = squashAtomCommandFailure(result);
1565 toastManager.add(
1566 stackedThreadToast({
1567 type: "error",
1568 title: gt("Failed to rename thread"),
1569 description: thrownErrorMessage(error, m) ?? gt("An error occurred."),
1570 }),
1571 );
1572 }
1573 })();
1574 };
1575
1576 const readOpensPullRequestsInRightPanel = useStableCallback(() => routeThreadRef !== null);
1577 const handleThreadClick = (event: ReactMouseEvent, threadRef: ScopedThreadRef) => {
1578 if (isSidebarNestedLinkClick(event.target)) return;
1579 const isMac = isMacPlatform(navigator.platform);
1580 const isModClick = isMac ? event.metaKey : event.ctrlKey;
1581 const threadKey = scopedThreadKey(threadRef);
1582 if (isModClick) {
1583 event.preventDefault();
1584 toggleThreadSelection(threadKey);
1585 return;
1586 }
1587 if (event.shiftKey) {
1588 event.preventDefault();
1589 rangeSelectTo(threadKey, orderedThreadKeysRef.current);
1590 return;
1591 }
1592 if (isTrailingDoubleClick(event.detail)) {
1593 return;
1594 }
1595 navigateToThread(threadRef);
1596 };
1597
1598 // Snapshot navigation before partition mutation; background parks use a null plan.
1599 const planForwardNavigation = (
1600 threadKey: string,
1601 coParkingKeys?: ReadonlySet<string>,
1602 ): (() => void) | null => {
1603 if (readRouteThreadKey(router) !== threadKey) return null;
1604 const shell = threadByKeyRef.current.get(threadKey);
1605 const orderedKeys = orderedThreadKeysRef.current;
1606 const settledKeys = settledThreadKeysRef.current;
1607 const snoozedKeys = snoozedThreadKeysRef.current;
1608 const currentIndex = orderedKeys.indexOf(threadKey);
1609 const nextCardKey =
1610 currentIndex === -1
1611 ? null
1612 : ([...orderedKeys.slice(currentIndex + 1), ...orderedKeys.slice(0, currentIndex)].find(
1613 (key) => !settledKeys.has(key) && !snoozedKeys.has(key) && !coParkingKeys?.has(key),
1614 ) ?? null);
1615 const nextThread = nextCardKey ? threadByKeyRef.current.get(nextCardKey) : null;
1616 return nextThread
1617 ? () => navigateToThread(scopeThreadRef(nextThread.environmentId, nextThread.id))
1618 : shell
1619 ? () => void handleNewThread(scopeProjectRef(shell.environmentId, shell.projectId))
1620 : () => void router.navigate({ to: "/" });
1621 };
1622
1623 const attemptSettle = (
1624 threadRef: ScopedThreadRef,
1625 opts: { coSettlingKeys?: ReadonlySet<string> } = {},
1626 ) => {
1627 void (async () => {
1628 const threadKey = scopedThreadKey(threadRef);
1629 if (settlingThreadKeysRef.current.has(threadKey)) return;
1630 settlingThreadKeysRef.current.add(threadKey);
1631 const navigateAfterSettle = planForwardNavigation(threadKey, opts.coSettlingKeys);
1632 const result = await settleThread(threadRef);
1633 settlingThreadKeysRef.current.delete(threadKey);
1634 if (result._tag === "Failure") {
1635 if (!isAtomCommandInterrupted(result)) {
1636 const error = squashAtomCommandFailure(result);
1637 toastManager.add(
1638 stackedThreadToast({
1639 type: "error",
1640 title: gt("Failed to settle thread"),
1641 description: thrownErrorMessage(error, m) ?? gt("An error occurred."),
1642 }),
1643 );
1644 }
1645 return;
1646 }
1647 if (
1648 shouldNavigateAfterThreadPark({
1649 threadKey,
1650 currentThreadKey: readRouteThreadKey(router),
1651 action: "settle",
1652 now: new Date().toISOString(),
1653 thread: readThreadShell(threadRef),
1654 })
1655 ) {
1656 navigateAfterSettle?.();
1657 }
1658 })();
1659 };
1660 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- registers this sidebar's settle handler in the module-level settleAndAdvance registry
1661 useEffect(() => registerSettleAndAdvance(attemptSettle), [attemptSettle]);
1662 const settleThreads = (threadKeys: readonly string[]) => {
1663 const coSettlingKeys = new Set(threadKeys);
1664 for (const threadKey of threadKeys) {
1665 const thread = threadByKeyRef.current.get(threadKey);
1666 if (!thread || thread.settledOverride === "settled") continue;
1667 attemptSettle(scopeThreadRef(thread.environmentId, thread.id), { coSettlingKeys });
1668 }
1669 };
1670 const attemptUnsettle = (threadRef: ScopedThreadRef) => {
1671 void (async () => {
1672 const result = await unsettleThread(threadRef);
1673 if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) {
1674 const error = squashAtomCommandFailure(result);
1675 toastManager.add(
1676 stackedThreadToast({
1677 type: "error",
1678 title: gt("Failed to un-settle thread"),
1679 description: thrownErrorMessage(error, m) ?? gt("An error occurred."),
1680 }),
1681 );
1682 }
1683 })();
1684 };
1685 const attemptUnsnooze = (threadRef: ScopedThreadRef) => {
1686 void (async () => {
1687 const result = await unsnoozeThread(threadRef);
1688 if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) {
1689 const error = squashAtomCommandFailure(result);
1690 toastManager.add(
1691 stackedThreadToast({
1692 type: "error",
1693 title: gt("Failed to wake thread"),
1694 description: thrownErrorMessage(error, m) ?? gt("An error occurred."),
1695 }),
1696 );
1697 }
1698 })();
1699 };
1700 const restrictBelowPins: Modifier = (args) =>
1701 restrictBelowSidebarLabel(args, dragLabelOffsetRef.current);
1702 const dndModifiers = [
1703 restrictToVerticalAxis,
1704 restrictBelowPins,
1705 restrictToFirstScrollableAncestor,
1706 ];
1707 const attachListMotionRef = (node: HTMLUListElement) => {
1708 threadListRef.current = node;
1709 const motion = createSidebarListMotion(node);
1710 listMotionRef.current = motion;
1711 motion.update(false);
1712 const shiftGuard = createSidebarShiftGuard(node);
1713 shiftGuardRef.current = shiftGuard;
1714 return () => {
1715 // Search replaces this list while the Sidebar stays mounted, and a drag
1716 // whose rows are gone can never drop. The compiler memoizes this callback
1717 // with no deps (it reads only refs), so the cleanup runs only on unmount.
1718 dragSensorRef.current?.cancel();
1719 motion.dispose();
1720 shiftGuard.dispose();
1721 if (listMotionRef.current === motion) listMotionRef.current = null;
1722 if (shiftGuardRef.current === shiftGuard) shiftGuardRef.current = null;
1723 if (threadListRef.current === node) threadListRef.current = null;
1724 };
1725 };
1726
1727 const attachTreeRef = (node: HTMLUListElement) => {
1728 const detachMotion = attachListMotionRef(node);
1729 const detachTree = attachSidebarTree(node);
1730 return () => {
1731 detachTree?.();
1732 detachMotion();
1733 };
1734 };
1735
1736 // Folder rows only drag out to the composer; folders own their order, so nothing drops in the list.
1737 const isContextDrag =
1738 projectFolders !== null ||
1739 dragState?.contextDrag === true ||
1740 dragState?.activeSection === "working";
1741 const dragTargetSection = isContextDrag ? null : (dragState?.targetSection ?? null);
1742 const finishThreadDrag = (started: boolean) => {
1743 dragSensorRef.current = null;
1744 contextDragKeyRef.current = null;
1745 dragScrollRef.current = null;
1746 endThreadContextDrag();
1747 if (started) {
1748 listMotionRef.current?.release();
1749 setDragState(null);
1750 }
1751 };
1752 const attachDragSensor = (sensor: SidebarPointerSensor) => {
1753 dragSensorRef.current = sensor;
1754 };
1755 const cancelThreadDrag = () => {
1756 dragSensorRef.current?.cancel();
1757 };
1758 const contextDragThreads = (): ReadonlyArray<ScopedThreadRef> => {
1759 const key = contextDragKeyRef.current;
1760 if (key === null) return [];
1761 const selected = useThreadSelectionStore.getState().selectedThreadKeys;
1762 const keys = selected.has(key) ? [...selected] : [key];
1763 return keys.flatMap((candidate) => {
1764 const ref = parseScopedThreadKey(candidate);
1765 return ref ? [ref] : [];
1766 });
1767 };
1768 const pointerOutsideThreadList = (point: { x: number; y: number }) => {
1769 // Search results replace the thread list, so only one of them is mounted.
1770 const bounds = (threadListRef.current ?? searchResultsListRef.current)?.getBoundingClientRect();
1771 return bounds !== undefined && (point.x < bounds.left || point.x > bounds.right);
1772 };
1773 // The path out of the list often crosses dnd-kit's edge zone, which autoscrolls the sidebar.
1774 const restoreDragScroll = () => {
1775 const scroll = dragScrollRef.current;
1776 if (scroll && scroll.viewport.scrollTop !== scroll.top) scroll.viewport.scrollTop = scroll.top;
1777 };
1778 const moveThreadContextDrag = (point: { x: number; y: number }) => {
1779 // Search results cannot reorder, so their context preview starts inside the list.
1780 const contextDrag = searchResultsListRef.current !== null || pointerOutsideThreadList(point);
1781 setDragState((current) =>
1782 current === null || current.contextDrag === contextDrag
1783 ? current
1784 : { ...current, contextDrag },
1785 );
1786 if (!contextDrag) {
1787 endThreadContextDrag();
1788 return false;
1789 }
1790 restoreDragScroll();
1791 const threads = contextDragThreads();
1792 const threadRef = parseScopedThreadKey(contextDragKeyRef.current ?? "");
1793 const title = (threadRef && readThreadShell(threadRef)?.title.trim()) || gt("Thread");
1794 moveThreadContextDragGhost(point, { title, count: threads.length });
1795 return true;
1796 };
1797 const dropThreadContextDrag = (point: { x: number; y: number }) => {
1798 if (!pointerOutsideThreadList(point)) return false;
1799 restoreDragScroll();
1800 dropThreadContext(point, contextDragThreads());
1801 return true;
1802 };
1803 // useSensor memoizes options identity; fresh options rebuild DndContext and every sortable row.
1804 const pointerSensorOptions = {
1805 distance: SIDEBAR_DRAG_DISTANCE,
1806 onAttach: attachDragSensor,
1807 onFinish: finishThreadDrag,
1808 onMove: moveThreadContextDrag,
1809 onDrop: dropThreadContextDrag,
1810 };
1811 const dndSensors = useSensors(useSensor(SidebarPointerSensor, pointerSensorOptions));
1812 const sectionByThreadKeyRef = useRef(sectionByThreadKey);
1813 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- publishes committed list data to refs read by stable drag and sweep callbacks
1814 useLayoutEffect(() => {
1815 projectGroupsRef.current = projectGroups;
1816 orderedThreadKeysRef.current = orderedThreadKeys;
1817 threadByKeyRef.current = threadByKey;
1818 settledThreadKeysRef.current = settledThreadKeys;
1819 snoozedThreadKeysRef.current = snoozedThreadKeys;
1820 sectionByThreadKeyRef.current = sectionByThreadKey;
1821 });
1822 const startActionSweep = useStableCallback(
1823 (threadRef: ScopedThreadRef, action: SidebarSweepAction, event: PointerEvent) => {
1824 const originKey = scopedThreadKey(threadRef);
1825 const originSection = sectionByThreadKeyRef.current.get(originKey);
1826 const canApply = (key: string) => {
1827 const thread = threadByKeyRef.current.get(key);
1828 return (
1829 thread !== undefined &&
1830 sectionByThreadKeyRef.current.get(key) === originSection &&
1831 serverConfigs.has(thread.environmentId)
1832 );
1833 };
1834 let targetKey: string | null = null;
1835 let sweptKeys: string[] = [];
1836 const sweepTo = (key: string | null) => {
1837 if (key === null || key === targetKey) return;
1838 targetKey = key;
1839 sweptKeys = resolveSidebarSweepKeys(orderedThreadKeysRef.current, originKey, key, canApply);
1840 setActionSweep({ action, keys: new Set(sweptKeys) });
1841 };
1842 dragSensorRef.current = new SidebarPointerSensor({
1843 active: originKey,
1844 event,
1845 options: {
1846 distance: SIDEBAR_DRAG_DISTANCE,
1847 onAttach: () => {},
1848 onFinish: () => {
1849 dragSensorRef.current = null;
1850 setActionSweep(null);
1851 },
1852 },
1853 onPending: () => {},
1854 onStart: () => sweepTo(originKey),
1855 onMove: ({ y }) =>
1856 sweepTo(threadListRef.current && sidebarThreadKeyAtY(threadListRef.current, y)),
1857 onEnd: () => {
1858 const keys = sweptKeys.filter(canApply);
1859 if (action === "settle") {
1860 settleThreads(keys);
1861 return;
1862 }
1863 for (const key of keys) {
1864 const ref = parseScopedThreadKey(key);
1865 if (ref === null) continue;
1866 if (action === "unsettle") attemptUnsettle(ref);
1867 else attemptUnsnooze(ref);
1868 }
1869 },
1870 onCancel: () => {},
1871 onAbort: () => {},
1872 });
1873 },
1874 );
1875 // Release during render when server state catches up so canonical order appears in the same frame.
1876 if (
1877 optimisticDrop !== null &&
1878 isOptimisticDropReleased({
1879 optimisticDrop,
1880 threads,
1881 pinnedKeys,
1882 activeKeys,
1883 now: snoozeNow,
1884 })
1885 ) {
1886 setOptimisticDrop(null);
1887 }
1888 const attemptPin = (threadRef: ScopedThreadRef) => {
1889 void (async () => {
1890 const result = await pinThread(threadRef);
1891 if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) {
1892 const error = squashAtomCommandFailure(result);
1893 toastManager.add(
1894 stackedThreadToast({
1895 type: "error",
1896 title: gt("Failed to pin thread"),
1897 description: thrownErrorMessage(error, m) ?? gt("An error occurred."),
1898 }),
1899 );
1900 }
1901 })();
1902 };
1903 const attemptUnpin = (threadRef: ScopedThreadRef) => {
1904 void (async () => {
1905 const result = await confirmAndUnpinThread(threadRef);
1906 if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) {
1907 const error = squashAtomCommandFailure(result);
1908 toastManager.add(
1909 stackedThreadToast({
1910 type: "error",
1911 title: gt("Failed to unpin thread"),
1912 description: thrownErrorMessage(error, m) ?? gt("An error occurred."),
1913 }),
1914 );
1915 }
1916 })();
1917 };
1918
1919 const handleThreadDragStart = (event: DragStartEvent) => {
1920 const activeKey = String(event.active.id);
1921 contextDragKeyRef.current = activeKey;
1922 const activeSection = sectionByThreadKey.get(activeKey);
1923 if (activeSection === undefined) return;
1924 listMotionRef.current?.suspend();
1925 const list = threadListRef.current;
1926 const viewport = list?.closest('[data-slot="scroll-area-viewport"]');
1927 dragScrollRef.current = viewport ? { viewport, top: viewport.scrollTop } : null;
1928 const header = list?.querySelector<HTMLElement>('[data-testid="sidebar-pinned-header"]');
1929 if (list && header) {
1930 const listRect = list.getBoundingClientRect();
1931 const scale = list.offsetWidth > 0 ? listRect.width / list.offsetWidth : 1;
1932 dragLabelOffsetRef.current =
1933 header.getBoundingClientRect().top - listRect.top + SIDEBAR_DRAG_LABEL_HEIGHT * scale;
1934 } else {
1935 dragLabelOffsetRef.current = 0;
1936 }
1937 setDragState({
1938 activeKey,
1939 activeSection,
1940 targetSection: activeSection,
1941 contextDrag: false,
1942 occurredAt: new Date().toISOString(),
1943 activationY:
1944 event.activatorEvent instanceof PointerEvent ? event.activatorEvent.clientY : null,
1945 });
1946 };
1947 const hasProjectFolders = projectFolders !== null && projectFolders.length > 0;
1948 const sidebarListItemsFresh = ((): readonly SidebarListItem[] => {
1949 const rowsOf = (
1950 list: readonly EnvironmentThreadShell[],
1951 section: SidebarSection,
1952 ): SidebarListItem[] =>
1953 list.map((thread) => {
1954 const key = scopedThreadKey(scopeThreadRef(thread.environmentId, thread.id));
1955 return { kind: "thread", key, section };
1956 });
1957 // Boring mode keeps a pinned open project or one the user filtered to, so it can start a thread.
1958 if (
1959 !hasProjectFolders &&
1960 pinnedThreads.length +
1961 activeThreads.length +
1962 workingThreads.length +
1963 snoozedThreads.length +
1964 settledCount ===
1965 0
1966 ) {
1967 return [];
1968 }
1969 const items: SidebarListItem[] = [{ kind: "marker", marker: "pinned-header" }];
1970 const pinnedRows = rowsOf(pinnedThreads, "pinned");
1971 items.push(...pinnedRows);
1972 items.push({ kind: "marker", marker: "pinned-divider" });
1973 const activeRows = rowsOf(activeThreads, "active");
1974 items.push({ kind: "marker", marker: "active-placeholder" });
1975 items.push(...activeRows);
1976 if (workingThreads.length > 0) {
1977 items.push({ kind: "marker", marker: "working-header" });
1978 items.push(...rowsOf(visibleWorkingThreads, "working"));
1979 }
1980 if (snoozedThreads.length > 0) {
1981 items.push({ kind: "marker", marker: "snoozed-header" });
1982 items.push(...rowsOf(visibleSnoozedThreads, "snoozed"));
1983 }
1984 items.push({ kind: "marker", marker: "settled-header" });
1985 const settledRows = rowsOf(renderedSettledThreads, "settled");
1986 items.push({ kind: "marker", marker: "settled-placeholder" });
1987 items.push(...settledRows);
1988 return items;
1989 })();
1990 // Preserve the list while streamed updates leave order unchanged to retain row memoization.
1991 const sidebarListItemsKey = sidebarListItemsFresh
1992 .map((item) => (item.kind === "thread" ? item.section + ":" + item.key : item.marker))
1993 .join("\n");
1994 const [sidebarListItemsState, setSidebarListItems] = useState(sidebarListItemsFresh);
1995 const [sidebarListItemsKeyState, setSidebarListItemsKeyState] = useState(sidebarListItemsKey);
1996 let sidebarListItems = sidebarListItemsState;
1997 if (sidebarListItemsKeyState !== sidebarListItemsKey) {
1998 setSidebarListItemsKeyState(sidebarListItemsKey);
1999 setSidebarListItems(sidebarListItemsFresh);
2000 // Update the local list too; threadByKey already omits rows moved into collapsed shelves.
2001 sidebarListItems = sidebarListItemsFresh;
2002 }
2003 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- cancels the dnd-kit drag sensor when the dragged row leaves the list
2004 useEffect(() => {
2005 if (
2006 dragState !== null &&
2007 !sidebarListItems.some((item) => item.kind === "thread" && item.key === dragState.activeKey)
2008 ) {
2009 cancelThreadDrag();
2010 }
2011 }, [cancelThreadDrag, dragState, sidebarListItems]);
2012 // Only order, section, or draft changes need layout reads and motion.
2013 const listMotionLayoutKey = [
2014 sidebarListItemsKey,
2015 projectFolders
2016 ?.map((folder) => `${folder.group.projectKey}:${folder.threads.length}`)
2017 .join("\n") ?? "",
2018 visibleDraftSessionCount,
2019 routeDraftIdForRows ?? "",
2020 ].join("\0");
2021 const listMotionAnimate =
2022 dragState === null && sidebarListItems.length + visibleDraftSessionCount > 0;
2023 // Cache on both fields so layout-key changes trigger the effect even when animate is unchanged.
2024 const listMotionPass = { layoutKey: listMotionLayoutKey, animate: listMotionAnimate };
2025 const shelfExpansionKey = [workingShelfExpanded, snoozedShelfExpanded, settledShelfExpanded].join(
2026 ":",
2027 );
2028 const previousShelfExpansionKeyRef = useRef(shelfExpansionKey);
2029 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- records moved rows and updates list motion after each layout-affecting commit
2030 useLayoutEffect(() => {
2031 shiftGuardRef.current?.update();
2032 // Shelf rows would travel over stationary headers below the bottom-anchored shelf.
2033 const shelvesUnchanged = previousShelfExpansionKeyRef.current === shelfExpansionKey;
2034 previousShelfExpansionKeyRef.current = shelfExpansionKey;
2035 listMotionRef.current?.update(listMotionPass.animate && shelvesUnchanged);
2036 }, [listMotionPass, shelfExpansionKey]);
2037 const handleThreadDragOver = (event: DragOverEvent) => {
2038 const target = event.over
2039 ? resolveSidebarDropTarget(sidebarListItems, String(event.active.id), String(event.over.id))
2040 : null;
2041 setDragState((current) =>
2042 current === null || current.activeKey !== String(event.active.id)
2043 ? current
2044 : { ...current, targetSection: target?.section ?? null },
2045 );
2046 };
2047 const sortableIds = sidebarListItems.map(sidebarListItemId);
2048 // Keep non-drag orders constant to preserve sorting strategy and row identity during streaming.
2049 const { settledOrder: draggedSettledOrder, activeOrder: draggedActiveOrder } =
2050 dragState === null
2051 ? NO_DRAGGED_ORDERS
2052 : resolveDraggedOrders({
2053 drag: dragState,
2054 threadByKey,
2055 settledThreads,
2056 activeThreads,
2057 workingShelfEnabled,
2058 });
2059 const sidebarSortingStrategy = createSidebarSortingStrategy({
2060 items: sidebarListItems,
2061 enabled: !isContextDrag,
2062 boundaryLabelHeight: SIDEBAR_DRAG_LABEL_HEIGHT,
2063 settledOrder: draggedSettledOrder,
2064 ...(draggedActiveOrder === undefined ? {} : { activeOrder: draggedActiveOrder }),
2065 settledExpanded: settledShelfExpanded,
2066 settledVisibleCount,
2067 routeThreadKey: routeRowThreadKey,
2068 snoozedThreadCount: snoozedThreads.length,
2069 });
2070 const draggedThreadKey = dragState?.activeKey;
2071 const draggedFromSection = dragState?.activeSection;
2072 const dragActivationY = dragState?.activationY;
2073 const dndCollisionDetection = (() => {
2074 if (draggedThreadKey === undefined || draggedFromSection === undefined)
2075 return createSidebarCollisionDetection(() => true);
2076 const source = threadByKey.get(draggedThreadKey);
2077 if (source === undefined) return createSidebarCollisionDetection(() => false);
2078 return createSidebarCollisionDetection(
2079 (id) => {
2080 const target = resolveSidebarDropTarget(sidebarListItems, draggedThreadKey, id);
2081 if (target === null) return false;
2082 return (
2083 planSidebarThreadDrop({
2084 activeKey: draggedThreadKey,
2085 activeSection: draggedFromSection,
2086 activePinned: source.pinnedAt != null,
2087 activeSettled: source.settledOverride === "settled",
2088 supportsSettlement: serverConfigs.has(source.environmentId),
2089 target,
2090 pinnedOrder: pinnedKeys,
2091 pinnedKeysById,
2092 reorderableKeys: draggableThreadKeys,
2093 activeOrder: activeKeys,
2094 activeKeysById,
2095 activeReorderableKeys: activeReorderableThreadKeys,
2096 activeTimeOrdered: workingShelfEnabled,
2097 }).kind !== "none"
2098 );
2099 },
2100 {
2101 items: sidebarListItems,
2102 activationY: dragActivationY ?? null,
2103 },
2104 );
2105 })();
2106 const handleThreadDragEnd = (event: DragEndEvent) => {
2107 if (projectFolders !== null) return;
2108 const activeKey = String(event.active.id);
2109 const activeSection = sectionByThreadKey.get(activeKey);
2110 const target =
2111 event.over === null
2112 ? null
2113 : resolveSidebarDropTarget(sidebarListItems, activeKey, String(event.over.id));
2114 const activeThread = threadByKey.get(activeKey);
2115 if (activeSection === undefined || target === null || activeThread === undefined) return;
2116 const threadRef = scopeThreadRef(activeThread.environmentId, activeThread.id);
2117 const plan = planSidebarThreadDrop({
2118 activeKey,
2119 activeSection,
2120 activePinned: activeThread.pinnedAt != null,
2121 activeSettled: activeThread.settledOverride === "settled",
2122 supportsSettlement: serverConfigs.has(activeThread.environmentId),
2123 target,
2124 pinnedOrder: pinnedKeys,
2125 pinnedKeysById,
2126 reorderableKeys: draggableThreadKeys,
2127 activeOrder: activeKeys,
2128 activeKeysById,
2129 activeReorderableKeys: activeReorderableThreadKeys,
2130 activeTimeOrdered: workingShelfEnabled,
2131 });
2132 if (plan.kind === "none") return;
2133 if (plan.kind === "settle" && settlingThreadKeysRef.current.has(activeKey)) return;
2134 const assignments =
2135 plan.kind === "pin"
2136 ? [
2137 ...(plan.orderKey === undefined ? [] : [{ id: activeKey, orderKey: plan.orderKey }]),
2138 ...plan.extraAssignments,
2139 ]
2140 : plan.kind === "reorder-pinned" || plan.kind === "move-active"
2141 ? plan.assignments
2142 : [];
2143 if (
2144 !checkThreadOperations(
2145 [activeKey, ...assignments.map(({ id }) => id)].flatMap((key) => {
2146 const thread = threadByKey.get(key);
2147 return thread ? [thread] : [];
2148 }),
2149 )
2150 )
2151 return;
2152 const drop = {
2153 key: activeKey,
2154 sourceSection: activeSection,
2155 section: target.section,
2156 occurredAt: new Date().toISOString(),
2157 clearsSnooze:
2158 plan.kind === "pin" ||
2159 plan.kind === "settle" ||
2160 (plan.kind === "move-active" && plan.unsnooze),
2161 order: plan.kind === "settle" ? null : plan.order,
2162 keysAtDrop: target.section === "active" ? activeKeysById : pinnedKeysById,
2163 assignedKeys: new Map(assignments.map(({ id, orderKey }) => [id, orderKey])),
2164 };
2165 setOptimisticDrop(drop);
2166 void (async () => {
2167 const run = async (
2168 operation: Promise<AtomCommandResult<unknown, unknown>>,
2169 title: string,
2170 ) => {
2171 const result = await operation;
2172 if (result._tag === "Success") return true;
2173 setOptimisticDrop((current) => (current === drop ? null : current));
2174 if (!isAtomCommandInterrupted(result)) {
2175 const error = squashAtomCommandFailure(result);
2176 toastManager.add(
2177 stackedThreadToast({
2178 type: "error",
2179 title,
2180 description: thrownErrorMessage(error, m) ?? gt("An error occurred."),
2181 }),
2182 );
2183 }
2184 return false;
2185 };
2186 switch (plan.kind) {
2187 case "settle": {
2188 settlingThreadKeysRef.current.add(activeKey);
2189 const navigateAfterSettle = planForwardNavigation(activeKey);
2190 const settled = await run(settleThread(threadRef), gt("Failed to settle thread")).finally(
2191 () => settlingThreadKeysRef.current.delete(activeKey),
2192 );
2193 if (
2194 settled &&
2195 shouldNavigateAfterThreadPark({
2196 threadKey: activeKey,
2197 currentThreadKey: readRouteThreadKey(router),
2198 action: "settle",
2199 now: new Date().toISOString(),
2200 thread: readThreadShell(threadRef),
2201 })
2202 )
2203 navigateAfterSettle?.();
2204 return;
2205 }
2206 case "move-active":
2207 if (plan.unpin && !(await run(unpinThread(threadRef), gt("Failed to unpin thread"))))
2208 return;
2209 if (
2210 plan.unsettle &&
2211 !(await run(unsettleThread(threadRef), gt("Failed to un-settle thread")))
2212 )
2213 return;
2214 if (plan.unsnooze && !(await run(unsnoozeThread(threadRef), gt("Failed to wake thread"))))
2215 return;
2216 break;
2217 case "pin":
2218 if (
2219 !(await run(
2220 pinThread(threadRef, plan.orderKey === undefined ? {} : { orderKey: plan.orderKey }),
2221 gt("Failed to pin thread"),
2222 ))
2223 )
2224 return;
2225 break;
2226 case "reorder-pinned":
2227 break;
2228 }
2229 const keyWrites = plan.kind === "pin" ? plan.extraAssignments : plan.assignments;
2230 for (const assignment of keyWrites) {
2231 const thread = threadByKey.get(assignment.id);
2232 if (thread === undefined) continue;
2233 if (
2234 !(await run(
2235 (plan.kind === "move-active" ? reorderActiveThread : reorderPinnedThread)(
2236 scopeThreadRef(thread.environmentId, thread.id),
2237 assignment.orderKey,
2238 ),
2239 plan.kind === "move-active"
2240 ? gt("Failed to reorder active threads")
2241 : gt("Failed to reorder pinned threads"),
2242 ))
2243 )
2244 return;
2245 }
2246 })();
2247 };
2248 const performSnooze = async (
2249 threadRef: ScopedThreadRef,
2250 preset: Pick<SnoozePreset, "snoozedUntil">,
2251 opts: { coSnoozingKeys?: ReadonlySet<string> } = {},
2252 ) => {
2253 const threadKey = scopedThreadKey(threadRef);
2254 if (snoozingThreadKeysRef.current.has(threadKey)) {
2255 return { status: "skipped" } as const;
2256 }
2257 snoozingThreadKeysRef.current.add(threadKey);
2258 const navigateAfterSnooze = planForwardNavigation(threadKey, opts.coSnoozingKeys);
2259 const result = await snoozeThread(threadRef, preset.snoozedUntil);
2260 snoozingThreadKeysRef.current.delete(threadKey);
2261 if (result._tag === "Failure") {
2262 return isAtomCommandInterrupted(result)
2263 ? ({ status: "interrupted" } as const)
2264 : ({ status: "failure", error: squashAtomCommandFailure(result) } as const);
2265 }
2266 if (
2267 shouldNavigateAfterThreadPark({
2268 threadKey,
2269 currentThreadKey: readRouteThreadKey(router),
2270 action: "snooze",
2271 now: new Date().toISOString(),
2272 thread: readThreadShell(threadRef),
2273 })
2274 ) {
2275 navigateAfterSnooze?.();
2276 }
2277 return { status: "success" } as const;
2278 };
2279 const attemptSnooze = useStableCallback(
2280 (
2281 threadRef: ScopedThreadRef,
2282 preset: Pick<SnoozePreset, "snoozedUntil">,
2283 opts: { coSnoozingKeys?: ReadonlySet<string> } = {},
2284 ) => {
2285 void (async () => {
2286 const outcome = await performSnooze(threadRef, preset, opts);
2287 if (outcome.status === "failure") {
2288 toastManager.add(
2289 stackedThreadToast({
2290 type: "error",
2291 title: gt("Failed to snooze thread"),
2292 description: thrownErrorMessage(outcome.error, m) ?? gt("An error occurred."),
2293 }),
2294 );
2295 return;
2296 }
2297 })();
2298 },
2299 );
2300
2301 const handleMultiSelectContextMenu = useStableCallback(
2302 async (position: { x: number; y: number }, source: ContextMenuSource) => {
2303 const api = readLocalApi();
2304 if (!api) return;
2305 const selectedThreadKeys = [...useThreadSelectionStore.getState().selectedThreadKeys];
2306 const threadKeys = selectedThreadKeys.filter((threadKey) =>
2307 threadByKeyRef.current.has(threadKey),
2308 );
2309 if (threadKeys.length === 0) return;
2310 const count = threadKeys.length;
2311 const selectionNow = new Date();
2312 const selectedThreads = threadKeys.flatMap((threadKey) => {
2313 const thread = threadByKeyRef.current.get(threadKey);
2314 return thread ? [thread] : [];
2315 });
2316 const settlingThreads = selectedThreads.filter(
2317 (thread) => thread.settledOverride !== "settled",
2318 );
2319 const canSnoozeSelection = selectedThreads.every(
2320 (thread) =>
2321 serverConfigs.has(thread.environmentId) &&
2322 canSnooze(thread, { now: selectionNow.toISOString() }),
2323 );
2324 const titleRegenerationThreads = selectedThreads.filter((thread) =>
2325 serverConfigs.has(thread.environmentId),
2326 );
2327 const regeneratableTitleThreads = titleRegenerationThreads.filter(
2328 (thread) => thread.titleRegeneration == null,
2329 );
2330 const titleRegenerationMenuItem = buildBulkTitleRegenerationContextMenuItem({
2331 supportedCount: titleRegenerationThreads.length,
2332 actionableCount: regeneratableTitleThreads.length,
2333 });
2334 const pinnedSelectedThreads = selectedThreads.filter(
2335 (thread) => serverConfigs.has(thread.environmentId) && thread.pinnedAt != null,
2336 );
2337 const unpinMenuItem = buildBulkUnpinContextMenuItem({
2338 pinnedCount: pinnedSelectedThreads.length,
2339 });
2340 // Presets sync across environments, so the first selected thread's stand for all.
2341 const menuOpenedAt = new Date();
2342 const snoozePresets = resolveSnoozePresets(
2343 menuOpenedAt,
2344 timestampFormat,
2345 selectedThreads[0]!.environmentId,
2346 );
2347 const clicked = await settlePromise(() =>
2348 api.contextMenu.show(
2349 [
2350 ...(unpinMenuItem
2351 ? [{ ...unpinMenuItem, disabled: !canOperateThreads(pinnedSelectedThreads) }]
2352 : []),
2353 {
2354 id: "settle",
2355 label: gt("Settle ({count})", { count }),
2356 disabled: settlingThreads.length === 0 || !canOperateThreads(settlingThreads),
2357 },
2358 ...(canSnoozeSelection
2359 ? [
2360 {
2361 id: "snooze",
2362 label: gt("Snooze ({count})", { count }),
2363 disabled: !canOperateThreads(selectedThreads),
2364 children: [
2365 ...snoozePresets.map((preset) => ({
2366 id: `snooze:${preset.id}`,
2367 label: preset.label,
2368 detail: preset.whenLabel,
2369 disabled: !canOperateThreads(selectedThreads),
2370 })),
2371 {
2372 id: "snooze:custom",
2373 label: gt("Custom…"),
2374 separatorBefore: snoozePresets.length > 0,
2375 disabled: !canOperateThreads(selectedThreads),
2376 },
2377 ],
2378 },
2379 ]
2380 : []),
2381 ...(titleRegenerationMenuItem
2382 ? [
2383 {
2384 ...titleRegenerationMenuItem,
2385 disabled:
2386 titleRegenerationMenuItem.disabled ||
2387 !canOperateThreads(regeneratableTitleThreads),
2388 },
2389 ]
2390 : []),
2391 { id: "mark-unread", label: gt("Mark unread ({count})", { count }) },
2392 {
2393 id: "delete",
2394 label: gt("Delete ({count})", { count }),
2395 destructive: true,
2396 disabled: !canOperateThreads(selectedThreads),
2397 },
2398 ],
2399 position,
2400 source,
2401 ),
2402 );
2403 if (clicked._tag === "Failure" || clicked.value === null) return;
2404 const actionTargets =
2405 clicked.value === "unpin"
2406 ? pinnedSelectedThreads
2407 : clicked.value === "regenerate-title"
2408 ? regeneratableTitleThreads
2409 : clicked.value === "settle"
2410 ? settlingThreads.flatMap((thread) => {
2411 const current = threadByKeyRef.current.get(
2412 scopedThreadKey(scopeThreadRef(thread.environmentId, thread.id)),
2413 );
2414 return current && current.settledOverride !== "settled" ? [current] : [];
2415 })
2416 : selectedThreads;
2417 if (clicked.value === "settle" && actionTargets.length === 0) return;
2418 if (clicked.value !== "mark-unread" && !checkThreadOperations(actionTargets)) return;
2419 if (clicked.value?.startsWith("snooze:")) {
2420 const preset =
2421 clicked.value === "snooze:custom"
2422 ? await requestCustomSnooze()
2423 : pickSnoozePreset(
2424 snoozePresets,
2425 clicked.value.slice("snooze:".length),
2426 timestampFormat,
2427 selectedThreads[0]!.environmentId,
2428 );
2429 if (preset) {
2430 const coSnoozingKeys = new Set(threadKeys);
2431 clearSelection();
2432 const outcomes = await Promise.all(
2433 selectedThreads.map(async (thread) => {
2434 const threadRef = scopeThreadRef(thread.environmentId, thread.id);
2435 const outcome = await performSnooze(threadRef, preset, { coSnoozingKeys });
2436 return { outcome, threadRef };
2437 }),
2438 );
2439 const snoozedThreadRefs = outcomes.flatMap(({ outcome, threadRef }) =>
2440 outcome.status === "success" ? [threadRef] : [],
2441 );
2442 const failures = outcomes.flatMap(({ outcome }) =>
2443 outcome.status === "failure" ? [outcome.error] : [],
2444 );
2445
2446 if (failures.length > 0) {
2447 const firstError = failures[0];
2448 toastManager.add(
2449 stackedThreadToast({
2450 type: "error",
2451 title:
2452 snoozedThreadRefs.length > 0
2453 ? gt(
2454 "{count, plural, one {Failed to snooze {count} thread} other {Failed to snooze {count} threads}}",
2455 { count: failures.length },
2456 )
2457 : gt("Failed to snooze threads"),
2458 description: thrownErrorMessage(firstError, m) ?? gt("An error occurred."),
2459 }),
2460 );
2461 }
2462 }
2463 return;
2464 }
2465 if (clicked.value === "unpin") {
2466 for (const thread of pinnedSelectedThreads) {
2467 attemptUnpin(scopeThreadRef(thread.environmentId, thread.id));
2468 }
2469 clearSelection();
2470 return;
2471 }
2472 if (clicked.value === "regenerate-title") {
2473 clearSelection();
2474 const toast = titleRegenerationToast(
2475 await Promise.all(
2476 regeneratableTitleThreads.map((thread) =>
2477 regenerateThreadTitle({
2478 environmentId: thread.environmentId,
2479 input: { threadId: thread.id },
2480 }),
2481 ),
2482 ),
2483 );
2484 if (toast) toastManager.add(toast);
2485 return;
2486 }
2487 if (clicked.value === "settle") {
2488 settleThreads(
2489 actionTargets.map((thread) =>
2490 scopedThreadKey(scopeThreadRef(thread.environmentId, thread.id)),
2491 ),
2492 );
2493 clearSelection();
2494 return;
2495 }
2496 if (clicked.value === "mark-unread") {
2497 for (const threadKey of threadKeys) {
2498 const thread = threadByKeyRef.current.get(threadKey);
2499 if (thread) markThreadUnread(scopeThreadRef(thread.environmentId, thread.id));
2500 }
2501 clearSelection();
2502 return;
2503 }
2504 if (clicked.value !== "delete") return;
2505 if (confirmThreadDelete) {
2506 const confirmed = await settlePromise(() =>
2507 api.dialogs.confirm(
2508 [
2509 gt("{count, plural, one {Delete {count} thread?} other {Delete {count} threads?}}", {
2510 count,
2511 }),
2512 gt("This permanently clears conversation history for these threads."),
2513 ].join("\n"),
2514 { variant: "destructive" },
2515 ),
2516 );
2517 if (confirmed._tag === "Failure" || !confirmed.value) return;
2518 }
2519 if (
2520 !checkThreadOperations(
2521 threadKeys.flatMap((threadKey) => {
2522 const thread = threadByKeyRef.current.get(threadKey);
2523 return thread ? [thread] : [];
2524 }),
2525 )
2526 )
2527 return;
2528 const { deletedThreadKeys, firstFailure } = await deleteSelectedThreadEntries({
2529 entries: threadKeys.map((threadKey) => ({ threadKey })),
2530 delete: async ({ threadKey }, deletedThreadKeys) => {
2531 const thread = threadByKeyRef.current.get(threadKey);
2532 if (!thread) return null;
2533 return deleteThread(scopeThreadRef(thread.environmentId, thread.id), {
2534 deletedThreadKeys,
2535 });
2536 },
2537 });
2538 if (firstFailure !== null) {
2539 const firstError = squashAtomCommandFailure(firstFailure);
2540 toastManager.add(
2541 stackedThreadToast({
2542 type: "error",
2543 title: gt("Failed to delete threads"),
2544 description: thrownErrorMessage(firstError, m) ?? gt("An error occurred."),
2545 }),
2546 );
2547 }
2548 removeFromSelection(
2549 getThreadKeysToDeselectAfterDelete(selectedThreadKeys, deletedThreadKeys, (threadKey) => {
2550 const threadRef = parseScopedThreadKey(threadKey);
2551 return threadRef !== null && readThreadShell(threadRef) !== null;
2552 }),
2553 );
2554 },
2555 );
2556
2557 const handleDraftContextMenu = useStableCallback(
2558 (draftId: DraftId, position: { x: number; y: number }, source: ContextMenuSource) => {
2559 void (async () => {
2560 const api = readLocalApi();
2561 const session = useComposerDraftStore.getState().getDraftSession(draftId);
2562 if (!api || !session || session.promotedTo) return;
2563 const projectGroup = projectGroupsRef.current.find((group) =>
2564 group.memberProjectRefs.some(
2565 (ref) =>
2566 ref.environmentId === session.environmentId && ref.projectId === session.projectId,
2567 ),
2568 );
2569 const workspacePath =
2570 session.worktreePath ??
2571 projectByKey.get(`${session.environmentId}:${session.projectId}`)?.workspaceRoot;
2572 const clicked = await settlePromise(() =>
2573 api.contextMenu.show(
2574 buildDraftActionMenuItems({
2575 hasPath: Boolean(workspacePath),
2576 hasBranch: Boolean(session.branch),
2577 hasProject: projectGroup != null,
2578 }),
2579 position,
2580 source,
2581 ),
2582 );
2583 if (clicked._tag === "Failure") return;
2584 switch (clicked.value) {
2585 case "project-settings":
2586 if (projectGroup)
2587 openProjectSettings(projectGroup, {
2588 environmentId: session.environmentId,
2589 projectId: session.projectId,
2590 });
2591 return;
2592 case "copy-path":
2593 if (workspacePath) copyPathToClipboard(workspacePath, { path: workspacePath });
2594 return;
2595 case "copy-branch":
2596 if (session.branch) copyBranchToClipboard(session.branch, { branch: session.branch });
2597 return;
2598 case "discard": {
2599 // The menu may outlive draft promotion; discarding then would strand the send.
2600 const current = useComposerDraftStore.getState().getDraftSession(draftId);
2601 if (current && !current.promotedTo) discardComposerDraft(draftId);
2602 return;
2603 }
2604 }
2605 })();
2606 },
2607 );
2608
2609 const handleThreadContextMenu = useStableCallback(
2610 (
2611 threadRef: ScopedThreadRef,
2612 position: { x: number; y: number },
2613 source: ContextMenuSource,
2614 fromSearch = false,
2615 ) => {
2616 void (async () => {
2617 const api = readLocalApi();
2618 if (!api) return;
2619 const threadKey = scopedThreadKey(threadRef);
2620 const selectionState = useThreadSelectionStore.getState();
2621 // Search results are not selectable rows, so they always act on their own thread.
2622 if (
2623 !fromSearch &&
2624 selectionState.hasSelection() &&
2625 selectionState.selectedThreadKeys.has(threadKey)
2626 ) {
2627 await handleMultiSelectContextMenu(position, source);
2628 return;
2629 }
2630 // Search results also reach threads in collapsed shelves, which are not rendered rows.
2631 const thread =
2632 threadByKeyRef.current.get(threadKey) ??
2633 searchableThreads.find((candidate) => threadShellKey(candidate) === threadKey);
2634 if (!thread) return;
2635 const threadWorkspacePath =
2636 thread.worktreePath ??
2637 projectByKey.get(`${thread.environmentId}:${thread.projectId}`)?.workspaceRoot ??
2638 null;
2639 const configLoaded = serverConfigs.has(thread.environmentId);
2640 const supportsAutoSettleOptOut =
2641 serverConfigs.get(thread.environmentId)?.environment.capabilities
2642 .threadAutoSettleOptOut === true;
2643 const isRegeneratingTitle = thread.titleRegeneration != null;
2644 const isSettled = settledThreadKeysRef.current.has(threadKey);
2645 const isSnoozed = snoozedThreadKeysRef.current.has(threadKey);
2646 const isPinned = thread.pinnedAt != null;
2647 const snoozePresets = resolveSnoozePresets(
2648 new Date(),
2649 timestampFormat,
2650 thread.environmentId,
2651 );
2652 const threadProjectGroup =
2653 projectGroupsRef.current.find((project) =>
2654 project.memberProjectRefs.some(
2655 (projectRef) =>
2656 projectRef.environmentId === thread.environmentId &&
2657 projectRef.projectId === thread.projectId,
2658 ),
2659 ) ?? null;
2660 const clicked = await settlePromise(() =>
2661 api.contextMenu.show(
2662 buildThreadActionMenuItems({
2663 canOperate: readEnvironmentScope(
2664 threadRef.environmentId,
2665 AuthOrchestrationOperateScope,
2666 ),
2667 branch: thread.branch ?? null,
2668 // An archived project is not a filter choice.
2669 projectFilter:
2670 threadProjectGroup && !threadProjectGroup.archived
2671 ? {
2672 label: threadProjectGroup.displayName,
2673 isActive: projectScopeKeys.includes(threadProjectGroup.projectKey),
2674 }
2675 : null,
2676 isPinned,
2677 isSettled,
2678 autoSettleEnabled: thread.autoSettleDisabledAt == null,
2679 isSnoozed,
2680 canSnoozeNow: canSnooze(thread, { now: new Date().toISOString() }),
2681 isRegeneratingTitle,
2682 isRunning: !threadRuntimeCanArchive(thread.runtime),
2683 canShareWithGuest: appAtomRegistry.get(
2684 canShareWithGuestAtom(threadRef.environmentId),
2685 ),
2686 canTurnIntoProject: canTurnThreadIntoProject(threadRef),
2687 canRename: !fromSearch,
2688 supports: {
2689 settlement: configLoaded,
2690 autoSettleOptOut: supportsAutoSettleOptOut,
2691 snooze: configLoaded,
2692 pinning: configLoaded,
2693 titleRegeneration: configLoaded,
2694 },
2695 snoozePresets,
2696 }),
2697 position,
2698 source,
2699 ),
2700 );
2701 if (clicked._tag === "Failure" || clicked.value === null) return;
2702 if (threadActionRequiresOperate(clicked.value) && !checkThreadOperations([thread])) return;
2703 if (clicked.value?.startsWith("snooze:")) {
2704 const preset =
2705 clicked.value === "snooze:custom"
2706 ? await requestCustomSnooze()
2707 : pickSnoozePreset(
2708 snoozePresets,
2709 clicked.value.slice("snooze:".length),
2710 timestampFormat,
2711 thread.environmentId,
2712 );
2713 if (preset) attemptSnooze(threadRef, preset);
2714 return;
2715 }
2716 switch (clicked.value) {
2717 case "filter-by-project":
2718 if (threadProjectGroup) {
2719 setProjectScopeKeys(
2720 projectScopeKeys.includes(threadProjectGroup.projectKey)
2721 ? []
2722 : [threadProjectGroup.projectKey],
2723 );
2724 }
2725 return;
2726 case "project-settings":
2727 if (threadProjectGroup)
2728 openProjectSettings(threadProjectGroup, {
2729 environmentId: threadRef.environmentId,
2730 projectId: thread.projectId,
2731 });
2732 return;
2733 case "new-thread-on-branch": {
2734 const result = await settlePromise(() =>
2735 handleNewThread(scopeProjectRef(thread.environmentId, thread.projectId), {
2736 branch: thread.branch,
2737 worktreePath: thread.worktreePath,
2738 envMode: thread.worktreePath ? "worktree" : "local",
2739 startFromOrigin: false,
2740 }),
2741 );
2742 if (result._tag === "Failure") {
2743 const error = squashAtomCommandFailure(result);
2744 toastManager.add(
2745 stackedThreadToast({
2746 type: "error",
2747 title: gt("Could not create thread"),
2748 description: thrownErrorMessage(error, m) ?? gt("An error occurred."),
2749 }),
2750 );
2751 }
2752 return;
2753 }
2754 case "settle":
2755 attemptSettle(threadRef);
2756 return;
2757 case "unsettle":
2758 attemptUnsettle(threadRef);
2759 return;
2760 case "unsnooze":
2761 attemptUnsnooze(threadRef);
2762 return;
2763 case "pin":
2764 attemptPin(threadRef);
2765 return;
2766 case "unpin":
2767 attemptUnpin(threadRef);
2768 return;
2769 case "turn-into-project": {
2770 const result = await turnThreadIntoProject(threadRef);
2771 if (result._tag === "Success") {
2772 toastManager.add({
2773 type: "success",
2774 title: gt("Project created"),
2775 description: thread.title,
2776 });
2777 } else if (!isAtomCommandInterrupted(result)) {
2778 const error = squashAtomCommandFailure(result);
2779 toastManager.add(
2780 stackedThreadToast({
2781 type: "error",
2782 title: gt("Could not turn thread into a project"),
2783 description: thrownErrorMessage(error, m) ?? gt("An error occurred."),
2784 }),
2785 );
2786 }
2787 return;
2788 }
2789 case "auto-settle:enabled":
2790 case "auto-settle:disabled": {
2791 const result = await setThreadAutoSettle(
2792 threadRef,
2793 clicked.value === "auto-settle:enabled",
2794 );
2795 if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) {
2796 const error = squashAtomCommandFailure(result);
2797 toastManager.add(
2798 stackedThreadToast({
2799 type: "error",
2800 title: gt("Failed to update auto-settle"),
2801 description: thrownErrorMessage(error, m) ?? gt("An error occurred."),
2802 }),
2803 );
2804 }
2805 return;
2806 }
2807 case "rename":
2808 startThreadRename(threadRef, thread.title);
2809 return;
2810 case "share-guest":
2811 openGuestShareDialog(threadRef);
2812 return;
2813 case "regenerate-title": {
2814 if (isRegeneratingTitle) return;
2815 const toast = titleRegenerationToast([
2816 await regenerateThreadTitle({
2817 environmentId: threadRef.environmentId,
2818 input: { threadId: threadRef.threadId },
2819 }),
2820 ]);
2821 if (toast) toastManager.add(toast);
2822 return;
2823 }
2824 case "mark-unread":
2825 markThreadUnread(threadRef);
2826 return;
2827 case "copy-path":
2828 if (!threadWorkspacePath) {
2829 toastManager.add(
2830 stackedThreadToast({
2831 type: "error",
2832 title: gt("Path unavailable"),
2833 description: gt("This thread does not have a workspace path to copy."),
2834 }),
2835 );
2836 return;
2837 }
2838 copyPathToClipboard(threadWorkspacePath, { path: threadWorkspacePath });
2839 return;
2840 case "copy-branch":
2841 if (thread.branch) {
2842 copyBranchToClipboard(thread.branch, { branch: thread.branch });
2843 }
2844 return;
2845 case "copy-thread":
2846 void copyThreadReference(
2847 threadChipCopyTarget(threadRef, thread.title, configuredHostedAppUrl(), m),
2848 );
2849 return;
2850 case "copy-thread-id":
2851 copyThreadIdToClipboard(thread.id, { threadId: thread.id });
2852 return;
2853 case "archive": {
2854 if (confirmThreadArchive) {
2855 const confirmed = await settlePromise(() =>
2856 api.dialogs.confirm(gt('Archive thread "{title}"?', { title: thread.title })),
2857 );
2858 if (confirmed._tag === "Failure" || !confirmed.value) return;
2859 }
2860 let didArchive = false;
2861 const result = await archiveThread(threadRef, {
2862 onArchived: () => {
2863 didArchive = true;
2864 },
2865 });
2866 if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) {
2867 const error = squashAtomCommandFailure(result);
2868 toastManager.add(
2869 stackedThreadToast({
2870 type: "error",
2871 title: didArchive
2872 ? gt("Thread archived, but navigation failed")
2873 : gt("Failed to archive thread"),
2874 description: thrownErrorMessage(error, m) ?? gt("An error occurred."),
2875 }),
2876 );
2877 return;
2878 }
2879 return;
2880 }
2881 case "delete": {
2882 if (confirmThreadDelete) {
2883 const confirmed = await settlePromise(() =>
2884 api.dialogs.confirm(
2885 [
2886 gt('Delete thread "{title}"?', { title: thread.title }),
2887 gt("This permanently clears conversation history for this thread."),
2888 ].join("\n"),
2889 { variant: "destructive" },
2890 ),
2891 );
2892 if (confirmed._tag === "Failure" || !confirmed.value) return;
2893 }
2894 const result = await deleteThread(threadRef);
2895 if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) {
2896 const error = squashAtomCommandFailure(result);
2897 toastManager.add(
2898 stackedThreadToast({
2899 type: "error",
2900 title: gt("Failed to delete thread"),
2901 description: thrownErrorMessage(error, m) ?? gt("An error occurred."),
2902 }),
2903 );
2904 return;
2905 }
2906 return;
2907 }
2908 default:
2909 return;
2910 }
2911 })();
2912 },
2913 );
2914 const handleSearchResultContextMenu = useStableCallback(
2915 (threadRef: ScopedThreadRef, position: { x: number; y: number }, source: ContextMenuSource) =>
2916 handleThreadContextMenu(threadRef, position, source, true),
2917 );
2918
2919 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- subscribes to window keydown for thread navigation shortcuts using the current thread list
2920 useEffect(() => {
2921 const onWindowKeyDown = (event: KeyboardEvent) => {
2922 if (event.defaultPrevented || event.repeat || isCommandPaletteOpen() || isModelPickerOpen()) {
2923 return;
2924 }
2925 const command = resolveShortcutCommand(event, keybindings, {
2926 platform: navigator.platform,
2927 context: threadShortcutContext(routeThreadRef),
2928 });
2929 const navigateToThreadKey = (targetThreadKey: string | null) => {
2930 if (!targetThreadKey) return false;
2931 const targetThread = threadByKey.get(targetThreadKey);
2932 if (!targetThread) return false;
2933 event.preventDefault();
2934 event.stopPropagation();
2935 navigateToThread(scopeThreadRef(targetThread.environmentId, targetThread.id));
2936 return true;
2937 };
2938 const traversalDirection = threadTraversalDirectionFromCommand(command);
2939 if (traversalDirection !== null) {
2940 navigateToThreadKey(
2941 resolveAdjacentThreadId({
2942 threadIds: orderedThreadKeys,
2943 currentThreadId: routeRowThreadKey,
2944 direction: traversalDirection,
2945 }),
2946 );
2947 return;
2948 }
2949 const jumpIndex = threadJumpIndexFromCommand(command ?? "");
2950 if (jumpIndex === null) return;
2951 navigateToThreadKey(orderedThreadKeys[jumpIndex] ?? null);
2952 };
2953 window.addEventListener("keydown", onWindowKeyDown);
2954 return () => window.removeEventListener("keydown", onWindowKeyDown);
2955 }, [
2956 keybindings,
2957 navigateToThread,
2958 orderedThreadKeys,
2959 routeRowThreadKey,
2960 routeThreadRef,
2961 threadByKey,
2962 ]);
2963
2964 const showJumpHints = useThreadJumpHintsVisible(keybindings, routeThreadRef);
2965
2966 const handleNewThreadClick = (event?: ReactMouseEvent) => {
2967 if (
2968 shouldCreateNewThreadInCurrentProject(
2969 event?.shiftKey ?? false,
2970 scopeGroups.length,
2971 projectGroups.length,
2972 )
2973 ) {
2974 if (isMobile) setOpenMobile(false);
2975 // With no current or open project, such as when every project is archived, pick one.
2976 void startNewThreadFromContext({
2977 activeDraftThread: newThreadContext.activeDraftThread,
2978 activeThread: newThreadContext.activeThread ?? undefined,
2979 defaultProjectRef: newThreadContext.defaultProjectRef,
2980 handleNewThread,
2981 }).then((started) => {
2982 if (!started) openCommandPalette({ open: "new-thread-in" });
2983 });
2984 return;
2985 }
2986 if (isMobile) setOpenMobile(false);
2987 openCommandPalette({ open: "new-thread-in" });
2988 };
2989
2990 const newThreadShortcutLabel =
2991 shortcutLabelForCommand(keybindings, "chat.new") ??
2992 (shouldCreateNewThreadInCurrentProject(false, scopeGroups.length, projectGroups.length)
2993 ? shortcutLabelForCommand(keybindings, "chat.newLocal")
2994 : undefined);
2995 const newThreadInProjectShortcutLabel = shortcutLabelForCommand(keybindings, "chat.newLocal");
2996 return (
2997 <SidebarFolderDrop>
2998 <SidebarChromeHeader isElectron={isElectron} />
2999 <SidebarContent
3000 ref={sidebarContentRef}
3001 className="min-h-full"
3002 fixedHeader={
3003 <SidebarGroup className="z-[1]">
3004 <SidebarThreadHeader
3005 hasProjects={projectGroups.length > 0}
3006 projectScope={
3007 <Combobox
3008 items={projectScopeItems}
3009 filteredItems={filteredProjectScopeItems}
3010 autoHighlight
3011 itemToStringLabel={(item) => item.label}
3012 isItemEqualToValue={(a, b) => a.value === b.value}
3013 open={projectScopeMenuState.open}
3014 onOpenChange={(open, eventDetails) => {
3015 if (eventDetails.isCanceled) return;
3016 if (open) suppressNextScopeChangeRef.current = false;
3017 dispatchProjectScopeMenu({ type: "open-changed", open });
3018 }}
3019 onItemHighlighted={(item) => {
3020 highlightedProjectScopeKeyRef.current = item?.value ?? null;
3021 }}
3022 value={selectedProjectScopeItem}
3023 onValueChange={(item, eventDetails) => {
3024 if (suppressNextScopeChangeRef.current) {
3025 suppressNextScopeChangeRef.current = false;
3026 return;
3027 }
3028 if (!item) return;
3029 if (item.value === "all") {
3030 setProjectScopeKeys([]);
3031 } else if (
3032 eventDetails.event instanceof MouseEvent &&
3033 eventDetails.event.shiftKey
3034 ) {
3035 // Canceling skips Base UI's commit, which would freeze the search query, and its close.
3036 eventDetails.cancel();
3037 toggleProjectScopeKey(item.value);
3038 } else {
3039 setProjectScopeKeys([item.value]);
3040 }
3041 }}
3042 >
3043 <ComboboxTrigger
3044 render={
3045 <SidebarHeaderIconButton
3046 label={
3047 scopedProjectGroups.length > 0
3048 ? gt("Filter threads by project: {projects}", {
3049 projects: scopedProjectGroups
3050 .map((project) => project.displayName)
3051 .join(", "),
3052 })
3053 : gt("Filter threads by project")
3054 }
3055 />
3056 }
3057 >
3058 {scopedProjectGroups.length > 1 ? (
3059 <span className="flex shrink-0">
3060 {scopedProjectGroups.slice(0, 2).map((project, index) => (
3061 <span
3062 key={project.projectKey}
3063 className={
3064 index === 0
3065 ? "flex"
3066 : "-ml-1 flex rounded-[25%] bg-sidebar ring-2 ring-sidebar"
3067 }
3068 >
3069 <ProjectFavicon project={project} className="size-3.5" />
3070 </span>
3071 ))}
3072 </span>
3073 ) : scopedProjectGroups[0] ? (
3074 <span className="flex shrink-0">
3075 <ProjectFavicon project={scopedProjectGroups[0]} className="size-4" />
3076 </span>
3077 ) : (
3078 <ListFilterIcon className="size-4" />
3079 )}
3080 </ComboboxTrigger>
3081 {/* Refocusing the trigger after a pointer close shows its focus ring and opens its tooltip. */}
3082 <ComboboxPopup
3083 align="start"
3084 collisionAvoidance={{ side: "flip", align: "shift" }}
3085 className="w-[min(18rem,var(--available-width))] overflow-hidden"
3086 finalFocus={(closeType) => closeType === "keyboard"}
3087 >
3088 <ComboboxSearchInput
3089 aria-label={gt("Search projects")}
3090 placeholder={gt("Search projects...")}
3091 value={projectScopeMenuState.query}
3092 onKeyDown={(event) => {
3093 if (
3094 event.defaultPrevented ||
3095 event.nativeEvent.isComposing ||
3096 event.keyCode === 229
3097 ) {
3098 return;
3099 }
3100 const scopeKey = highlightedProjectScopeKeyRef.current;
3101 const project = scopeKey ? projectGroupByScopeKey.get(scopeKey) : null;
3102 // The thread pin shortcut pins the highlighted project here.
3103 if (
3104 project &&
3105 canPinProject(project) &&
3106 isProjectPinShortcut(event, keybindings)
3107 ) {
3108 event.preventDefault();
3109 event.stopPropagation();
3110 toggleProjectGroupPin(project);
3111 return;
3112 }
3113 if (event.ctrlKey || event.altKey || event.metaKey) return;
3114 if (event.shiftKey && event.key === "Enter") {
3115 if (!project) return;
3116 event.preventDefault();
3117 toggleProjectScopeKey(project.projectKey);
3118 return;
3119 }
3120 if (
3121 event.key !== "ContextMenu" &&
3122 !(event.shiftKey && event.key === "F10")
3123 ) {
3124 return;
3125 }
3126 if (project) handleProjectSettings(event, project);
3127 }}
3128 onChange={(event) =>
3129 dispatchProjectScopeMenu({
3130 type: "query-changed",
3131 query: event.target.value,
3132 })
3133 }
3134 />
3135 <ComboboxEmpty>
3136 <T>No matching projects.</T>
3137 </ComboboxEmpty>
3138 <ComboboxList aria-multiselectable>
3139 {(item: (typeof projectScopeItems)[number]) => {
3140 const project = projectGroupByScopeKey.get(item.value) ?? null;
3141 const isSelected = project
3142 ? projectScopeKeys.includes(item.value)
3143 : projectScopeKeys.length === 0;
3144 return (
3145 <ComboboxItem
3146 key={item.value}
3147 hideIndicator
3148 value={item}
3149 aria-selected={isSelected}
3150 // The icon badge marks selection; Base UI's single value would shade one row.
3151 data-selected={undefined}
3152 onContextMenu={(event) => {
3153 if (project) handleProjectSettings(event, project);
3154 }}
3155 >
3156 <ProjectScopeRowIcon isSelected={isSelected}>
3157 {project ? (
3158 <ProjectFavicon project={project} className="size-4 shrink-0" />
3159 ) : (
3160 <FolderIcon className="size-4 shrink-0" />
3161 )}
3162 </ProjectScopeRowIcon>
3163 <span className="min-w-0 truncate text-sm">{item.label}</span>
3164 {project && showProjectEnvironments ? (
3165 <ProjectEnvironmentBadge
3166 group={project}
3167 primaryEnvironmentId={primaryEnvironmentId}
3168 machineByEnvironmentId={environmentMachineById}
3169 />
3170 ) : null}
3171 {project ? (
3172 <ProjectRowActions
3173 pin={
3174 canPinProject(project) ? (
3175 <ProjectPinButton
3176 name={project.displayName}
3177 pinned={project.pinned}
3178 shortcutLabel={shortcutLabelForCommand(
3179 keybindings,
3180 "thread.pin",
3181 )}
3182 onToggle={() => toggleProjectGroupPin(project)}
3183 />
3184 ) : null
3185 }
3186 settings={
3187 <Button
3188 size="icon-xs"
3189 variant="ghost-muted"
3190 tabIndex={-1}
3191 aria-hidden="true"
3192 title={gt("Project settings for {project}", {
3193 project: project.displayName,
3194 })}
3195 onPointerDown={(event) => event.stopPropagation()}
3196 onClick={(event) => {
3197 void handleProjectSettings(event, project);
3198 }}
3199 >
3200 <SettingsIcon className="size-3.5" />
3201 </Button>
3202 }
3203 />
3204 ) : (
3205 // Keeps "All projects" as tall as the project rows.
3206 <span className="ml-auto size-7 shrink-0 sm:size-6" />
3207 )}
3208 </ComboboxItem>
3209 );
3210 }}
3211 </ComboboxList>
3212 </ComboboxPopup>
3213 </Combobox>
3214 }
3215 onNewProject={openAddProjectCommandPalette}
3216 onNewThread={handleNewThreadClick}
3217 newThreadDisabled={projects.length === 0}
3218 newThreadShortcutLabel={newThreadShortcutLabel}
3219 newThreadInProjectShortcutLabel={newThreadInProjectShortcutLabel}
3220 showNewThreadInProjectHint={
3221 !shouldCreateNewThreadInCurrentProject(
3222 false,
3223 scopeGroups.length,
3224 projectGroups.length,
3225 )
3226 }
3227 searchInputRef={threadSearchInputRef}
3228 searchQuery={threadSearchQuery}
3229 onSearchQueryChange={(value) => {
3230 setThreadSearchQuery(value);
3231 setSearchHighlightKey(null);
3232 }}
3233 onSearchKeyDown={handleThreadSearchKeyDown}
3234 isSearching={isSearchingThreads}
3235 searchResultCount={threadSearchResults.length}
3236 activeSearchResultIndex={activeSearchResultIndex}
3237 onClearSearch={clearThreadSearch}
3238 />
3239 </SidebarGroup>
3240 }
3241 >
3242 <SidebarGroup className="flex-1" role="presentation">
3243 {isSearchingThreads ? (
3244 threadSearchResults.length > 0 ? (
3245 <TooltipProvider
3246 key="sidebar-thread-search-tooltips-150"
3247 delay={150}
3248 closeDelay={0}
3249 timeout={400}
3250 >
3251 <DndContext
3252 sensors={dndSensors}
3253 autoScroll={false}
3254 onDragStart={(event) => {
3255 contextDragKeyRef.current = String(event.active.id);
3256 }}
3257 >
3258 <ul
3259 ref={searchResultsListRef}
3260 id="sidebar-thread-search-results"
3261 role="listbox"
3262 aria-label={gt("Thread search results")}
3263 className="flex flex-col gap-px"
3264 >
3265 {threadSearchResults.map((thread, index) => {
3266 const threadKey = scopedThreadKey(
3267 scopeThreadRef(thread.environmentId, thread.id),
3268 );
3269 return (
3270 <SidebarSearchResultRow
3271 isSettled={settledThreadKeys.has(threadKey)}
3272 key={threadKey}
3273 thread={thread}
3274 project={
3275 projectByKey.get(`${thread.environmentId}:${thread.projectId}`) ?? null
3276 }
3277 projectDisplayName={
3278 projectDisplayNameByKey.get(
3279 `${thread.environmentId}:${thread.projectId}`,
3280 ) ?? null
3281 }
3282 environmentLabel={environmentLabelById.get(thread.environmentId) ?? null}
3283 environmentMachine={
3284 environmentMachineById.get(thread.environmentId) ?? "server"
3285 }
3286 providerEntryByInstanceId={
3287 providerEntriesByEnvironment.get(thread.environmentId) ??
3288 EMPTY_PROVIDER_ENTRIES
3289 }
3290 isHighlighted={activeSearchResultIndex === index}
3291 isRouteActive={routeRowThreadKey === threadKey}
3292 resultId={threadSearchResultId(index)}
3293 searchMatch={
3294 threadSearchMatchByKey.get(
3295 threadSearchMatchKey({
3296 environmentId: thread.environmentId,
3297 threadId: thread.id,
3298 }),
3299 ) ?? null
3300 }
3301 searchQuery={threadSearchQuery}
3302 searchMatchQuery={threadSearch.query}
3303 onHighlight={() => setActiveSearchResultIndex(index)}
3304 onSelect={() => selectThreadSearchResult(thread)}
3305 onContextMenu={handleSearchResultContextMenu}
3306 onFileDropThreads={handleThreadFileDrop}
3307 />
3308 );
3309 })}
3310 </ul>
3311 </DndContext>
3312 </TooltipProvider>
3313 ) : (
3314 <p
3315 role="status"
3316 className="px-2 py-6 text-center text-xs text-sidebar-muted-foreground"
3317 >
3318 {threadSearch.isPending
3319 ? gt("Searching thread messages…")
3320 : threadSearch.failed
3321 ? gt("Couldn't search thread messages")
3322 : gt("No threads found")}
3323 </p>
3324 )
3325 ) : null}
3326 {/* A scope can hide every active thread; say so even when its project still has settled ones. */}
3327 {!isSearchingThreads &&
3328 !hasProjectFolders &&
3329 visibleDraftSessionCount === 0 &&
3330 pinnedThreads.length +
3331 activeThreads.length +
3332 workingThreads.length +
3333 snoozedThreads.length ===
3334 0 &&
3335 (settledCount === 0 || scopedProjectGroups.length > 0) ? (
3336 <div className="flex flex-col items-center gap-2 px-2 py-6 text-center text-xs text-muted-foreground/60">
3337 {projects.length === 0 ? (
3338 <>
3339 <span>
3340 <T>No projects yet</T>
3341 </span>
3342 <button
3343 type="button"
3344 onClick={openAddProjectCommandPalette}
3345 className="inline-flex cursor-pointer items-center gap-1.5 rounded-md border border-sidebar-border px-2.5 py-1 text-2xs font-medium text-sidebar-muted-foreground transition-colors hover:bg-sidebar-row-hover hover:text-sidebar-foreground"
3346 >
3347 <PlusIcon className="-mx-0.5 size-3" />
3348 <T>Add project</T>
3349 </button>
3350 </>
3351 ) : scopedProjectGroups.length > 0 ? (
3352 <>
3353 <span>
3354 {settledCount > 0
3355 ? scopedProjectGroups.length > 1
3356 ? gt("No active threads in these projects")
3357 : gt("No active threads in {project}", {
3358 project: scopedProjectGroups[0]!.displayName,
3359 })
3360 : scopedProjectGroups.length > 1
3361 ? gt("No threads in these projects yet")
3362 : gt("No threads in {project} yet", {
3363 project: scopedProjectGroups[0]!.displayName,
3364 })}
3365 </span>
3366 <button
3367 type="button"
3368 onClick={() => setProjectScopeKeys([])}
3369 className="inline-flex cursor-pointer items-center gap-1.5 rounded-md border border-sidebar-border px-2.5 py-1 text-2xs font-medium text-sidebar-muted-foreground transition-colors hover:bg-sidebar-row-hover hover:text-sidebar-foreground"
3370 >
3371 <T>Show all projects</T>
3372 </button>
3373 </>
3374 ) : (
3375 <T>No threads yet</T>
3376 )}
3377 </div>
3378 ) : null}
3379 {!isSearchingThreads ? (
3380 <TooltipProvider
3381 key="sidebar-thread-tooltips-150"
3382 delay={150}
3383 closeDelay={0}
3384 timeout={400}
3385 >
3386 <DndContext
3387 sensors={dndSensors}
3388 autoScroll={isContextDrag ? false : SIDEBAR_AUTO_SCROLL}
3389 collisionDetection={dndCollisionDetection}
3390 modifiers={dndModifiers}
3391 onDragStart={handleThreadDragStart}
3392 onDragOver={handleThreadDragOver}
3393 onDragEnd={handleThreadDragEnd}
3394 >
3395 <SortableContext items={sortableIds} strategy={sidebarSortingStrategy}>
3396 <ul
3397 ref={attachTreeRef}
3398 // Presentation flattens VoiceOver's list interaction boundary while preserving descendant
3399 // controls.
3400 role="presentation"
3401 className={cn(
3402 "relative flex flex-col gap-px",
3403 sidebarListItems.length > 0 && "flex-1",
3404 actionSweep !== null && "**:pointer-events-none",
3405 // Projected rows (two boundary labels, two hints) extend the scroll range; a range that
3406 // shrinks as the target changes clamps scrollTop and flips the target under a still pointer.
3407 dragState !== null &&
3408 "after:pointer-events-none after:absolute after:inset-x-0 after:-bottom-30 after:h-px after:content-['']",
3409 )}
3410 >
3411 {(() => {
3412 const renderThreadRow = (
3413 thread: EnvironmentThreadShell,
3414 section: SidebarSection,
3415 // The tree row of the project folder this row sits in.
3416 folderRow?: string,
3417 ) => {
3418 const threadKey = scopedThreadKey(
3419 scopeThreadRef(thread.environmentId, thread.id),
3420 );
3421 const isCard =
3422 section === "active" || section === "pinned" || section === "working";
3423 const rowVariant = folderRow
3424 ? folderRowsMultiline
3425 ? "folder-multiline"
3426 : "folder"
3427 : isCard
3428 ? "card"
3429 : "slim";
3430 return (
3431 <SortableThreadRow
3432 key={threadKey}
3433 sortableId={threadKey}
3434 contextDrag={isContextDrag}
3435 sortableDisabled={
3436 renamingThreadKey === threadKey ||
3437 !draggableThreadKeys.has(threadKey) ||
3438 optimisticDrop !== null
3439 }
3440 thread={thread}
3441 variant={rowVariant}
3442 navigationParent={
3443 folderRow ??
3444 (section === "working" ||
3445 section === "snoozed" ||
3446 section === "settled"
3447 ? `shelf:${section}`
3448 : undefined)
3449 }
3450 variantAction={
3451 section === "snoozed"
3452 ? "unsnooze"
3453 : section === "settled"
3454 ? "unsettle"
3455 : "settle"
3456 }
3457 settlementSupported={serverConfigs.has(thread.environmentId)}
3458 snoozeSupported={serverConfigs.has(thread.environmentId)}
3459 pinningSupported={serverConfigs.has(thread.environmentId)}
3460 isPinned={thread.pinnedAt != null}
3461 dropVerb={
3462 dragState?.activeKey === threadKey
3463 ? resolveSidebarDropVerb(dragState.activeSection, dragTargetSection)
3464 : null
3465 }
3466 dragOverPinned={
3467 dragState?.activeKey === threadKey && dragTargetSection === "pinned"
3468 }
3469 sweepAction={
3470 actionSweep?.keys.has(threadKey) ? actionSweep.action : null
3471 }
3472 snoozeWakeLabelText={
3473 section === "snoozed" && thread.snoozedUntil != null
3474 ? snoozeWakeLabel(
3475 thread.snoozedUntil,
3476 { now: new Date().toISOString() },
3477 messages,
3478 )
3479 : null
3480 }
3481 wokeAt={threadWokeAt(thread, { now: snoozeNow })}
3482 isActive={routeRowThreadKey === threadKey}
3483 revealRef={
3484 routeRowThreadKey === threadKey ? revealActiveRow : undefined
3485 }
3486 isRouteThread={routeThreadKey === threadKey}
3487 readOpensPullRequestsInRightPanel={readOpensPullRequestsInRightPanel}
3488 jumpLabel={
3489 showJumpHints ? (jumpLabelByKey.get(threadKey) ?? null) : null
3490 }
3491 currentEnvironmentId={primaryEnvironmentId}
3492 environmentLabel={
3493 environmentLabelById.get(thread.environmentId) ?? null
3494 }
3495 environmentMachine={
3496 environmentMachineById.get(thread.environmentId) ?? "server"
3497 }
3498 scratchMachineLabel={scratchMachineLabelFor(thread)}
3499 project={
3500 projectByKey.get(`${thread.environmentId}:${thread.projectId}`) ??
3501 null
3502 }
3503 projectDisplayName={
3504 projectDisplayNameByKey.get(
3505 `${thread.environmentId}:${thread.projectId}`,
3506 ) ?? null
3507 }
3508 providerEntryByInstanceId={
3509 providerEntriesByEnvironment.get(thread.environmentId) ??
3510 EMPTY_PROVIDER_ENTRIES
3511 }
3512 timestampFormat={timestampFormat}
3513 onThreadClick={handleThreadClick}
3514 onThreadActivate={navigateToThread}
3515 onStartRename={startThreadRename}
3516 onRenameTitleChange={setRenamingTitle}
3517 onCommitRename={commitThreadRename}
3518 onCancelRename={cancelThreadRename}
3519 isRenaming={renamingThreadKey === threadKey}
3520 renamingTitle={renamingThreadKey === threadKey ? renamingTitle : ""}
3521 onContextMenu={handleThreadContextMenu}
3522 onSettle={attemptSettle}
3523 onActionSweepStart={startActionSweep}
3524 onUnsettle={attemptUnsettle}
3525 onSnooze={attemptSnooze}
3526 onUnsnooze={attemptUnsnooze}
3527 onUnpin={attemptUnpin}
3528 onAcknowledgeWoke={acknowledgeWoke}
3529 onFileDropThreads={handleThreadFileDrop}
3530 />
3531 );
3532 };
3533 const from = isContextDrag ? null : (dragState?.activeSection ?? null);
3534 const items: ReactNode[] = [
3535 <SidebarDraftBlock
3536 key="draft-sessions"
3537 projectByKey={projectByKey}
3538 projectDisplayNameByKey={projectDisplayNameByKey}
3539 scopedProjectKeys={scopedProjectKeys}
3540 routeDraftId={routeDraftIdForRows}
3541 onNavigateToDraft={navigateToDraft}
3542 onDraftContextMenu={handleDraftContextMenu}
3543 />,
3544 ];
3545 for (const item of sidebarListItems) {
3546 if (item.kind === "thread") {
3547 // Folders draw active rows in their own place below.
3548 if (projectFolders !== null && item.section === "active") continue;
3549 items.push(renderThreadRow(threadByKey.get(item.key)!, item.section));
3550 continue;
3551 }
3552 if (projectFolders !== null && item.marker === "active-placeholder") {
3553 for (const folder of projectFolders) {
3554 items.push(
3555 <SidebarProjectFolderHeader
3556 key={`project-folder:${folder.group.projectKey}`}
3557 group={folder.group}
3558 collapsed={folder.collapsed}
3559 hiddenThreads={folder.hiddenThreads}
3560 onToggle={toggleProjectFolder}
3561 onNewThread={startThreadInProjectFolder}
3562 onContextMenu={handleProjectFolderContextMenu}
3563 />,
3564 );
3565 for (const thread of folder.threads) {
3566 items.push(
3567 renderThreadRow(
3568 thread,
3569 "active",
3570 sidebarFolderRowId(folder.group.projectKey),
3571 ),
3572 );
3573 }
3574 }
3575 continue;
3576 }
3577 switch (item.marker) {
3578 case "pinned-header":
3579 items.push(
3580 <SidebarDragBoundary
3581 key="pinned-header"
3582 marker="pinned-header"
3583 label={gt("Pinned", { $context: "sidebar section" })}
3584 visible={from !== null}
3585 isDropTarget={dragTargetSection === "pinned"}
3586 />,
3587 );
3588 break;
3589 case "pinned-divider":
3590 items.push(
3591 <SidebarDragBoundary
3592 key="pinned-divider"
3593 marker="pinned-divider"
3594 label={gt("Active", { $context: "sidebar section" })}
3595 visible={from !== null}
3596 isDropTarget={dragTargetSection === "active"}
3597 />,
3598 );
3599 break;
3600 case "active-placeholder":
3601 items.push(
3602 <SidebarSectionPlaceholder
3603 key="active-placeholder"
3604 marker="active-placeholder"
3605 label={gt("Active", { $context: "sidebar section" })}
3606 showHint={
3607 from !== null &&
3608 (activeThreads.length === 0 ||
3609 (from === "active" &&
3610 activeThreads.length === 1 &&
3611 dragTargetSection !== null &&
3612 dragTargetSection !== "active"))
3613 }
3614 isDropTarget={dragTargetSection === "active"}
3615 />,
3616 );
3617 break;
3618 case "working-header":
3619 items.push(
3620 <SidebarSectionHeader
3621 key="working-shelf-header"
3622 marker="working-header"
3623 className="mt-auto"
3624 label={gt("Working", { $context: "sidebar section" })}
3625 count={workingThreads.length}
3626 toggle={{
3627 expanded: workingShelfExpanded,
3628 onToggle: toggleWorkingShelf,
3629 }}
3630 />,
3631 );
3632 break;
3633 case "snoozed-header":
3634 items.push(
3635 <SidebarSectionHeader
3636 key="snoozed-shelf-header"
3637 marker="snoozed-header"
3638 className={cn(workingThreads.length === 0 && "mt-auto")}
3639 label={gt("Snoozed", { $context: "sidebar section" })}
3640 count={snoozedThreads.length}
3641 toggle={{
3642 expanded: snoozedShelfExpanded,
3643 onToggle: toggleSnoozedShelf,
3644 }}
3645 />,
3646 );
3647 break;
3648 case "settled-header":
3649 items.push(
3650 <SidebarSectionHeader
3651 key="settled-shelf-header"
3652 marker="settled-header"
3653 className={cn(
3654 workingThreads.length + snoozedThreads.length === 0 && "mt-auto",
3655 )}
3656 label={gt("Settled", { $context: "sidebar section" })}
3657 count={settledCount}
3658 dragging={from !== null}
3659 isDropTarget={dragTargetSection === "settled"}
3660 toggle={{
3661 expanded: settledShelfExpanded,
3662 onToggle: toggleSettledShelf,
3663 }}
3664 />,
3665 );
3666 break;
3667 case "settled-placeholder":
3668 items.push(
3669 <SidebarSectionPlaceholder
3670 key="settled-placeholder"
3671 marker="settled-placeholder"
3672 label={gt("Settled", { $context: "sidebar section" })}
3673 showHint={
3674 from !== null &&
3675 (renderedSettledThreads.length === 0 ||
3676 (from === "settled" &&
3677 renderedSettledThreads.length === 1 &&
3678 dragTargetSection !== null &&
3679 dragTargetSection !== "settled"))
3680 }
3681 isDropTarget={dragTargetSection === "settled"}
3682 />,
3683 );
3684 break;
3685 }
3686 }
3687 return items;
3688 })()}
3689 {settledShelfExpanded && hiddenSettledCount > 0 ? (
3690 <li className="list-none">
3691 <button
3692 type="button"
3693 data-sidebar-row="settled:more"
3694 data-sidebar-parent="shelf:settled"
3695 aria-disabled={olderSettledShelf.loading}
3696 onClick={() => {
3697 if (olderSettledShelf.loading) return;
3698 olderSettledShelf.retry();
3699 showMoreSettled();
3700 }}
3701 className="flex h-9 w-full cursor-pointer items-center gap-2.5 rounded-md px-2.5 text-left text-sm text-sidebar-muted-foreground hover:bg-sidebar-row-hover hover:text-sidebar-foreground aria-disabled:cursor-default"
3702 >
3703 {/* Plus means "add", so revealing more uses a chevron. */}
3704 <ChevronDownIcon aria-hidden className="size-4 shrink-0" />
3705 {olderSettledShelf.loading
3706 ? gt("Loading")
3707 : olderSettledShelf.failed
3708 ? gt("Could not load older threads. Retry")
3709 : gt(
3710 "{count, plural, one {Show {count} more} other {Show {count} more}}",
3711 {
3712 count: Math.min(hiddenSettledCount, SETTLED_TAIL_PAGE_COUNT),
3713 },
3714 )}
3715 </button>
3716 </li>
3717 ) : null}
3718 </ul>
3719 </SortableContext>
3720 </DndContext>
3721 </TooltipProvider>
3722 ) : null}
3723 </SidebarGroup>
3724 </SidebarContent>
3725 <SidebarChromeFooter />
3726 </SidebarFolderDrop>
3727 );
3728 }