@devries-cameron20 / t3code Mirror · read-only / commits / 23163fdc48
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 23, 08:00 UTC

perf(web): the legacy sidebar compiles with the React Compiler (#20640)

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>

Julius Marminge committed Oct 16, 2026 at 21:05 UTC 23163fdc48871b6b297371e408e239dc02199c91
2 files changed +1331 -1507
apps/web/reactCompiledFiles.ts
+1
@@ -97,4 +97,5 @@ export const REACT_COMPILED_FILES = [
97 "apps/web/src/components/ThreadTerminalDrawer.tsx",
98 "apps/web/src/components/settings/SettingsPanels.tsx",
99 "apps/web/src/routes/_chat.pull-requests.tsx",
100 + "apps/web/src/components/LegacySidebar.tsx",
101 ] as const;
apps/web/src/components/LegacySidebar.tsx
+1330 -1507
@@ -24,7 +24,7 @@ import { EnvironmentMachineIcon } from "./EnvironmentMachineIcon";
24 import { ProjectFavicon } from "./ProjectFavicon";
25 import { useAtomValue } from "@effect/atom-react";
26 import { autoAnimate } from "@formkit/auto-animate";
27 -import React, { useCallback, useEffect, memo, useMemo, useRef, useState } from "react";
27 +import React, { useEffect, useEffectEvent, memo, useRef, useState } from "react";
28 import { cn } from "~/lib/utils";
29 import { useShallow } from "zustand/react/shallow";
30 import {
@@ -79,6 +79,7 @@ import {
79 import { isDesktopLocalConnectionTarget, isWslConnectionTarget } from "../connection/desktopLocal";
80 import { useDesktopLocalBootstraps } from "../connection/useDesktopLocalBootstraps";
81 import { isElectron } from "../env";
82 +import { useStableCallback } from "../hooks/useStableCallback";
83 import { useTerminalFocus } from "../hooks/useTerminalFocus";
84 import { useOpenPrLink } from "../lib/openPullRequestLink";
85 import { releaseProjectDraftUploads } from "../lib/composerDraftUploads";
@@ -194,7 +195,6 @@ import {
195 isSidebarNestedLinkClick,
196 isTrailingDoubleClick,
197 resolveProjectStatusIndicator,
197 - resolveThreadRowClassName,
198 resolveThreadLastVisitedAt,
199 resolveThreadStatusPill,
200 orderItemsByPreferredIds,
@@ -291,6 +291,13 @@ function projectGroupingModeDescription(mode: SidebarProjectGroupingMode): strin
291 }
292 }
293
294 +// Every project row keys on this map, so it gets its own cache: inline, it
295 +// shared one with the modifier-key state and rebuilt on every key press.
296 +function useThreadJumpLabelMap(input: Parameters<typeof buildThreadJumpLabelMap>[0]) {
297 + "use memo";
298 + return buildThreadJumpLabelMap(input);
299 +}
300 +
301 function buildThreadJumpLabelMap(input: {
302 keybindings: ResolvedKeybindingsConfig;
303 platform: string;
@@ -376,6 +383,13 @@ function checkTaskPermission(environmentId: EnvironmentId): boolean {
383 return false;
384 }
385
386 +// The row's handlers key on this ref; built inline, the hooks after it kept the
387 +// compiler from caching it, so every render rebuilt all of them.
388 +function useScopedThreadRef(environmentId: EnvironmentId, threadId: ThreadId) {
389 + "use memo";
390 + return scopeThreadRef(environmentId, threadId);
391 +}
392 +
393 const SidebarThreadRow = memo(function SidebarThreadRow(props: SidebarThreadRowProps) {
394 const {
395 orderedProjectThreadKeys,
@@ -406,20 +420,16 @@ const SidebarThreadRow = memo(function SidebarThreadRow(props: SidebarThreadRowP
420 } = props;
421 const canOperateThread = useEnvironmentScope(thread.environmentId, AuthOrchestrationOperateScope);
422 const canOperatePreview = useEnvironmentScope(thread.environmentId, AuthPreviewOperateScope);
409 - const threadRef = scopeThreadRef(thread.environmentId, thread.id);
423 + const threadRef = useScopedThreadRef(thread.environmentId, thread.id);
424 const threadKey = scopedThreadKey(threadRef);
425 const [isFileDragOver, setIsFileDragOver] = useState(false);
412 - const fileDropHandlers = useMemo(
413 - () =>
414 - makeWorkspaceFileDropHandlers({
415 - setDragActive: setIsFileDragOver,
416 - addFiles: (files) => {
417 - onFileDropThreads(threadRef, files);
418 - },
419 - addFolders: () => {},
420 - }),
421 - [onFileDropThreads, threadRef],
422 - );
426 + const fileDropHandlers = makeWorkspaceFileDropHandlers({
427 + setDragActive: setIsFileDragOver,
428 + addFiles: (files) => {
429 + onFileDropThreads(threadRef, files);
430 + },
431 + addFolders: () => {},
432 + });
433 useEffect(() => {
434 if (!isFileDragOver) return;
435 const clearFileDrag = () => setIsFileDragOver(false);
@@ -453,31 +463,27 @@ const SidebarThreadRow = memo(function SidebarThreadRow(props: SidebarThreadRowP
463 ? (remoteEnvLabel ?? (isDesktopLocalThread ? "Local" : "Remote"))
464 : null;
465 const isHighlighted = isActive || isSelected;
456 - const handleOpenDiscoveredPort = useCallback(
457 - (event: React.MouseEvent<HTMLButtonElement>) => {
458 - const port = discoveredPorts[0];
459 - if (!port || !canOperatePreview) return;
460 - event.preventDefault();
461 - event.stopPropagation();
462 - navigateToThread(threadRef);
463 - void (async () => {
464 - const result = await openDiscoveredPort({ threadRef, port, openPreview });
465 - if (result._tag === "Success" || isAtomCommandInterrupted(result)) {
466 - return;
467 - }
468 - const error = squashAtomCommandFailure(result);
469 - toastManager.add(
470 - stackedThreadToast({
471 - type: "error",
472 - title: "Unable to open preview",
473 - description:
474 - error instanceof Error ? error.message : "The preview could not be opened.",
475 - }),
476 - );
477 - })();
478 - },
479 - [canOperatePreview, discoveredPorts, navigateToThread, openPreview, threadRef],
480 - );
466 + const handleOpenDiscoveredPort = (event: React.MouseEvent<HTMLButtonElement>) => {
467 + const port = discoveredPorts[0];
468 + if (!port || !canOperatePreview) return;
469 + event.preventDefault();
470 + event.stopPropagation();
471 + navigateToThread(threadRef);
472 + void (async () => {
473 + const result = await openDiscoveredPort({ threadRef, port, openPreview });
474 + if (result._tag === "Success" || isAtomCommandInterrupted(result)) {
475 + return;
476 + }
477 + const error = squashAtomCommandFailure(result);
478 + toastManager.add(
479 + stackedThreadToast({
480 + type: "error",
481 + title: "Unable to open preview",
482 + description: error instanceof Error ? error.message : "The preview could not be opened.",
483 + }),
484 + );
485 + })();
486 + };
487 const isThreadRunning = !threadRuntimeCanArchive(thread.runtime);
488 const threadStatus = resolveThreadStatusPill({
489 thread: {
@@ -505,84 +511,47 @@ const SidebarThreadRow = memo(function SidebarThreadRow(props: SidebarThreadRowP
511 : canOperateThread && !isThreadRunning
512 ? "pointer-events-none transition-opacity duration-150 max-sm:pr-6 group-hover/menu-sub-item:opacity-0 group-focus-within/menu-sub-item:opacity-0"
513 : "pointer-events-none";
508 - const clearConfirmingArchive = useCallback(() => {
514 + const clearConfirmingArchive = () => {
515 setConfirmingArchiveThreadKey((current) => (current === threadKey ? null : current));
510 - }, [setConfirmingArchiveThreadKey, threadKey]);
511 - const handleMouseLeave = useCallback(() => {
516 + };
517 + const handleMouseLeave = () => {
518 clearConfirmingArchive();
513 - }, [clearConfirmingArchive]);
514 - const handleBlurCapture = useCallback(
515 - (event: React.FocusEvent<HTMLLIElement>) => {
516 - const currentTarget = event.currentTarget;
517 - requestAnimationFrame(() => {
518 - if (currentTarget.contains(document.activeElement)) {
519 - return;
520 - }
521 - clearConfirmingArchive();
522 - });
523 - },
524 - [clearConfirmingArchive],
525 - );
526 - const handleRowClick = useCallback(
527 - (event: React.MouseEvent) => {
528 - handleThreadClick(event, threadRef, orderedProjectThreadKeys);
529 - },
530 - [handleThreadClick, orderedProjectThreadKeys, threadRef],
531 - );
532 - const handleRowDoubleClick = useCallback(
533 - (event: React.MouseEvent) => {
534 - if (!readEnvironmentScope(thread.environmentId, AuthOrchestrationOperateScope)) return;
535 - if (renamingThreadKey === threadKey) return;
536 - // On mobile the first tap navigates and closes the sidebar sheet, so the
537 - // inline rename can't be shown. Renaming there stays on the context menu.
538 - if (isMobile) return;
539 - if (event.metaKey || event.ctrlKey || event.shiftKey || event.altKey) return;
540 - if ((event.target as HTMLElement).closest("button, a")) return;
541 - event.preventDefault();
542 - startThreadRename(threadKey, thread.title);
543 - },
544 - [isMobile, renamingThreadKey, startThreadRename, threadKey, thread.environmentId, thread.title],
545 - );
546 - const handleRowKeyDown = useCallback(
547 - (event: React.KeyboardEvent) => {
548 - if (event.key !== "Enter" && event.key !== " ") return;
549 - event.preventDefault();
550 - navigateToThread(threadRef);
551 - },
552 - [navigateToThread, threadRef],
553 - );
554 - const handleRowContextMenu = useCallback(
555 - (event: React.MouseEvent) => {
556 - event.preventDefault();
557 - const hasSelection = useThreadSelectionStore.getState().hasSelection();
558 - if (hasSelection && isSelected) {
559 - void (async () => {
560 - const result = await settlePromise(() =>
561 - handleMultiSelectContextMenu({
562 - x: event.clientX,
563 - y: event.clientY,
564 - }),
565 - );
566 - if (result._tag === "Failure") {
567 - const error = squashAtomCommandFailure(result);
568 - toastManager.add(
569 - stackedThreadToast({
570 - type: "error",
571 - title: "Thread action failed",
572 - description: error instanceof Error ? error.message : "An error occurred.",
573 - }),
574 - );
575 - }
576 - })();
519 + };
520 + const handleBlurCapture = (event: React.FocusEvent<HTMLLIElement>) => {
521 + const currentTarget = event.currentTarget;
522 + requestAnimationFrame(() => {
523 + if (currentTarget.contains(document.activeElement)) {
524 return;
525 }
579 -
580 - if (hasSelection) {
581 - clearSelection();
582 - }
526 + clearConfirmingArchive();
527 + });
528 + };
529 + const handleRowClick = (event: React.MouseEvent) => {
530 + handleThreadClick(event, threadRef, orderedProjectThreadKeys);
531 + };
532 + const handleRowDoubleClick = (event: React.MouseEvent) => {
533 + if (!readEnvironmentScope(thread.environmentId, AuthOrchestrationOperateScope)) return;
534 + if (renamingThreadKey === threadKey) return;
535 + // On mobile the first tap navigates and closes the sidebar sheet, so the
536 + // inline rename can't be shown. Renaming there stays on the context menu.
537 + if (isMobile) return;
538 + if (event.metaKey || event.ctrlKey || event.shiftKey || event.altKey) return;
539 + if ((event.target as HTMLElement).closest("button, a")) return;
540 + event.preventDefault();
541 + startThreadRename(threadKey, thread.title);
542 + };
543 + const handleRowKeyDown = (event: React.KeyboardEvent) => {
544 + if (event.key !== "Enter" && event.key !== " ") return;
545 + event.preventDefault();
546 + navigateToThread(threadRef);
547 + };
548 + const handleRowContextMenu = (event: React.MouseEvent) => {
549 + event.preventDefault();
550 + const hasSelection = useThreadSelectionStore.getState().hasSelection();
551 + if (hasSelection && isSelected) {
552 void (async () => {
553 const result = await settlePromise(() =>
585 - handleThreadContextMenu(threadRef, {
554 + handleMultiSelectContextMenu({
555 x: event.clientX,
556 y: event.clientY,
557 }),
@@ -598,118 +567,105 @@ const SidebarThreadRow = memo(function SidebarThreadRow(props: SidebarThreadRowP
567 );
568 }
569 })();
601 - },
602 - [clearSelection, handleMultiSelectContextMenu, handleThreadContextMenu, isSelected, threadRef],
603 - );
604 - const handlePrClick = useCallback(
605 - (event: React.MouseEvent<HTMLAnchorElement>) => {
606 - const url = prStatus?.url ?? currentLinkedPr?.url;
607 - if (!url) return;
608 - const openedInRightPanel = openPrLink(
609 - event,
610 - url,
611 - openPullRequestsInRightPanel ? threadRef : undefined,
570 + return;
571 + }
572 +
573 + if (hasSelection) {
574 + clearSelection();
575 + }
576 + void (async () => {
577 + const result = await settlePromise(() =>
578 + handleThreadContextMenu(threadRef, {
579 + x: event.clientX,
580 + y: event.clientY,
581 + }),
582 );
613 - if (openedInRightPanel && openPullRequestsInRightPanel && !isActive) {
614 - navigateToThread(threadRef);
615 - }
616 - },
617 - [
618 - isActive,
619 - navigateToThread,
620 - openPrLink,
621 - openPullRequestsInRightPanel,
622 - prStatus,
623 - currentLinkedPr,
624 - threadRef,
625 - ],
626 - );
627 - const handleRenameInputRef = useCallback(
628 - (element: HTMLInputElement | null) => {
629 - if (element && renamingInputRef.current !== element) {
630 - renamingInputRef.current = element;
631 - element.focus();
632 - element.select();
633 - }
634 - },
635 - [renamingInputRef],
636 - );
637 - const handleRenameInputChange = useCallback(
638 - (event: React.ChangeEvent<HTMLInputElement>) => {
639 - setRenamingTitle(event.target.value);
640 - },
641 - [setRenamingTitle],
642 - );
643 - const handleRenameInputKeyDown = useCallback(
644 - (event: React.KeyboardEvent<HTMLInputElement>) => {
645 - event.stopPropagation();
646 - if (event.key === "Enter") {
647 - event.preventDefault();
648 - renamingCommittedRef.current = true;
649 - void commitRename(threadRef, renamingTitle, thread.title);
650 - } else if (event.key === "Escape") {
651 - event.preventDefault();
652 - renamingCommittedRef.current = true;
653 - cancelRename();
583 + if (result._tag === "Failure") {
584 + const error = squashAtomCommandFailure(result);
585 + toastManager.add(
586 + stackedThreadToast({
587 + type: "error",
588 + title: "Thread action failed",
589 + description: error instanceof Error ? error.message : "An error occurred.",
590 + }),
591 + );
592 }
655 - },
656 - [cancelRename, commitRename, renamingCommittedRef, renamingTitle, thread.title, threadRef],
657 - );
658 - const handleRenameInputBlur = useCallback(() => {
593 + })();
594 + };
595 + const handlePrClick = (event: React.MouseEvent<HTMLAnchorElement>) => {
596 + const url = prStatus?.url ?? currentLinkedPr?.url;
597 + if (!url) return;
598 + const openedInRightPanel = openPrLink(
599 + event,
600 + url,
601 + openPullRequestsInRightPanel ? threadRef : undefined,
602 + );
603 + if (openedInRightPanel && openPullRequestsInRightPanel && !isActive) {
604 + navigateToThread(threadRef);
605 + }
606 + };
607 + const handleRenameInputRef = (element: HTMLInputElement | null) => {
608 + if (element && renamingInputRef.current !== element) {
609 + renamingInputRef.current = element;
610 + element.focus();
611 + element.select();
612 + }
613 + };
614 + const handleRenameInputChange = (event: React.ChangeEvent<HTMLInputElement>) => {
615 + setRenamingTitle(event.target.value);
616 + };
617 + const handleRenameInputKeyDown = (event: React.KeyboardEvent<HTMLInputElement>) => {
618 + event.stopPropagation();
619 + if (event.key === "Enter") {
620 + event.preventDefault();
621 + renamingCommittedRef.current = true;
622 + void commitRename(threadRef, renamingTitle, thread.title);
623 + } else if (event.key === "Escape") {
624 + event.preventDefault();
625 + renamingCommittedRef.current = true;
626 + cancelRename();
627 + }
628 + };
629 + const handleRenameInputBlur = () => {
630 if (!renamingCommittedRef.current) {
631 void commitRename(threadRef, renamingTitle, thread.title);
632 }
662 - }, [commitRename, renamingCommittedRef, renamingTitle, thread.title, threadRef]);
633 + };
634 // Without stopping `dblclick`, double-clicking to select a word would re-fire
635 // the row's rename handler and reset the in-progress edit back to the title.
665 - const handleRenameInputClick = useCallback((event: React.MouseEvent<HTMLInputElement>) => {
636 + const handleRenameInputClick = (event: React.MouseEvent<HTMLInputElement>) => {
637 event.stopPropagation();
667 - }, []);
668 - const handleConfirmArchiveRef = useCallback(
669 - (element: HTMLButtonElement | null) => {
670 - if (element) {
671 - confirmArchiveButtonRefs.current.set(threadKey, element);
672 - } else {
673 - confirmArchiveButtonRefs.current.delete(threadKey);
674 - }
675 - },
676 - [confirmArchiveButtonRefs, threadKey],
677 - );
678 - const stopPropagationOnPointerDown = useCallback(
679 - (event: React.PointerEvent<HTMLButtonElement>) => {
680 - event.stopPropagation();
681 - },
682 - [],
683 - );
684 - const handleConfirmArchiveClick = useCallback(
685 - (event: React.MouseEvent<HTMLButtonElement>) => {
686 - event.preventDefault();
687 - event.stopPropagation();
688 - clearConfirmingArchive();
689 - void attemptArchiveThread(threadRef);
690 - },
691 - [attemptArchiveThread, clearConfirmingArchive, threadRef],
692 - );
693 - const handleStartArchiveConfirmation = useCallback(
694 - (event: React.MouseEvent<HTMLButtonElement>) => {
695 - event.preventDefault();
696 - event.stopPropagation();
697 - if (!checkTaskPermission(thread.environmentId)) return;
698 - setConfirmingArchiveThreadKey(threadKey);
699 - requestAnimationFrame(() => {
700 - confirmArchiveButtonRefs.current.get(threadKey)?.focus();
701 - });
702 - },
703 - [confirmArchiveButtonRefs, setConfirmingArchiveThreadKey, threadKey, thread.environmentId],
704 - );
705 - const handleArchiveImmediateClick = useCallback(
706 - (event: React.MouseEvent<HTMLButtonElement>) => {
707 - event.preventDefault();
708 - event.stopPropagation();
709 - void attemptArchiveThread(threadRef);
710 - },
711 - [attemptArchiveThread, threadRef],
712 - );
638 + };
639 + const handleConfirmArchiveRef = (element: HTMLButtonElement | null) => {
640 + if (element) {
641 + confirmArchiveButtonRefs.current.set(threadKey, element);
642 + } else {
643 + confirmArchiveButtonRefs.current.delete(threadKey);
644 + }
645 + };
646 + const stopPropagationOnPointerDown = (event: React.PointerEvent<HTMLButtonElement>) => {
647 + event.stopPropagation();
648 + };
649 + const handleConfirmArchiveClick = (event: React.MouseEvent<HTMLButtonElement>) => {
650 + event.preventDefault();
651 + event.stopPropagation();
652 + clearConfirmingArchive();
653 + void attemptArchiveThread(threadRef);
654 + };
655 + const handleStartArchiveConfirmation = (event: React.MouseEvent<HTMLButtonElement>) => {
656 + event.preventDefault();
657 + event.stopPropagation();
658 + if (!checkTaskPermission(thread.environmentId)) return;
659 + setConfirmingArchiveThreadKey(threadKey);
660 + requestAnimationFrame(() => {
661 + confirmArchiveButtonRefs.current.get(threadKey)?.focus();
662 + });
663 + };
664 + const handleArchiveImmediateClick = (event: React.MouseEvent<HTMLButtonElement>) => {
665 + event.preventDefault();
666 + event.stopPropagation();
667 + void attemptArchiveThread(threadRef);
668 + };
669
670 return (
671 <SidebarMenuSubItem
@@ -1040,8 +996,8 @@ const SidebarProjectThreadList = memo(function SidebarProjectThreadList(
996 expandThreadListForProject,
997 collapseThreadListForProject,
998 } = props;
1043 - const showMoreButtonRender = useMemo(() => <button type="button" />, []);
1044 - const showLessButtonRender = useMemo(() => <button type="button" />, []);
999 + const showMoreButtonRender = <button type="button" />;
1000 + const showLessButtonRender = <button type="button" />;
1001
1002 return (
1003 <SidebarMenuSub
@@ -1149,6 +1105,153 @@ interface SidebarProjectItemProps {
1105 dragHandleProps: SortableProjectHandleProps | null;
1106 }
1107
1108 +function resolveProjectThreadStatus(
1109 + thread: SidebarThreadSummary,
1110 + lastVisitedAtByThreadKey: ReadonlyMap<string, string | undefined>,
1111 +) {
1112 + const lastVisitedAt = lastVisitedAtByThreadKey.get(
1113 + scopedThreadKey(scopeThreadRef(thread.environmentId, thread.id)),
1114 + );
1115 + return resolveThreadStatusPill({
1116 + thread: {
1117 + ...thread,
1118 + ...(lastVisitedAt !== null && lastVisitedAt !== undefined ? { lastVisitedAt } : {}),
1119 + },
1120 + });
1121 +}
1122 +
1123 +// Thread derivations for one project row. Built in their own hooks so they reach
1124 +// SidebarProjectItem frozen: inline, its later calls made the compiler fuse the
1125 +// ordered keys with the route-dependent panel, handing every row a new array.
1126 +function useProjectThreads(project: SidebarProjectSnapshot) {
1127 + "use memo";
1128 + const threadSortOrder = useClientSettings<SidebarThreadSortOrder>(
1129 + (settings) => settings.sidebarThreadSortOrder,
1130 + );
1131 + const sidebarThreads = useThreadShellsForProjectRefs(project.memberProjectRefs);
1132 + const threadLastVisitedAts = useUiStateStore(
1133 + useShallow((state) =>
1134 + sidebarThreads.map(
1135 + (thread) =>
1136 + state.threadLastVisitedAtById[
1137 + scopedThreadKey(scopeThreadRef(thread.environmentId, thread.id))
1138 + ] ?? null,
1139 + ),
1140 + ),
1141 + );
1142 + const sidebarThreadByKey = new Map(
1143 + sidebarThreads.map(
1144 + (thread) =>
1145 + [scopedThreadKey(scopeThreadRef(thread.environmentId, thread.id)), thread] as const,
1146 + ),
1147 + );
1148 + const memberProjectByScopedKey = new Map(
1149 + project.memberProjects.map((member) => [
1150 + scopedProjectKey(scopeProjectRef(member.environmentId, member.id)),
1151 + member,
1152 + ]),
1153 + );
1154 + const memberThreadCountByPhysicalKey = new Map<string, number>(
1155 + project.memberProjects.map((member) => [member.physicalProjectKey, 0] as const),
1156 + );
1157 + for (const thread of sidebarThreads) {
1158 + const member = memberProjectByScopedKey.get(
1159 + scopedProjectKey(scopeProjectRef(thread.environmentId, thread.projectId)),
1160 + );
1161 + if (!member) {
1162 + continue;
1163 + }
1164 + memberThreadCountByPhysicalKey.set(
1165 + member.physicalProjectKey,
1166 + (memberThreadCountByPhysicalKey.get(member.physicalProjectKey) ?? 0) + 1,
1167 + );
1168 + }
1169 + const lastVisitedAtByThreadKey = new Map(
1170 + sidebarThreads.map((thread, index) => [
1171 + scopedThreadKey(scopeThreadRef(thread.environmentId, thread.id)),
1172 + resolveThreadLastVisitedAt(thread.lastVisitedAt, threadLastVisitedAts[index] ?? undefined),
1173 + ]),
1174 + );
1175 + const visibleProjectThreads = sortThreads(
1176 + sidebarThreads.filter((thread) => thread.archivedAt === null),
1177 + threadSortOrder,
1178 + );
1179 + const projectStatus = resolveProjectStatusIndicator(
1180 + visibleProjectThreads.map((thread) =>
1181 + resolveProjectThreadStatus(thread, lastVisitedAtByThreadKey),
1182 + ),
1183 + );
1184 + const orderedProjectThreadKeys = visibleProjectThreads.map((thread) =>
1185 + scopedThreadKey(scopeThreadRef(thread.environmentId, thread.id)),
1186 + );
1187 + return {
1188 + sidebarThreads,
1189 + sidebarThreadByKey,
1190 + memberProjectByScopedKey,
1191 + memberThreadCountByPhysicalKey,
1192 + lastVisitedAtByThreadKey,
1193 + visibleProjectThreads,
1194 + projectStatus,
1195 + orderedProjectThreadKeys,
1196 + };
1197 +}
1198 +
1199 +function useProjectThreadPanel(input: {
1200 + visibleProjectThreads: readonly SidebarThreadSummary[];
1201 + lastVisitedAtByThreadKey: ReadonlyMap<string, string | undefined>;
1202 + activeRouteThreadKey: string | null;
1203 + projectExpanded: boolean;
1204 + isThreadListExpanded: boolean;
1205 +}) {
1206 + "use memo";
1207 + const {
1208 + visibleProjectThreads,
1209 + lastVisitedAtByThreadKey,
1210 + activeRouteThreadKey,
1211 + projectExpanded,
1212 + isThreadListExpanded,
1213 + } = input;
1214 + const sidebarThreadPreviewCount = useClientSettings<SidebarThreadPreviewCount>(
1215 + (settings) => settings.sidebarThreadPreviewCount,
1216 + );
1217 + const activeThreadKey = activeRouteThreadKey ?? undefined;
1218 + const pinnedCollapsedThread =
1219 + !activeThreadKey || projectExpanded
1220 + ? null
1221 + : (visibleProjectThreads.find(
1222 + (thread) =>
1223 + scopedThreadKey(scopeThreadRef(thread.environmentId, thread.id)) === activeThreadKey,
1224 + ) ?? null);
1225 + const hasOverflowingThreads = visibleProjectThreads.length > sidebarThreadPreviewCount;
1226 + const previewThreads =
1227 + isThreadListExpanded || !hasOverflowingThreads
1228 + ? visibleProjectThreads
1229 + : visibleProjectThreads.slice(0, sidebarThreadPreviewCount);
1230 + const visibleThreadKeys = new Set(
1231 + [...previewThreads, ...(pinnedCollapsedThread ? [pinnedCollapsedThread] : [])].map((thread) =>
1232 + scopedThreadKey(scopeThreadRef(thread.environmentId, thread.id)),
1233 + ),
1234 + );
1235 + const renderedThreads = pinnedCollapsedThread
1236 + ? [pinnedCollapsedThread]
1237 + : visibleProjectThreads.filter((thread) =>
1238 + visibleThreadKeys.has(scopedThreadKey(scopeThreadRef(thread.environmentId, thread.id))),
1239 + );
1240 + const hiddenThreads = visibleProjectThreads.filter(
1241 + (thread) =>
1242 + !visibleThreadKeys.has(scopedThreadKey(scopeThreadRef(thread.environmentId, thread.id))),
1243 + );
1244 + return {
1245 + hasOverflowingThreads,
1246 + hiddenThreadStatus: resolveProjectStatusIndicator(
1247 + hiddenThreads.map((thread) => resolveProjectThreadStatus(thread, lastVisitedAtByThreadKey)),
1248 + ),
1249 + renderedThreads,
1250 + showEmptyThreadState: projectExpanded && visibleProjectThreads.length === 0,
1251 + shouldShowThreadPanel: projectExpanded || pinnedCollapsedThread !== null,
1252 + };
1253 +}
1254 +
1255 const SidebarProjectItem = memo(function SidebarProjectItem(props: SidebarProjectItemProps) {
1256 const {
1257 project,
@@ -1175,9 +1278,6 @@ const SidebarProjectItem = memo(function SidebarProjectItem(props: SidebarProjec
1278 : project.allRemoteMembersAreDesktopLocal
1279 ? "laptop"
1280 : "cloud";
1178 - const threadSortOrder = useClientSettings<SidebarThreadSortOrder>(
1179 - (settings) => settings.sidebarThreadSortOrder,
1180 - );
1281 const appSettingsConfirmThreadDelete = useClientSettings<boolean>(
1282 (settings) => settings.confirmThreadDelete,
1283 );
@@ -1195,9 +1295,6 @@ const SidebarProjectItem = memo(function SidebarProjectItem(props: SidebarProjec
1295 reportFailure: false,
1296 });
1297 const updateSettings = useUpdateClientSettings();
1198 - const sidebarThreadPreviewCount = useClientSettings<SidebarThreadPreviewCount>(
1199 - (settings) => settings.sidebarThreadPreviewCount,
1200 - );
1298 const router = useRouter();
1299 const queuePendingFileDrop = useSidebarPendingFileDropStore((s) => s.queuePendingFileDrop);
1300 const clearPendingFileDrop = useSidebarPendingFileDropStore((s) => s.clearPendingFileDrop);
@@ -1249,37 +1346,23 @@ const SidebarProjectItem = memo(function SidebarProjectItem(props: SidebarProjec
1346 },
1347 });
1348 const openPrLink = useOpenPrLink();
1252 - const sidebarThreads = useThreadShellsForProjectRefs(project.memberProjectRefs);
1253 - const sidebarThreadByKey = useMemo(
1254 - () =>
1255 - new Map(
1256 - sidebarThreads.map(
1257 - (thread) =>
1258 - [scopedThreadKey(scopeThreadRef(thread.environmentId, thread.id)), thread] as const,
1259 - ),
1260 - ),
1261 - [sidebarThreads],
1262 - );
1263 - // Keep a ref so callbacks can read the latest map without appearing in
1264 - // dependency arrays (avoids invalidating every thread-row memo on each
1265 - // thread-list change).
1266 - const sidebarThreadByKeyRef = useRef(sidebarThreadByKey);
1267 - sidebarThreadByKeyRef.current = sidebarThreadByKey;
1268 - const projectThreads = sidebarThreads;
1269 - const projectPreferenceKeys = useMemo(() => projectExpansionPreferenceKeys(project), [project]);
1349 + const {
1350 + sidebarThreads,
1351 + sidebarThreadByKey,
1352 + memberProjectByScopedKey,
1353 + memberThreadCountByPhysicalKey,
1354 + projectStatus,
1355 + visibleProjectThreads,
1356 + orderedProjectThreadKeys,
1357 + lastVisitedAtByThreadKey,
1358 + } = useProjectThreads(project);
1359 + // The "Delete anyway" toast action runs after the toast delay, so it must see
1360 + // the thread list as of the click, not as of the first prompt.
1361 + const readSidebarThreadByKey = useStableCallback(() => sidebarThreadByKey);
1362 + const projectPreferenceKeys = projectExpansionPreferenceKeys(project);
1363 const projectExpanded = useUiStateStore((state) =>
1364 resolveProjectExpanded(state.projectExpandedById, projectPreferenceKeys),
1365 );
1273 - const threadLastVisitedAts = useUiStateStore(
1274 - useShallow((state) =>
1275 - projectThreads.map(
1276 - (thread) =>
1277 - state.threadLastVisitedAtById[
1278 - scopedThreadKey(scopeThreadRef(thread.environmentId, thread.id))
1279 - ] ?? null,
1280 - ),
1281 - ),
1282 - );
1366 const [renamingThreadKey, setRenamingThreadKey] = useState<string | null>(null);
1367 const [renamingTitle, setRenamingTitle] = useState("");
1368 const [confirmingArchiveThreadKey, setConfirmingArchiveThreadKey] = useState<string | null>(null);
@@ -1299,708 +1382,470 @@ const SidebarProjectItem = memo(function SidebarProjectItem(props: SidebarProjec
1382 const renamingCommittedRef = useRef(false);
1383 const renamingInputRef = useRef<HTMLInputElement | null>(null);
1384 const confirmArchiveButtonRefs = useRef(new Map<string, HTMLButtonElement>());
1302 - const memberProjectByScopedKey = useMemo(
1303 - () =>
1304 - new Map(
1305 - project.memberProjects.map((member) => [
1306 - scopedProjectKey(scopeProjectRef(member.environmentId, member.id)),
1307 - member,
1308 - ]),
1309 - ),
1310 - [project.memberProjects],
1311 - );
1312 - const memberThreadCountByPhysicalKey = useMemo(() => {
1313 - const counts = new Map<string, number>(
1314 - project.memberProjects.map((member) => [member.physicalProjectKey, 0] as const),
1315 - );
1316 - for (const thread of projectThreads) {
1317 - const member = memberProjectByScopedKey.get(
1318 - scopedProjectKey(scopeProjectRef(thread.environmentId, thread.projectId)),
1319 - );
1320 - if (!member) {
1321 - continue;
1322 - }
1323 - counts.set(member.physicalProjectKey, (counts.get(member.physicalProjectKey) ?? 0) + 1);
1324 - }
1325 - return counts;
1326 - }, [memberProjectByScopedKey, project.memberProjects, projectThreads]);
1327 -
1328 - const { projectStatus, visibleProjectThreads, orderedProjectThreadKeys } = useMemo(() => {
1329 - const lastVisitedAtByThreadKey = new Map(
1330 - projectThreads.map((thread, index) => [
1331 - scopedThreadKey(scopeThreadRef(thread.environmentId, thread.id)),
1332 - resolveThreadLastVisitedAt(thread.lastVisitedAt, threadLastVisitedAts[index] ?? undefined),
1333 - ]),
1334 - );
1335 - const resolveProjectThreadStatus = (thread: SidebarThreadSummary) => {
1336 - const lastVisitedAt = lastVisitedAtByThreadKey.get(
1337 - scopedThreadKey(scopeThreadRef(thread.environmentId, thread.id)),
1338 - );
1339 - return resolveThreadStatusPill({
1340 - thread: {
1341 - ...thread,
1342 - ...(lastVisitedAt !== null && lastVisitedAt !== undefined ? { lastVisitedAt } : {}),
1343 - },
1344 - });
1345 - };
1346 - const visibleProjectThreads = sortThreads(
1347 - projectThreads.filter((thread) => thread.archivedAt === null),
1348 - threadSortOrder,
1349 - );
1350 - const projectStatus = resolveProjectStatusIndicator(
1351 - visibleProjectThreads.map((thread) => resolveProjectThreadStatus(thread)),
1352 - );
1353 - return {
1354 - orderedProjectThreadKeys: visibleProjectThreads.map((thread) =>
1355 - scopedThreadKey(scopeThreadRef(thread.environmentId, thread.id)),
1356 - ),
1357 - projectStatus,
1358 - visibleProjectThreads,
1359 - };
1360 - }, [projectThreads, threadLastVisitedAts, threadSortOrder]);
1361 - const pinnedCollapsedThread = useMemo(() => {
1362 - const activeThreadKey = activeRouteThreadKey ?? undefined;
1363 - if (!activeThreadKey || projectExpanded) {
1364 - return null;
1365 - }
1366 - return (
1367 - visibleProjectThreads.find(
1368 - (thread) =>
1369 - scopedThreadKey(scopeThreadRef(thread.environmentId, thread.id)) === activeThreadKey,
1370 - ) ?? null
1371 - );
1372 - }, [activeRouteThreadKey, projectExpanded, visibleProjectThreads]);
1373 -
1385 const {
1386 hasOverflowingThreads,
1387 hiddenThreadStatus,
1388 renderedThreads,
1389 showEmptyThreadState,
1390 shouldShowThreadPanel,
1380 - } = useMemo(() => {
1381 - const lastVisitedAtByThreadKey = new Map(
1382 - projectThreads.map((thread, index) => [
1383 - scopedThreadKey(scopeThreadRef(thread.environmentId, thread.id)),
1384 - resolveThreadLastVisitedAt(thread.lastVisitedAt, threadLastVisitedAts[index] ?? undefined),
1385 - ]),
1386 - );
1387 - const resolveProjectThreadStatus = (thread: SidebarThreadSummary) => {
1388 - const lastVisitedAt = lastVisitedAtByThreadKey.get(
1389 - scopedThreadKey(scopeThreadRef(thread.environmentId, thread.id)),
1390 - );
1391 - return resolveThreadStatusPill({
1392 - thread: {
1393 - ...thread,
1394 - ...(lastVisitedAt !== null && lastVisitedAt !== undefined ? { lastVisitedAt } : {}),
1395 - },
1396 - });
1397 - };
1398 - const hasOverflowingThreads = visibleProjectThreads.length > sidebarThreadPreviewCount;
1399 - const previewThreads =
1400 - isThreadListExpanded || !hasOverflowingThreads
1401 - ? visibleProjectThreads
1402 - : visibleProjectThreads.slice(0, sidebarThreadPreviewCount);
1403 - const visibleThreadKeys = new Set(
1404 - [...previewThreads, ...(pinnedCollapsedThread ? [pinnedCollapsedThread] : [])].map((thread) =>
1405 - scopedThreadKey(scopeThreadRef(thread.environmentId, thread.id)),
1406 - ),
1407 - );
1408 - const renderedThreads = pinnedCollapsedThread
1409 - ? [pinnedCollapsedThread]
1410 - : visibleProjectThreads.filter((thread) =>
1411 - visibleThreadKeys.has(scopedThreadKey(scopeThreadRef(thread.environmentId, thread.id))),
1412 - );
1413 - const hiddenThreads = visibleProjectThreads.filter(
1414 - (thread) =>
1415 - !visibleThreadKeys.has(scopedThreadKey(scopeThreadRef(thread.environmentId, thread.id))),
1416 - );
1417 - return {
1418 - hasOverflowingThreads,
1419 - hiddenThreadStatus: resolveProjectStatusIndicator(
1420 - hiddenThreads.map((thread) => resolveProjectThreadStatus(thread)),
1421 - ),
1422 - renderedThreads,
1423 - showEmptyThreadState: projectExpanded && visibleProjectThreads.length === 0,
1424 - shouldShowThreadPanel: projectExpanded || pinnedCollapsedThread !== null,
1425 - };
1426 - }, [
1427 - isThreadListExpanded,
1428 - pinnedCollapsedThread,
1429 - projectExpanded,
1430 - projectThreads,
1431 - sidebarThreadPreviewCount,
1432 - threadLastVisitedAts,
1391 + } = useProjectThreadPanel({
1392 visibleProjectThreads,
1434 - ]);
1435 -
1436 - const handleProjectButtonClick = useCallback(
1437 - (event: React.MouseEvent<HTMLButtonElement>) => {
1438 - if (suppressProjectClickForContextMenuRef.current) {
1439 - suppressProjectClickForContextMenuRef.current = false;
1440 - event.preventDefault();
1441 - event.stopPropagation();
1442 - return;
1443 - }
1444 - if (dragInProgressRef.current) {
1445 - event.preventDefault();
1446 - event.stopPropagation();
1447 - return;
1448 - }
1449 - if (suppressProjectClickAfterDragRef.current) {
1450 - suppressProjectClickAfterDragRef.current = false;
1451 - event.preventDefault();
1452 - event.stopPropagation();
1453 - return;
1454 - }
1455 - if (useThreadSelectionStore.getState().hasSelection()) {
1456 - clearSelection();
1457 - }
1458 - setProjectExpanded(projectPreferenceKeys, !projectExpanded);
1459 - },
1460 - [
1461 - clearSelection,
1462 - dragInProgressRef,
1463 - projectExpanded,
1464 - projectPreferenceKeys,
1465 - setProjectExpanded,
1466 - suppressProjectClickAfterDragRef,
1467 - suppressProjectClickForContextMenuRef,
1468 - ],
1469 - );
1393 + lastVisitedAtByThreadKey,
1394 + activeRouteThreadKey,
1395 + projectExpanded,
1396 + isThreadListExpanded,
1397 + });
1398
1471 - const handleProjectButtonKeyDown = useCallback(
1472 - (event: React.KeyboardEvent<HTMLButtonElement>) => {
1473 - if (event.key !== "Enter" && event.key !== " ") return;
1399 + const handleProjectButtonClick = (event: React.MouseEvent<HTMLButtonElement>) => {
1400 + if (suppressProjectClickForContextMenuRef.current) {
1401 + suppressProjectClickForContextMenuRef.current = false;
1402 event.preventDefault();
1475 - if (dragInProgressRef.current) {
1476 - return;
1477 - }
1478 - setProjectExpanded(projectPreferenceKeys, !projectExpanded);
1479 - },
1480 - [dragInProgressRef, projectExpanded, projectPreferenceKeys, setProjectExpanded],
1481 - );
1403 + event.stopPropagation();
1404 + return;
1405 + }
1406 + if (dragInProgressRef.current) {
1407 + event.preventDefault();
1408 + event.stopPropagation();
1409 + return;
1410 + }
1411 + if (suppressProjectClickAfterDragRef.current) {
1412 + suppressProjectClickAfterDragRef.current = false;
1413 + event.preventDefault();
1414 + event.stopPropagation();
1415 + return;
1416 + }
1417 + if (useThreadSelectionStore.getState().hasSelection()) {
1418 + clearSelection();
1419 + }
1420 + setProjectExpanded(projectPreferenceKeys, !projectExpanded);
1421 + };
1422
1483 - const handleProjectButtonPointerDownCapture = useCallback(
1484 - (event: React.PointerEvent<HTMLButtonElement>) => {
1485 - suppressProjectClickForContextMenuRef.current = false;
1486 - if (
1487 - isContextMenuPointerDown({
1488 - button: event.button,
1489 - ctrlKey: event.ctrlKey,
1490 - isMac: isMacPlatform(navigator.platform),
1491 - })
1492 - ) {
1493 - event.stopPropagation();
1494 - }
1423 + const handleProjectButtonKeyDown = (event: React.KeyboardEvent<HTMLButtonElement>) => {
1424 + if (event.key !== "Enter" && event.key !== " ") return;
1425 + event.preventDefault();
1426 + if (dragInProgressRef.current) {
1427 + return;
1428 + }
1429 + setProjectExpanded(projectPreferenceKeys, !projectExpanded);
1430 + };
1431
1496 - suppressProjectClickAfterDragRef.current = false;
1497 - },
1498 - [suppressProjectClickAfterDragRef, suppressProjectClickForContextMenuRef],
1499 - );
1432 + const handleProjectButtonPointerDownCapture = (event: React.PointerEvent<HTMLButtonElement>) => {
1433 + suppressProjectClickForContextMenuRef.current = false;
1434 + if (
1435 + isContextMenuPointerDown({
1436 + button: event.button,
1437 + ctrlKey: event.ctrlKey,
1438 + isMac: isMacPlatform(navigator.platform),
1439 + })
1440 + ) {
1441 + event.stopPropagation();
1442 + }
1443
1501 - const openProjectRenameDialog = useCallback((member: SidebarProjectGroupMember) => {
1444 + suppressProjectClickAfterDragRef.current = false;
1445 + };
1446 +
1447 + const openProjectRenameDialog = (member: SidebarProjectGroupMember) => {
1448 if (!checkTaskPermission(member.environmentId)) return;
1449 setProjectRenameTarget(member);
1450 setProjectRenameTitle(member.title);
1505 - }, []);
1451 + };
1452
1507 - const openProjectGroupingDialog = useCallback(
1508 - (member: SidebarProjectGroupMember) => {
1509 - const overrideKey = deriveProjectGroupingOverrideKey(member);
1510 - setProjectGroupingTarget(member);
1511 - setProjectGroupingSelection(
1512 - projectGroupingSettings.sidebarProjectGroupingOverrides?.[overrideKey] ?? "inherit",
1513 - );
1514 - },
1515 - [projectGroupingSettings.sidebarProjectGroupingOverrides],
1516 - );
1453 + const openProjectGroupingDialog = (member: SidebarProjectGroupMember) => {
1454 + const overrideKey = deriveProjectGroupingOverrideKey(member);
1455 + setProjectGroupingTarget(member);
1456 + setProjectGroupingSelection(
1457 + projectGroupingSettings.sidebarProjectGroupingOverrides?.[overrideKey] ?? "inherit",
1458 + );
1459 + };
1460
1518 - const removeProject = useCallback(
1519 - async (member: SidebarProjectGroupMember) => {
1520 - const memberProjectRef = scopeProjectRef(member.environmentId, member.id);
1521 - const result = await deleteProject({
1522 - environmentId: member.environmentId,
1523 - input: {
1524 - projectId: member.id,
1525 - force: true,
1526 - },
1527 - });
1528 - if (result._tag === "Failure") {
1529 - return result;
1530 - }
1531 - await waitForProjectRemoval(memberProjectRef);
1532 - const draftStore = useComposerDraftStore.getState();
1533 - releaseProjectDraftUploads(
1534 - memberProjectRef,
1535 - sidebarThreads
1536 - .filter(
1537 - (thread) =>
1538 - thread.environmentId === member.environmentId && thread.projectId === member.id,
1539 - )
1540 - .map((thread) => scopeThreadRef(thread.environmentId, thread.id)),
1541 - );
1542 - const projectDraftThread = draftStore.getDraftThreadByProjectRef(memberProjectRef);
1543 - if (projectDraftThread) {
1544 - draftStore.clearDraftThread(projectDraftThread.draftId);
1545 - }
1546 - draftStore.clearProjectDraftThreadId(memberProjectRef);
1461 + const removeProject = async (member: SidebarProjectGroupMember) => {
1462 + const memberProjectRef = scopeProjectRef(member.environmentId, member.id);
1463 + const result = await deleteProject({
1464 + environmentId: member.environmentId,
1465 + input: {
1466 + projectId: member.id,
1467 + force: true,
1468 + },
1469 + });
1470 + if (result._tag === "Failure") {
1471 return result;
1548 - },
1549 - [deleteProject, sidebarThreads],
1550 - );
1472 + }
1473 + await waitForProjectRemoval(memberProjectRef);
1474 + const draftStore = useComposerDraftStore.getState();
1475 + releaseProjectDraftUploads(
1476 + memberProjectRef,
1477 + sidebarThreads
1478 + .filter(
1479 + (thread) =>
1480 + thread.environmentId === member.environmentId && thread.projectId === member.id,
1481 + )
1482 + .map((thread) => scopeThreadRef(thread.environmentId, thread.id)),
1483 + );
1484 + const projectDraftThread = draftStore.getDraftThreadByProjectRef(memberProjectRef);
1485 + if (projectDraftThread) {
1486 + draftStore.clearDraftThread(projectDraftThread.draftId);
1487 + }
1488 + draftStore.clearProjectDraftThreadId(memberProjectRef);
1489 + return result;
1490 + };
1491
1552 - const handleRemoveProject = useCallback(
1553 - async (member: SidebarProjectGroupMember) => {
1554 - if (!checkTaskPermission(member.environmentId)) return;
1555 - const api = readLocalApi();
1556 - if (!api) {
1557 - return;
1558 - }
1492 + const handleRemoveProject = async (member: SidebarProjectGroupMember) => {
1493 + if (!checkTaskPermission(member.environmentId)) return;
1494 + const api = readLocalApi();
1495 + if (!api) {
1496 + return;
1497 + }
1498
1560 - const memberProjectRef = scopeProjectRef(member.environmentId, member.id);
1561 - const memberThreadCount = memberThreadCountByPhysicalKey.get(member.physicalProjectKey) ?? 0;
1562 - if (memberThreadCount > 0) {
1563 - const warningToastId = toastManager.add(
1564 - stackedThreadToast({
1565 - type: "warning",
1566 - title: "Project is not empty",
1567 - description: "Delete all threads in this project before removing it.",
1568 - actionVariant: "destructive",
1569 - actionProps: {
1570 - children: "Delete anyway",
1571 - onClick: () => {
1572 - void (async () => {
1573 - toastManager.close(warningToastId);
1574 - await new Promise<void>((resolve) => {
1575 - window.setTimeout(resolve, 180);
1576 - });
1577 - if (!checkTaskPermission(member.environmentId)) return;
1578 -
1579 - const latestProjectThreads = Array.from(
1580 - sidebarThreadByKeyRef.current.values(),
1581 - ).filter(
1582 - (thread) =>
1583 - thread.environmentId === memberProjectRef.environmentId &&
1584 - thread.projectId === memberProjectRef.projectId,
1585 - );
1586 - const confirmed = await api.dialogs.confirm(
1587 - latestProjectThreads.length > 0
1588 - ? [
1589 - `Remove project "${member.title}" and delete its ${latestProjectThreads.length} thread${
1590 - latestProjectThreads.length === 1 ? "" : "s"
1591 - }?`,
1592 - `Path: ${member.workspaceRoot}`,
1593 - ...(member.environmentLabel
1594 - ? [`Environment: ${member.environmentLabel}`]
1595 - : []),
1596 - "This permanently clears conversation history for those threads and any archived threads.",
1597 - "This removes only this project entry.",
1598 - "This action cannot be undone.",
1599 - ].join("\n")
1600 - : [
1601 - `Remove project "${member.title}"?`,
1602 - `Path: ${member.workspaceRoot}`,
1603 - ...(member.environmentLabel
1604 - ? [`Environment: ${member.environmentLabel}`]
1605 - : []),
1606 - "This permanently clears any archived conversation history.",
1607 - "This removes only this project entry.",
1608 - ].join("\n"),
1609 - { variant: "destructive" },
1610 - );
1611 - if (!confirmed) {
1612 - return;
1613 - }
1499 + const memberProjectRef = scopeProjectRef(member.environmentId, member.id);
1500 + const memberThreadCount = memberThreadCountByPhysicalKey.get(member.physicalProjectKey) ?? 0;
1501 + if (memberThreadCount > 0) {
1502 + const warningToastId = toastManager.add(
1503 + stackedThreadToast({
1504 + type: "warning",
1505 + title: "Project is not empty",
1506 + description: "Delete all threads in this project before removing it.",
1507 + actionVariant: "destructive",
1508 + actionProps: {
1509 + children: "Delete anyway",
1510 + onClick: () => {
1511 + void (async () => {
1512 + toastManager.close(warningToastId);
1513 + await new Promise<void>((resolve) => {
1514 + window.setTimeout(resolve, 180);
1515 + });
1516 + if (!checkTaskPermission(member.environmentId)) return;
1517 +
1518 + const latestProjectThreads = Array.from(readSidebarThreadByKey().values()).filter(
1519 + (thread) =>
1520 + thread.environmentId === memberProjectRef.environmentId &&
1521 + thread.projectId === memberProjectRef.projectId,
1522 + );
1523 + const confirmed = await api.dialogs.confirm(
1524 + latestProjectThreads.length > 0
1525 + ? [
1526 + `Remove project "${member.title}" and delete its ${latestProjectThreads.length} thread${
1527 + latestProjectThreads.length === 1 ? "" : "s"
1528 + }?`,
1529 + `Path: ${member.workspaceRoot}`,
1530 + ...(member.environmentLabel
1531 + ? [`Environment: ${member.environmentLabel}`]
1532 + : []),
1533 + "This permanently clears conversation history for those threads and any archived threads.",
1534 + "This removes only this project entry.",
1535 + "This action cannot be undone.",
1536 + ].join("\n")
1537 + : [
1538 + `Remove project "${member.title}"?`,
1539 + `Path: ${member.workspaceRoot}`,
1540 + ...(member.environmentLabel
1541 + ? [`Environment: ${member.environmentLabel}`]
1542 + : []),
1543 + "This permanently clears any archived conversation history.",
1544 + "This removes only this project entry.",
1545 + ].join("\n"),
1546 + { variant: "destructive" },
1547 + );
1548 + if (!confirmed) {
1549 + return;
1550 + }
1551
1615 - const result = await removeProject(member);
1616 - if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) {
1617 - const error = squashAtomCommandFailure(result);
1618 - toastManager.add(
1619 - stackedThreadToast({
1620 - type: "error",
1621 - title: `Failed to remove "${member.title}"`,
1622 - description:
1623 - error instanceof Error
1624 - ? error.message
1625 - : "Unknown error removing project.",
1626 - }),
1627 - );
1628 - }
1629 - })().catch((error) => {
1630 - const message =
1631 - error instanceof Error ? error.message : "Unknown error removing project.";
1632 - console.error("Failed to remove project", {
1633 - projectId: member.id,
1634 - environmentId: member.environmentId,
1635 - ...safeErrorLogAttributes(error),
1636 - });
1552 + const result = await removeProject(member);
1553 + if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) {
1554 + const error = squashAtomCommandFailure(result);
1555 toastManager.add(
1556 stackedThreadToast({
1557 type: "error",
1558 title: `Failed to remove "${member.title}"`,
1641 - description: message,
1559 + description:
1560 + error instanceof Error ? error.message : "Unknown error removing project.",
1561 }),
1562 );
1563 + }
1564 + })().catch((error) => {
1565 + const message =
1566 + error instanceof Error ? error.message : "Unknown error removing project.";
1567 + console.error("Failed to remove project", {
1568 + projectId: member.id,
1569 + environmentId: member.environmentId,
1570 + ...safeErrorLogAttributes(error),
1571 });
1645 - },
1572 + toastManager.add(
1573 + stackedThreadToast({
1574 + type: "error",
1575 + title: `Failed to remove "${member.title}"`,
1576 + description: message,
1577 + }),
1578 + );
1579 + });
1580 },
1647 - }),
1648 - );
1649 - return;
1650 - }
1651 -
1652 - const message = [
1653 - `Remove project "${member.title}"?`,
1654 - `Path: ${member.workspaceRoot}`,
1655 - ...(member.environmentLabel ? [`Environment: ${member.environmentLabel}`] : []),
1656 - "This permanently clears any archived conversation history.",
1657 - "This removes only this project entry.",
1658 - ].join("\n");
1659 - const confirmed = await api.dialogs.confirm(message, { variant: "destructive" });
1660 - if (!confirmed) {
1661 - return;
1662 - }
1581 + },
1582 + }),
1583 + );
1584 + return;
1585 + }
1586
1664 - const result = await removeProject(member);
1665 - if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) {
1666 - const error = squashAtomCommandFailure(result);
1667 - const message = error instanceof Error ? error.message : "Unknown error removing project.";
1668 - console.error("Failed to remove project", {
1669 - projectId: member.id,
1670 - environmentId: member.environmentId,
1671 - ...safeErrorLogAttributes(error),
1672 - });
1673 - toastManager.add(
1674 - stackedThreadToast({
1675 - type: "error",
1676 - title: `Failed to remove "${member.title}"`,
1677 - description: message,
1678 - }),
1679 - );
1680 - }
1681 - },
1682 - [memberThreadCountByPhysicalKey, removeProject],
1683 - );
1587 + const message = [
1588 + `Remove project "${member.title}"?`,
1589 + `Path: ${member.workspaceRoot}`,
1590 + ...(member.environmentLabel ? [`Environment: ${member.environmentLabel}`] : []),
1591 + "This permanently clears any archived conversation history.",
1592 + "This removes only this project entry.",
1593 + ].join("\n");
1594 + const confirmed = await api.dialogs.confirm(message, { variant: "destructive" });
1595 + if (!confirmed) {
1596 + return;
1597 + }
1598
1685 - const handleProjectButtonContextMenu = useCallback(
1686 - (event: React.MouseEvent<HTMLButtonElement>) => {
1687 - event.preventDefault();
1688 - suppressProjectClickForContextMenuRef.current = true;
1689 - void (async () => {
1690 - const api = readLocalApi();
1691 - if (!api) return;
1692 -
1693 - const actionHandlers = new Map<string, () => Promise<void> | void>();
1694 - const makeLeaf = (
1695 - action: "rename" | "grouping" | "copy-path" | "delete",
1696 - member: SidebarProjectGroupMember,
1697 - options?: {
1698 - destructive?: boolean;
1699 - disabled?: boolean;
1700 - },
1701 - ): ContextMenuItem<string> => {
1702 - const id = `${action}:${member.physicalProjectKey}`;
1703 - actionHandlers.set(id, () => {
1704 - switch (action) {
1705 - case "rename":
1706 - openProjectRenameDialog(member);
1707 - return;
1708 - case "grouping":
1709 - openProjectGroupingDialog(member);
1710 - return;
1711 - case "copy-path":
1712 - copyPathToClipboard(member.workspaceRoot, { path: member.workspaceRoot });
1713 - return;
1714 - case "delete":
1715 - return handleRemoveProject(member);
1716 - }
1717 - });
1599 + const result = await removeProject(member);
1600 + if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) {
1601 + const error = squashAtomCommandFailure(result);
1602 + const message = error instanceof Error ? error.message : "Unknown error removing project.";
1603 + console.error("Failed to remove project", {
1604 + projectId: member.id,
1605 + environmentId: member.environmentId,
1606 + ...safeErrorLogAttributes(error),
1607 + });
1608 + toastManager.add(
1609 + stackedThreadToast({
1610 + type: "error",
1611 + title: `Failed to remove "${member.title}"`,
1612 + description: message,
1613 + }),
1614 + );
1615 + }
1616 + };
1617
1719 - return {
1720 - id,
1721 - label: formatProjectMemberActionLabel(member, project.groupedProjectCount),
1722 - ...(options?.destructive ? { destructive: true } : {}),
1723 - ...(options?.disabled ? { disabled: true } : {}),
1724 - };
1725 - };
1618 + const handleProjectButtonContextMenu = (event: React.MouseEvent<HTMLButtonElement>) => {
1619 + event.preventDefault();
1620 + suppressProjectClickForContextMenuRef.current = true;
1621 + void (async () => {
1622 + const api = readLocalApi();
1623 + if (!api) return;
1624
1727 - const buildTargetedItem = (
1728 - action: "rename" | "grouping" | "copy-path" | "delete",
1729 - label: string,
1730 - options?: {
1731 - destructive?: boolean;
1732 - isDisabled?: (member: SidebarProjectGroupMember) => boolean;
1733 - },
1734 - ): ContextMenuItem<string> => {
1735 - if (project.memberProjects.length === 1) {
1736 - const singleMember = project.memberProjects[0]!;
1737 - return {
1738 - ...makeLeaf(action, singleMember, {
1739 - ...(options?.destructive ? { destructive: true } : {}),
1740 - ...(options?.isDisabled?.(singleMember) ? { disabled: true } : {}),
1741 - }),
1742 - label,
1743 - ...(action === "delete" ? { icon: "trash" } : {}),
1744 - };
1625 + const actionHandlers = new Map<string, () => Promise<void> | void>();
1626 + const makeLeaf = (
1627 + action: "rename" | "grouping" | "copy-path" | "delete",
1628 + member: SidebarProjectGroupMember,
1629 + options?: {
1630 + destructive?: boolean;
1631 + disabled?: boolean;
1632 + },
1633 + ): ContextMenuItem<string> => {
1634 + const id = `${action}:${member.physicalProjectKey}`;
1635 + actionHandlers.set(id, () => {
1636 + switch (action) {
1637 + case "rename":
1638 + openProjectRenameDialog(member);
1639 + return;
1640 + case "grouping":
1641 + openProjectGroupingDialog(member);
1642 + return;
1643 + case "copy-path":
1644 + copyPathToClipboard(member.workspaceRoot, { path: member.workspaceRoot });
1645 + return;
1646 + case "delete":
1647 + return handleRemoveProject(member);
1648 }
1649 + });
1650
1651 + return {
1652 + id,
1653 + label: formatProjectMemberActionLabel(member, project.groupedProjectCount),
1654 + ...(options?.destructive ? { destructive: true } : {}),
1655 + ...(options?.disabled ? { disabled: true } : {}),
1656 + };
1657 + };
1658 +
1659 + const buildTargetedItem = (
1660 + action: "rename" | "grouping" | "copy-path" | "delete",
1661 + label: string,
1662 + options?: {
1663 + destructive?: boolean;
1664 + isDisabled?: (member: SidebarProjectGroupMember) => boolean;
1665 + },
1666 + ): ContextMenuItem<string> => {
1667 + if (project.memberProjects.length === 1) {
1668 + const singleMember = project.memberProjects[0]!;
1669 return {
1748 - id: `${action}:submenu`,
1670 + ...makeLeaf(action, singleMember, {
1671 + ...(options?.destructive ? { destructive: true } : {}),
1672 + ...(options?.isDisabled?.(singleMember) ? { disabled: true } : {}),
1673 + }),
1674 label,
1675 ...(action === "delete" ? { icon: "trash" } : {}),
1751 - children: project.memberProjects.map((member) =>
1752 - makeLeaf(action, member, {
1753 - ...(options?.destructive ? { destructive: true } : {}),
1754 - ...(options?.isDisabled?.(member) ? { disabled: true } : {}),
1755 - }),
1756 - ),
1676 };
1758 - };
1759 -
1760 - actionHandlers.set("project-settings", () => {
1761 - if (isMobile) setOpenMobile(false);
1762 - void router.navigate({
1763 - to: "/projects/$projectKey",
1764 - params: { projectKey: project.projectKey },
1765 - });
1766 - });
1767 -
1768 - const clicked = await api.contextMenu.show(
1769 - [
1770 - buildTargetedItem("rename", "Rename", {
1771 - isDisabled: (member) =>
1772 - !readEnvironmentScope(member.environmentId, AuthOrchestrationOperateScope),
1773 - }),
1774 - buildTargetedItem("grouping", "Group into..."),
1775 - buildTargetedItem("copy-path", "Copy Path"),
1776 - { id: "project-settings", label: "Project settings", icon: "settings" },
1777 - buildTargetedItem("delete", "Remove", {
1778 - destructive: true,
1779 - isDisabled: (member) =>
1780 - !readEnvironmentScope(member.environmentId, AuthOrchestrationOperateScope),
1781 - }),
1782 - ],
1783 - {
1784 - x: event.clientX,
1785 - y: event.clientY,
1786 - },
1787 - );
1788 -
1789 - if (!clicked) {
1790 - return;
1677 }
1678
1793 - await actionHandlers.get(clicked)?.();
1794 - })();
1795 - },
1796 - [
1797 - copyPathToClipboard,
1798 - handleRemoveProject,
1799 - isMobile,
1800 - openProjectGroupingDialog,
1801 - openProjectRenameDialog,
1802 - project.groupedProjectCount,
1803 - project.memberProjects,
1804 - project.projectKey,
1805 - router,
1806 - setOpenMobile,
1807 - suppressProjectClickForContextMenuRef,
1808 - ],
1809 - );
1679 + return {
1680 + id: `${action}:submenu`,
1681 + label,
1682 + ...(action === "delete" ? { icon: "trash" } : {}),
1683 + children: project.memberProjects.map((member) =>
1684 + makeLeaf(action, member, {
1685 + ...(options?.destructive ? { destructive: true } : {}),
1686 + ...(options?.isDisabled?.(member) ? { disabled: true } : {}),
1687 + }),
1688 + ),
1689 + };
1690 + };
1691
1811 - const navigateToThread = useCallback(
1812 - (threadRef: ScopedThreadRef) => {
1813 - if (useThreadSelectionStore.getState().selectedThreadKeys.size > 0) {
1814 - clearSelection();
1815 - }
1816 - setSelectionAnchor(scopedThreadKey(threadRef));
1817 - if (isMobile) {
1818 - setOpenMobile(false);
1819 - }
1820 - return router.navigate({
1821 - to: "/$environmentId/$threadId",
1822 - params: buildThreadRouteParams(threadRef),
1692 + actionHandlers.set("project-settings", () => {
1693 + if (isMobile) setOpenMobile(false);
1694 + void router.navigate({
1695 + to: "/projects/$projectKey",
1696 + params: { projectKey: project.projectKey },
1697 + });
1698 });
1824 - },
1825 - [clearSelection, isMobile, router, setOpenMobile, setSelectionAnchor],
1826 - );
1827 - const handleThreadFileDrop = useCallback(
1828 - async (threadRef: ScopedThreadRef, files: File[]) => {
1829 - const dropId = queuePendingFileDrop({ threadRef, files });
1830 - const targetPathname = router.buildLocation({
1831 - to: "/$environmentId/$threadId",
1832 - params: buildThreadRouteParams(threadRef),
1833 - }).pathname;
1834 - if (targetPathname === router.state.location.pathname) return;
1835 - try {
1836 - await navigateToThread(threadRef);
1837 - if (targetPathname !== router.state.location.pathname) {
1838 - clearPendingFileDrop(dropId);
1839 - }
1840 - } catch {
1841 - clearPendingFileDrop(dropId);
1842 - }
1843 - },
1844 - [clearPendingFileDrop, navigateToThread, queuePendingFileDrop, router],
1845 - );
1846 -
1847 - const handleThreadClick = useCallback(
1848 - (
1849 - event: React.MouseEvent,
1850 - threadRef: ScopedThreadRef,
1851 - orderedProjectThreadKeys: readonly string[],
1852 - ) => {
1853 - if (isSidebarNestedLinkClick(event.target)) return;
1854 - const isMac = isMacPlatform(navigator.platform);
1855 - const isModClick = isMac ? event.metaKey : event.ctrlKey;
1856 - const isShiftClick = event.shiftKey;
1857 - const threadKey = scopedThreadKey(threadRef);
1858 - const currentSelectionCount = useThreadSelectionStore.getState().selectedThreadKeys.size;
1699
1860 - if (isModClick) {
1861 - event.preventDefault();
1862 - toggleThreadSelection(threadKey);
1863 - return;
1864 - }
1700 + const clicked = await api.contextMenu.show(
1701 + [
1702 + buildTargetedItem("rename", "Rename", {
1703 + isDisabled: (member) =>
1704 + !readEnvironmentScope(member.environmentId, AuthOrchestrationOperateScope),
1705 + }),
1706 + buildTargetedItem("grouping", "Group into..."),
1707 + buildTargetedItem("copy-path", "Copy Path"),
1708 + { id: "project-settings", label: "Project settings", icon: "settings" },
1709 + buildTargetedItem("delete", "Remove", {
1710 + destructive: true,
1711 + isDisabled: (member) =>
1712 + !readEnvironmentScope(member.environmentId, AuthOrchestrationOperateScope),
1713 + }),
1714 + ],
1715 + {
1716 + x: event.clientX,
1717 + y: event.clientY,
1718 + },
1719 + );
1720
1866 - if (isShiftClick) {
1867 - event.preventDefault();
1868 - rangeSelectTo(threadKey, orderedProjectThreadKeys);
1721 + if (!clicked) {
1722 return;
1723 }
1724
1872 - // Ignore the trailing click of a plain double-click so it doesn't navigate
1873 - // while a double-click is starting an inline rename. Placed after the
1874 - // modifier branches so cmd/shift selection still processes every click.
1875 - if (isTrailingDoubleClick(event.detail)) {
1876 - return;
1877 - }
1725 + await actionHandlers.get(clicked)?.();
1726 + })();
1727 + };
1728
1879 - if (currentSelectionCount > 0) {
1880 - clearSelection();
1881 - }
1882 - setSelectionAnchor(threadKey);
1883 - if (isMobile) {
1884 - setOpenMobile(false);
1729 + const navigateToThread = (threadRef: ScopedThreadRef) => {
1730 + if (useThreadSelectionStore.getState().selectedThreadKeys.size > 0) {
1731 + clearSelection();
1732 + }
1733 + setSelectionAnchor(scopedThreadKey(threadRef));
1734 + if (isMobile) {
1735 + setOpenMobile(false);
1736 + }
1737 + return router.navigate({
1738 + to: "/$environmentId/$threadId",
1739 + params: buildThreadRouteParams(threadRef),
1740 + });
1741 + };
1742 + const handleThreadFileDrop = async (threadRef: ScopedThreadRef, files: File[]) => {
1743 + const dropId = queuePendingFileDrop({ threadRef, files });
1744 + const targetPathname = router.buildLocation({
1745 + to: "/$environmentId/$threadId",
1746 + params: buildThreadRouteParams(threadRef),
1747 + }).pathname;
1748 + if (targetPathname === router.state.location.pathname) return;
1749 + try {
1750 + await navigateToThread(threadRef);
1751 + if (targetPathname !== router.state.location.pathname) {
1752 + clearPendingFileDrop(dropId);
1753 }
1886 - void router.navigate({
1887 - to: "/$environmentId/$threadId",
1888 - params: buildThreadRouteParams(threadRef),
1889 - });
1890 - },
1891 - [
1892 - clearSelection,
1893 - isMobile,
1894 - rangeSelectTo,
1895 - router,
1896 - setOpenMobile,
1897 - setSelectionAnchor,
1898 - toggleThreadSelection,
1899 - ],
1900 - );
1754 + } catch {
1755 + clearPendingFileDrop(dropId);
1756 + }
1757 + };
1758
1902 - const handleMultiSelectContextMenu = useCallback(
1903 - async (position: { x: number; y: number }) => {
1904 - const api = readLocalApi();
1905 - if (!api) return;
1906 - const threadKeys = [...useThreadSelectionStore.getState().selectedThreadKeys];
1907 - if (threadKeys.length === 0) return;
1908 - const count = threadKeys.length;
1909 - const selectedThreadEntries = threadKeys.flatMap((threadKey) => {
1910 - const threadRef = parseScopedThreadKey(threadKey);
1911 - const thread = threadRef ? readThreadShell(threadRef) : null;
1912 - return threadRef && thread ? [{ threadKey, threadRef, thread }] : [];
1913 - });
1914 - const hasRunningThread = selectedThreadEntries.some(
1915 - ({ thread }) => !threadRuntimeCanArchive(thread.runtime),
1916 - );
1917 - const canOperateSelection = selectedThreadEntries.every(({ threadRef }) =>
1918 - readEnvironmentScope(threadRef.environmentId, AuthOrchestrationOperateScope),
1919 - );
1759 + const handleThreadClick = (
1760 + event: React.MouseEvent,
1761 + threadRef: ScopedThreadRef,
1762 + orderedProjectThreadKeys: readonly string[],
1763 + ) => {
1764 + if (isSidebarNestedLinkClick(event.target)) return;
1765 + const isMac = isMacPlatform(navigator.platform);
1766 + const isModClick = isMac ? event.metaKey : event.ctrlKey;
1767 + const isShiftClick = event.shiftKey;
1768 + const threadKey = scopedThreadKey(threadRef);
1769 + const currentSelectionCount = useThreadSelectionStore.getState().selectedThreadKeys.size;
1770 +
1771 + if (isModClick) {
1772 + event.preventDefault();
1773 + toggleThreadSelection(threadKey);
1774 + return;
1775 + }
1776
1921 - const clicked = await api.contextMenu.show(
1922 - buildMultiSelectThreadContextMenuItems({ count, hasRunningThread }).map((item) =>
1923 - item.id === "archive" || item.id === "delete"
1924 - ? { ...item, disabled: item.disabled || !canOperateSelection }
1925 - : item,
1926 - ),
1927 - position,
1928 - );
1777 + if (isShiftClick) {
1778 + event.preventDefault();
1779 + rangeSelectTo(threadKey, orderedProjectThreadKeys);
1780 + return;
1781 + }
1782
1930 - if (clicked === "mark-unread") {
1931 - for (const { threadRef } of selectedThreadEntries) {
1932 - markThreadUnread(threadRef);
1933 - }
1934 - clearSelection();
1935 - return;
1936 - }
1783 + // Ignore the trailing click of a plain double-click so it doesn't navigate
1784 + // while a double-click is starting an inline rename. Placed after the
1785 + // modifier branches so cmd/shift selection still processes every click.
1786 + if (isTrailingDoubleClick(event.detail)) {
1787 + return;
1788 + }
1789
1938 - if (
1939 - (clicked === "archive" || clicked === "delete") &&
1940 - !selectedThreadEntries.every(({ threadRef }) =>
1941 - checkTaskPermission(threadRef.environmentId),
1942 - )
1943 - ) {
1944 - return;
1945 - }
1790 + if (currentSelectionCount > 0) {
1791 + clearSelection();
1792 + }
1793 + setSelectionAnchor(threadKey);
1794 + if (isMobile) {
1795 + setOpenMobile(false);
1796 + }
1797 + void router.navigate({
1798 + to: "/$environmentId/$threadId",
1799 + params: buildThreadRouteParams(threadRef),
1800 + });
1801 + };
1802
1947 - if (clicked === "archive") {
1948 - if (appSettingsConfirmThreadArchive) {
1949 - const confirmed = await api.dialogs.confirm(
1950 - `Archive ${count} thread${count === 1 ? "" : "s"}?`,
1951 - );
1952 - if (!confirmed) return;
1953 - }
1954 - if (
1955 - !selectedThreadEntries.every(({ threadRef }) =>
1956 - checkTaskPermission(threadRef.environmentId),
1957 - )
1958 - ) {
1959 - return;
1960 - }
1803 + const handleMultiSelectContextMenu = async (position: { x: number; y: number }) => {
1804 + const api = readLocalApi();
1805 + if (!api) return;
1806 + const threadKeys = [...useThreadSelectionStore.getState().selectedThreadKeys];
1807 + if (threadKeys.length === 0) return;
1808 + const count = threadKeys.length;
1809 + const selectedThreadEntries = threadKeys.flatMap((threadKey) => {
1810 + const threadRef = parseScopedThreadKey(threadKey);
1811 + const thread = threadRef ? readThreadShell(threadRef) : null;
1812 + return threadRef && thread ? [{ threadKey, threadRef, thread }] : [];
1813 + });
1814 + const hasRunningThread = selectedThreadEntries.some(
1815 + ({ thread }) => !threadRuntimeCanArchive(thread.runtime),
1816 + );
1817 + const canOperateSelection = selectedThreadEntries.every(({ threadRef }) =>
1818 + readEnvironmentScope(threadRef.environmentId, AuthOrchestrationOperateScope),
1819 + );
1820
1962 - const archiveOutcome = await archiveSelectedThreadEntries({
1963 - entries: selectedThreadEntries,
1964 - archive: ({ threadRef }, onArchived) => archiveThread(threadRef, { onArchived }),
1965 - });
1966 - for (const failure of archiveOutcome.followupFailures) {
1967 - if (isAtomCommandInterrupted(failure)) continue;
1968 - const error = squashAtomCommandFailure(failure);
1969 - toastManager.add(
1970 - stackedThreadToast({
1971 - type: "error",
1972 - title: "Thread archived, but navigation failed",
1973 - description: error instanceof Error ? error.message : "An error occurred.",
1974 - }),
1975 - );
1976 - }
1977 - if (archiveOutcome.mutationFailure) {
1978 - removeFromSelection(archiveOutcome.archivedThreadKeys);
1979 - if (!isAtomCommandInterrupted(archiveOutcome.mutationFailure)) {
1980 - const error = squashAtomCommandFailure(archiveOutcome.mutationFailure);
1981 - toastManager.add(
1982 - stackedThreadToast({
1983 - type: "error",
1984 - title: "Failed to archive threads",
1985 - description: error instanceof Error ? error.message : "An error occurred.",
1986 - }),
1987 - );
1988 - }
1989 - return;
1990 - }
1991 - removeFromSelection(threadKeys);
1992 - return;
1821 + const clicked = await api.contextMenu.show(
1822 + buildMultiSelectThreadContextMenuItems({ count, hasRunningThread }).map((item) =>
1823 + item.id === "archive" || item.id === "delete"
1824 + ? { ...item, disabled: item.disabled || !canOperateSelection }
1825 + : item,
1826 + ),
1827 + position,
1828 + );
1829 +
1830 + if (clicked === "mark-unread") {
1831 + for (const { threadRef } of selectedThreadEntries) {
1832 + markThreadUnread(threadRef);
1833 }
1834 + clearSelection();
1835 + return;
1836 + }
1837
1995 - if (clicked !== "delete") return;
1838 + if (
1839 + (clicked === "archive" || clicked === "delete") &&
1840 + !selectedThreadEntries.every(({ threadRef }) => checkTaskPermission(threadRef.environmentId))
1841 + ) {
1842 + return;
1843 + }
1844
1997 - if (appSettingsConfirmThreadDelete) {
1845 + if (clicked === "archive") {
1846 + if (appSettingsConfirmThreadArchive) {
1847 const confirmed = await api.dialogs.confirm(
1999 - [
2000 - `Delete ${count} thread${count === 1 ? "" : "s"}?`,
2001 - "This permanently clears conversation history for these threads.",
2002 - ].join("\n"),
2003 - { variant: "destructive" },
1848 + `Archive ${count} thread${count === 1 ? "" : "s"}?`,
1849 );
1850 if (!confirmed) return;
1851 }
@@ -2012,200 +1857,232 @@ const SidebarProjectItem = memo(function SidebarProjectItem(props: SidebarProjec
1857 return;
1858 }
1859
2015 - const { deletedThreadKeys, firstFailure } = await deleteSelectedThreadEntries({
1860 + const archiveOutcome = await archiveSelectedThreadEntries({
1861 entries: selectedThreadEntries,
2017 - delete: ({ threadRef }, deletedThreadKeys) =>
2018 - deleteThread(threadRef, { deletedThreadKeys }),
1862 + archive: ({ threadRef }, onArchived) => archiveThread(threadRef, { onArchived }),
1863 });
2020 - if (firstFailure !== null) {
2021 - const firstError = squashAtomCommandFailure(firstFailure);
1864 + for (const failure of archiveOutcome.followupFailures) {
1865 + if (isAtomCommandInterrupted(failure)) continue;
1866 + const error = squashAtomCommandFailure(failure);
1867 toastManager.add(
1868 stackedThreadToast({
1869 type: "error",
2025 - title: "Failed to delete threads",
2026 - description: firstError instanceof Error ? firstError.message : "An error occurred.",
1870 + title: "Thread archived, but navigation failed",
1871 + description: error instanceof Error ? error.message : "An error occurred.",
1872 }),
1873 );
1874 }
2030 - removeFromSelection(
2031 - getThreadKeysToDeselectAfterDelete(threadKeys, deletedThreadKeys, (threadKey) => {
2032 - const threadRef = parseScopedThreadKey(threadKey);
2033 - return threadRef !== null && readThreadShell(threadRef) !== null;
2034 - }),
2035 - );
2036 - },
2037 - [
2038 - appSettingsConfirmThreadArchive,
2039 - appSettingsConfirmThreadDelete,
2040 - archiveThread,
2041 - clearSelection,
2042 - deleteThread,
2043 - markThreadUnread,
2044 - removeFromSelection,
2045 - ],
2046 - );
2047 -
2048 - const createThreadForProjectMember = useCallback(
2049 - (member: SidebarProjectGroupMember) => {
2050 - if (isMobile) {
2051 - setOpenMobile(false);
2052 - }
2053 - void (async () => {
2054 - const result = await settlePromise(() =>
2055 - handleNewThread(scopeProjectRef(member.environmentId, member.id)),
2056 - );
2057 - if (result._tag === "Failure") {
2058 - const error = squashAtomCommandFailure(result);
1875 + if (archiveOutcome.mutationFailure) {
1876 + removeFromSelection(archiveOutcome.archivedThreadKeys);
1877 + if (!isAtomCommandInterrupted(archiveOutcome.mutationFailure)) {
1878 + const error = squashAtomCommandFailure(archiveOutcome.mutationFailure);
1879 toastManager.add(
1880 stackedThreadToast({
1881 type: "error",
2062 - title: "Could not create thread",
1882 + title: "Failed to archive threads",
1883 description: error instanceof Error ? error.message : "An error occurred.",
1884 }),
1885 );
1886 }
2067 - })();
2068 - },
2069 - [handleNewThread, isMobile, setOpenMobile],
2070 - );
2071 -
2072 - const handleCreateThreadClick = useCallback(
2073 - (event: React.MouseEvent<HTMLButtonElement>) => {
2074 - event.preventDefault();
2075 - event.stopPropagation();
2076 -
2077 - if (project.memberProjects.length === 1) {
2078 - createThreadForProjectMember(project.memberProjects[0]!);
1887 return;
1888 }
1889 + removeFromSelection(threadKeys);
1890 + return;
1891 + }
1892
2082 - void (async () => {
2083 - const api = readLocalApi();
2084 - if (!api) {
2085 - return;
2086 - }
2087 - const clickedResult = await settlePromise(() =>
2088 - api.contextMenu.show(
2089 - project.memberProjects.map((member) => ({
2090 - id: member.physicalProjectKey,
2091 - label: formatProjectMemberActionLabel(member, project.groupedProjectCount),
2092 - })),
2093 - {
2094 - x: event.clientX,
2095 - y: event.clientY,
2096 - },
2097 - ),
2098 - );
2099 - if (clickedResult._tag === "Failure") {
2100 - const error = squashAtomCommandFailure(clickedResult);
2101 - toastManager.add(
2102 - stackedThreadToast({
2103 - type: "error",
2104 - title: "Could not choose environment",
2105 - description: error instanceof Error ? error.message : "An error occurred.",
2106 - }),
2107 - );
2108 - return;
2109 - }
2110 - const clicked = clickedResult.value;
2111 - if (!clicked) {
2112 - return;
2113 - }
2114 - const targetMember = project.memberProjects.find(
2115 - (member) => member.physicalProjectKey === clicked,
2116 - );
2117 - if (!targetMember) {
2118 - return;
2119 - }
2120 - createThreadForProjectMember(targetMember);
2121 - })();
2122 - },
2123 - [createThreadForProjectMember, project.groupedProjectCount, project.memberProjects],
2124 - );
1893 + if (clicked !== "delete") return;
1894
2126 - const attemptArchiveThread = useCallback(
2127 - async (threadRef: ScopedThreadRef) => {
2128 - if (!checkTaskPermission(threadRef.environmentId)) return;
2129 - const result = await archiveThread(threadRef);
2130 - if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) {
1895 + if (appSettingsConfirmThreadDelete) {
1896 + const confirmed = await api.dialogs.confirm(
1897 + [
1898 + `Delete ${count} thread${count === 1 ? "" : "s"}?`,
1899 + "This permanently clears conversation history for these threads.",
1900 + ].join("\n"),
1901 + { variant: "destructive" },
1902 + );
1903 + if (!confirmed) return;
1904 + }
1905 + if (
1906 + !selectedThreadEntries.every(({ threadRef }) => checkTaskPermission(threadRef.environmentId))
1907 + ) {
1908 + return;
1909 + }
1910 +
1911 + const { deletedThreadKeys, firstFailure } = await deleteSelectedThreadEntries({
1912 + entries: selectedThreadEntries,
1913 + delete: ({ threadRef }, deletedThreadKeys) => deleteThread(threadRef, { deletedThreadKeys }),
1914 + });
1915 + if (firstFailure !== null) {
1916 + const firstError = squashAtomCommandFailure(firstFailure);
1917 + toastManager.add(
1918 + stackedThreadToast({
1919 + type: "error",
1920 + title: "Failed to delete threads",
1921 + description: firstError instanceof Error ? firstError.message : "An error occurred.",
1922 + }),
1923 + );
1924 + }
1925 + removeFromSelection(
1926 + getThreadKeysToDeselectAfterDelete(threadKeys, deletedThreadKeys, (threadKey) => {
1927 + const threadRef = parseScopedThreadKey(threadKey);
1928 + return threadRef !== null && readThreadShell(threadRef) !== null;
1929 + }),
1930 + );
1931 + };
1932 +
1933 + const createThreadForProjectMember = (member: SidebarProjectGroupMember) => {
1934 + if (isMobile) {
1935 + setOpenMobile(false);
1936 + }
1937 + void (async () => {
1938 + const result = await settlePromise(() =>
1939 + handleNewThread(scopeProjectRef(member.environmentId, member.id)),
1940 + );
1941 + if (result._tag === "Failure") {
1942 const error = squashAtomCommandFailure(result);
1943 toastManager.add(
1944 stackedThreadToast({
1945 type: "error",
2135 - title: "Failed to archive thread",
1946 + title: "Could not create thread",
1947 description: error instanceof Error ? error.message : "An error occurred.",
1948 }),
1949 );
1950 }
2140 - },
2141 - [archiveThread],
2142 - );
2143 -
2144 - const cancelRename = useCallback(() => {
2145 - setRenamingThreadKey(null);
2146 - renamingInputRef.current = null;
2147 - }, []);
1951 + })();
1952 + };
1953
2149 - const startThreadRename = useCallback((threadKey: string, title: string) => {
2150 - const threadRef = parseScopedThreadKey(threadKey);
2151 - if (!threadRef || !checkTaskPermission(threadRef.environmentId)) return;
2152 - setRenamingThreadKey(threadKey);
2153 - setRenamingTitle(title);
2154 - renamingCommittedRef.current = false;
2155 - }, []);
1954 + const handleCreateThreadClick = (event: React.MouseEvent<HTMLButtonElement>) => {
1955 + event.preventDefault();
1956 + event.stopPropagation();
1957
2157 - const commitRename = useCallback(
2158 - async (threadRef: ScopedThreadRef, newTitle: string, originalTitle: string) => {
2159 - const threadKey = scopedThreadKey(threadRef);
2160 - const finishRename = () => {
2161 - setRenamingThreadKey((current) => {
2162 - if (current !== threadKey) return current;
2163 - renamingInputRef.current = null;
2164 - return null;
2165 - });
2166 - };
1958 + if (project.memberProjects.length === 1) {
1959 + createThreadForProjectMember(project.memberProjects[0]!);
1960 + return;
1961 + }
1962
2168 - const trimmed = newTitle.trim();
2169 - if (trimmed.length === 0) {
2170 - toastManager.add({
2171 - type: "warning",
2172 - title: "Thread title cannot be empty",
2173 - });
2174 - finishRename();
2175 - return;
2176 - }
2177 - if (trimmed === originalTitle) {
2178 - finishRename();
1963 + void (async () => {
1964 + const api = readLocalApi();
1965 + if (!api) {
1966 return;
1967 }
2181 - const result = await updateThreadMetadata({
2182 - environmentId: threadRef.environmentId,
2183 - input: {
2184 - threadId: threadRef.threadId,
2185 - title: trimmed,
2186 - },
2187 - });
2188 - if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) {
2189 - const error = squashAtomCommandFailure(result);
1968 + const clickedResult = await settlePromise(() =>
1969 + api.contextMenu.show(
1970 + project.memberProjects.map((member) => ({
1971 + id: member.physicalProjectKey,
1972 + label: formatProjectMemberActionLabel(member, project.groupedProjectCount),
1973 + })),
1974 + {
1975 + x: event.clientX,
1976 + y: event.clientY,
1977 + },
1978 + ),
1979 + );
1980 + if (clickedResult._tag === "Failure") {
1981 + const error = squashAtomCommandFailure(clickedResult);
1982 toastManager.add(
1983 stackedThreadToast({
1984 type: "error",
2193 - title: "Failed to rename thread",
1985 + title: "Could not choose environment",
1986 description: error instanceof Error ? error.message : "An error occurred.",
1987 }),
1988 );
1989 + return;
1990 + }
1991 + const clicked = clickedResult.value;
1992 + if (!clicked) {
1993 + return;
1994 + }
1995 + const targetMember = project.memberProjects.find(
1996 + (member) => member.physicalProjectKey === clicked,
1997 + );
1998 + if (!targetMember) {
1999 + return;
2000 }
2001 + createThreadForProjectMember(targetMember);
2002 + })();
2003 + };
2004 +
2005 + const attemptArchiveThread = async (threadRef: ScopedThreadRef) => {
2006 + if (!checkTaskPermission(threadRef.environmentId)) return;
2007 + const result = await archiveThread(threadRef);
2008 + if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) {
2009 + const error = squashAtomCommandFailure(result);
2010 + toastManager.add(
2011 + stackedThreadToast({
2012 + type: "error",
2013 + title: "Failed to archive thread",
2014 + description: error instanceof Error ? error.message : "An error occurred.",
2015 + }),
2016 + );
2017 + }
2018 + };
2019 +
2020 + const cancelRename = () => {
2021 + setRenamingThreadKey(null);
2022 + renamingInputRef.current = null;
2023 + };
2024 +
2025 + const startThreadRename = (threadKey: string, title: string) => {
2026 + const threadRef = parseScopedThreadKey(threadKey);
2027 + if (!threadRef || !checkTaskPermission(threadRef.environmentId)) return;
2028 + setRenamingThreadKey(threadKey);
2029 + setRenamingTitle(title);
2030 + renamingCommittedRef.current = false;
2031 + };
2032 +
2033 + const commitRename = async (
2034 + threadRef: ScopedThreadRef,
2035 + newTitle: string,
2036 + originalTitle: string,
2037 + ) => {
2038 + const threadKey = scopedThreadKey(threadRef);
2039 + const finishRename = () => {
2040 + setRenamingThreadKey((current) => {
2041 + if (current !== threadKey) return current;
2042 + renamingInputRef.current = null;
2043 + return null;
2044 + });
2045 + };
2046 +
2047 + const trimmed = newTitle.trim();
2048 + if (trimmed.length === 0) {
2049 + toastManager.add({
2050 + type: "warning",
2051 + title: "Thread title cannot be empty",
2052 + });
2053 finishRename();
2199 - },
2200 - [updateThreadMetadata],
2201 - );
2054 + return;
2055 + }
2056 + if (trimmed === originalTitle) {
2057 + finishRename();
2058 + return;
2059 + }
2060 + const result = await updateThreadMetadata({
2061 + environmentId: threadRef.environmentId,
2062 + input: {
2063 + threadId: threadRef.threadId,
2064 + title: trimmed,
2065 + },
2066 + });
2067 + if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) {
2068 + const error = squashAtomCommandFailure(result);
2069 + toastManager.add(
2070 + stackedThreadToast({
2071 + type: "error",
2072 + title: "Failed to rename thread",
2073 + description: error instanceof Error ? error.message : "An error occurred.",
2074 + }),
2075 + );
2076 + }
2077 + finishRename();
2078 + };
2079
2203 - const closeProjectRenameDialog = useCallback(() => {
2080 + const closeProjectRenameDialog = () => {
2081 setProjectRenameTarget(null);
2082 setProjectRenameTitle("");
2206 - }, []);
2083 + };
2084
2208 - const submitProjectRename = useCallback(async () => {
2085 + const submitProjectRename = async () => {
2086 if (!projectRenameTarget) {
2087 return;
2088 }
@@ -2243,14 +2120,14 @@ const SidebarProjectItem = memo(function SidebarProjectItem(props: SidebarProjec
2120 }),
2121 );
2122 }
2246 - }, [closeProjectRenameDialog, projectRenameTarget, projectRenameTitle, updateProject]);
2123 + };
2124
2248 - const closeProjectGroupingDialog = useCallback(() => {
2125 + const closeProjectGroupingDialog = () => {
2126 setProjectGroupingTarget(null);
2127 setProjectGroupingSelection("inherit");
2251 - }, []);
2128 + };
2129
2253 - const saveProjectGroupingPreference = useCallback(() => {
2130 + const saveProjectGroupingPreference = () => {
2131 if (!projectGroupingTarget) {
2132 return;
2133 }
@@ -2268,20 +2145,16 @@ const SidebarProjectItem = memo(function SidebarProjectItem(props: SidebarProjec
2145 sidebarProjectGroupingOverrides: nextOverrides,
2146 });
2147 closeProjectGroupingDialog();
2271 - }, [
2272 - closeProjectGroupingDialog,
2273 - projectGroupingSelection,
2274 - projectGroupingSettings.sidebarProjectGroupingOverrides,
2275 - projectGroupingTarget,
2276 - updateSettings,
2277 - ]);
2148 + };
2149
2279 - const handleThreadContextMenu = useCallback(
2150 + // Every thread row receives this, so it keeps one identity while the thread
2151 + // list changes instead of re-rendering all of them.
2152 + const handleThreadContextMenu = useStableCallback(
2153 async (threadRef: ScopedThreadRef, position: { x: number; y: number }) => {
2154 const api = readLocalApi();
2155 if (!api) return;
2156 const threadKey = scopedThreadKey(threadRef);
2284 - const thread = sidebarThreadByKeyRef.current.get(threadKey) ?? null;
2157 + const thread = sidebarThreadByKey.get(threadKey) ?? null;
2158 if (!thread) return;
2159 const threadProject = memberProjectByScopedKey.get(
2160 scopedProjectKey(scopeProjectRef(thread.environmentId, thread.projectId)),
@@ -2398,21 +2271,6 @@ const SidebarProjectItem = memo(function SidebarProjectItem(props: SidebarProjec
2271 );
2272 }
2273 },
2401 - [
2402 - appSettingsConfirmThreadDelete,
2403 - copyPathToClipboard,
2404 - copyThreadIdToClipboard,
2405 - deleteThread,
2406 - handleNewThread,
2407 - isMobile,
2408 - markThreadUnread,
2409 - memberProjectByScopedKey,
2410 - project.projectKey,
2411 - project.workspaceRoot,
2412 - router,
2413 - setOpenMobile,
2414 - startThreadRename,
2415 - ],
2274 );
2275
2276 return (
@@ -2698,7 +2556,7 @@ function LocalSecondaryStatus() {
2556 // exist; the hook polls because the bridge has no change event.
2557 const secondaries = useDesktopLocalBootstraps();
2558
2701 - const localEnvByUrl = useMemo(() => {
2559 + const localEnvByUrl = (() => {
2560 const map = new Map<string, { phase: string; error: string | null }>();
2561 for (const environment of environments) {
2562 if (
@@ -2712,7 +2570,7 @@ function LocalSecondaryStatus() {
2570 }
2571 }
2572 return map;
2715 - }, [environments]);
2573 + })();
2574
2575 const connecting: string[] = [];
2576 const failed: Array<{ label: string; error: string | null }> = [];
@@ -2777,19 +2635,16 @@ function ProjectSortMenu({
2635 onThreadSortOrderChange: (sortOrder: SidebarThreadSortOrder) => void;
2636 onThreadPreviewCountChange: (count: SidebarThreadPreviewCount) => void;
2637 }) {
2780 - const handleThreadPreviewCountChange = useCallback(
2781 - (nextValue: number | null) => {
2782 - if (nextValue === null) {
2783 - return;
2784 - }
2638 + const handleThreadPreviewCountChange = (nextValue: number | null) => {
2639 + if (nextValue === null) {
2640 + return;
2641 + }
2642
2786 - const clampedValue = clampSidebarThreadPreviewCount(nextValue);
2787 - if (clampedValue !== threadPreviewCount) {
2788 - onThreadPreviewCountChange(clampedValue);
2789 - }
2790 - },
2791 - [onThreadPreviewCountChange, threadPreviewCount],
2792 - );
2643 + const clampedValue = clampSidebarThreadPreviewCount(nextValue);
2644 + if (clampedValue !== threadPreviewCount) {
2645 + onThreadPreviewCountChange(clampedValue);
2646 + }
2647 + };
2648
2649 return (
2650 <Menu>
@@ -2944,6 +2799,7 @@ interface SidebarProjectsContentProps {
2799 deleteThread: ReturnType<typeof useThreadActions>["deleteThread"];
2800 markThreadUnread: ReturnType<typeof useThreadActions>["markThreadUnread"];
2801 sortedProjects: readonly SidebarProjectSnapshot[];
2802 + sortedProjectKeys: string[];
2803 expandedThreadListsByProject: ReadonlySet<string>;
2804 activeRouteProjectKey: string | null;
2805 routeThreadKey: string | null;
@@ -2987,6 +2843,7 @@ const SidebarProjectsContent = memo(function SidebarProjectsContent(
2843 deleteThread,
2844 markThreadUnread,
2845 sortedProjects,
2846 + sortedProjectKeys,
2847 expandedThreadListsByProject,
2848 activeRouteProjectKey,
2849 routeThreadKey,
@@ -3004,24 +2861,15 @@ const SidebarProjectsContent = memo(function SidebarProjectsContent(
2861 projectsLength,
2862 } = props;
2863
3007 - const handleProjectSortOrderChange = useCallback(
3008 - (sortOrder: SidebarProjectSortOrder) => {
3009 - updateSettings({ sidebarProjectSortOrder: sortOrder });
3010 - },
3011 - [updateSettings],
3012 - );
3013 - const handleThreadSortOrderChange = useCallback(
3014 - (sortOrder: SidebarThreadSortOrder) => {
3015 - updateSettings({ sidebarThreadSortOrder: sortOrder });
3016 - },
3017 - [updateSettings],
3018 - );
3019 - const handleThreadPreviewCountChange = useCallback(
3020 - (count: SidebarThreadPreviewCount) => {
3021 - updateSettings({ sidebarThreadPreviewCount: count });
3022 - },
3023 - [updateSettings],
3024 - );
2864 + const handleProjectSortOrderChange = (sortOrder: SidebarProjectSortOrder) => {
2865 + updateSettings({ sidebarProjectSortOrder: sortOrder });
2866 + };
2867 + const handleThreadSortOrderChange = (sortOrder: SidebarThreadSortOrder) => {
2868 + updateSettings({ sidebarThreadSortOrder: sortOrder });
2869 + };
2870 + const handleThreadPreviewCountChange = (count: SidebarThreadPreviewCount) => {
2871 + updateSettings({ sidebarThreadPreviewCount: count });
2872 + };
2873
2874 return (
2875 <SidebarContent
@@ -3100,16 +2948,13 @@ const SidebarProjectsContent = memo(function SidebarProjectsContent(
2948 <DndContext
2949 sensors={projectDnDSensors}
2950 collisionDetection={projectCollisionDetection}
3103 - modifiers={[restrictToVerticalAxis, restrictToFirstScrollableAncestor]}
2951 + modifiers={PROJECT_DND_MODIFIERS}
2952 onDragStart={handleProjectDragStart}
2953 onDragEnd={handleProjectDragEnd}
2954 onDragCancel={handleProjectDragCancel}
2955 >
2956 <SidebarMenu>
3109 - <SortableContext
3110 - items={sortedProjects.map((project) => project.projectKey)}
3111 - strategy={verticalListSortingStrategy}
3112 - >
2957 + <SortableContext items={sortedProjectKeys} strategy={verticalListSortingStrategy}>
2958 {sortedProjects.map((project) => (
2959 <SortableProjectItem key={project.projectKey} projectId={project.projectKey}>
2960 {(dragHandleProps) => (
@@ -3173,24 +3018,253 @@ const SidebarProjectsContent = memo(function SidebarProjectsContent(
3018 </SidebarMenu>
3019 )}
3020
3176 - {projectsLength === 0 && (
3177 - <div className="px-2 pt-4 text-center text-secondary-label text-xs">No projects yet</div>
3178 - )}
3179 - </SidebarGroup>
3180 - </SidebarContent>
3021 + {projectsLength === 0 && (
3022 + <div className="px-2 pt-4 text-center text-secondary-label text-xs">No projects yet</div>
3023 + )}
3024 + </SidebarGroup>
3025 + </SidebarContent>
3026 + );
3027 +});
3028 +
3029 +const PROJECT_POINTER_SENSOR_OPTIONS = { activationConstraint: { distance: 6 } };
3030 +const PROJECT_DND_MODIFIERS = [restrictToVerticalAxis, restrictToFirstScrollableAncestor];
3031 +
3032 +const projectCollisionDetection: CollisionDetection = (args) => {
3033 + const pointerCollisions = pointerWithin(args);
3034 + if (pointerCollisions.length > 0) {
3035 + return pointerCollisions;
3036 + }
3037 +
3038 + return closestCorners(args);
3039 +};
3040 +
3041 +function openAddProjectCommandPalette() {
3042 + openCommandPalette({ open: "add-project" });
3043 +}
3044 +
3045 +// Project and thread derivations live in their own hooks so they reach
3046 +// LegacySidebar frozen and cached on their real inputs; inline, its later hook
3047 +// calls made the compiler recompute them, and the props of every row with them.
3048 +function useLegacySidebarProjects() {
3049 + "use memo";
3050 + const projects = useProjects();
3051 + const projectOrder = useUiStateStore((store) => store.projectOrder);
3052 + const projectGroupingSettings = useClientSettings(selectProjectGroupingSettings);
3053 + const { environments } = useEnvironments();
3054 + const primaryEnvironmentId = usePrimaryEnvironmentId();
3055 + const environmentLabelById = new Map(
3056 + environments.map((environment) => [environment.environmentId, environment.label] as const),
3057 + );
3058 + const desktopLocalEnvironmentIds = new Set(
3059 + environments
3060 + .filter((environment) => isDesktopLocalConnectionTarget(environment.entry.target))
3061 + .map((environment) => environment.environmentId),
3062 + );
3063 + const wslEnvironmentIds = new Set(
3064 + environments
3065 + .filter((environment) => isWslConnectionTarget(environment.entry.target))
3066 + .map((environment) => environment.environmentId),
3067 + );
3068 + const orderedProjects = orderItemsByPreferredIds({
3069 + items: projects,
3070 + preferredIds: projectOrder,
3071 + getId: getProjectOrderKey,
3072 + getPreferenceIds: (project) => [
3073 + getProjectOrderKey(project),
3074 + legacyProjectCwdPreferenceKey(project.workspaceRoot),
3075 + ],
3076 + });
3077 + const physicalToLogicalKey = buildPhysicalToLogicalProjectKeyMap({
3078 + projects: orderedProjects,
3079 + settings: projectGroupingSettings,
3080 + primaryEnvironmentId,
3081 + });
3082 + const projectPhysicalKeyByScopedRef = new Map(
3083 + orderedProjects.map((project) => [
3084 + scopedProjectKey(scopeProjectRef(project.environmentId, project.id)),
3085 + derivePhysicalProjectKey(project),
3086 + ]),
3087 + );
3088 + const sidebarProjects: SidebarProjectSnapshot[] = buildSidebarProjectSnapshots({
3089 + projects: orderedProjects,
3090 + settings: projectGroupingSettings,
3091 + primaryEnvironmentId,
3092 + resolveEnvironmentLabel: (environmentId) => environmentLabelById.get(environmentId) ?? null,
3093 + isDesktopLocalEnvironment: (environmentId) => desktopLocalEnvironmentIds.has(environmentId),
3094 + isWslEnvironment: (environmentId) => wslEnvironmentIds.has(environmentId),
3095 + });
3096 + return {
3097 + projectsLength: projects.length,
3098 + orderedProjects,
3099 + physicalToLogicalKey,
3100 + projectPhysicalKeyByScopedRef,
3101 + sidebarProjects,
3102 + };
3103 +}
3104 +
3105 +// Kept apart from useLegacySidebarProjects so a thread change re-sorts the
3106 +// projects without rebuilding their snapshots, which every project row keys on.
3107 +function useSortedLegacySidebarProjects(input: {
3108 + sidebarProjects: readonly SidebarProjectSnapshot[];
3109 + physicalToLogicalKey: ReadonlyMap<string, string>;
3110 + projectPhysicalKeyByScopedRef: ReadonlyMap<string, string>;
3111 + sidebarProjectSortOrder: SidebarProjectSortOrder;
3112 +}) {
3113 + "use memo";
3114 + const {
3115 + sidebarProjects,
3116 + physicalToLogicalKey,
3117 + projectPhysicalKeyByScopedRef,
3118 + sidebarProjectSortOrder,
3119 + } = input;
3120 + const sidebarThreads = useThreadShells();
3121 + const sidebarProjectByKey = new Map(
3122 + sidebarProjects.map((project) => [project.projectKey, project] as const),
3123 + );
3124 + const sortableProjects = sidebarProjects.map((project) => ({
3125 + ...project,
3126 + id: project.projectKey,
3127 + }));
3128 + const sortableThreads = sidebarThreads
3129 + .filter((thread) => thread.archivedAt === null)
3130 + .map((thread) => {
3131 + const physicalKey =
3132 + projectPhysicalKeyByScopedRef.get(
3133 + scopedProjectKey(scopeProjectRef(thread.environmentId, thread.projectId)),
3134 + ) ?? scopedProjectKey(scopeProjectRef(thread.environmentId, thread.projectId));
3135 + return {
3136 + ...thread,
3137 + projectId: (physicalToLogicalKey.get(physicalKey) ?? physicalKey) as ProjectId,
3138 + };
3139 + });
3140 + const sortedProjects = sortProjectsForSidebar(
3141 + sortableProjects,
3142 + sortableThreads,
3143 + sidebarProjectSortOrder,
3144 + ).flatMap((project) => {
3145 + const resolvedProject = sidebarProjectByKey.get(project.id);
3146 + return resolvedProject ? [resolvedProject] : [];
3147 + });
3148 + return {
3149 + sortedProjects,
3150 + sortedProjectKeys: sortedProjects.map((project) => project.projectKey),
3151 + };
3152 +}
3153 +
3154 +function useLegacySidebarThreads(input: {
3155 + sortedProjects: readonly SidebarProjectSnapshot[];
3156 + physicalToLogicalKey: ReadonlyMap<string, string>;
3157 + projectPhysicalKeyByScopedRef: ReadonlyMap<string, string>;
3158 + routeThreadKey: string | null;
3159 + sidebarThreadSortOrder: SidebarThreadSortOrder;
3160 + sidebarThreadPreviewCount: number;
3161 + expandedThreadListsByProject: ReadonlySet<string>;
3162 +}) {
3163 + "use memo";
3164 + const {
3165 + sortedProjects,
3166 + physicalToLogicalKey,
3167 + projectPhysicalKeyByScopedRef,
3168 + routeThreadKey,
3169 + sidebarThreadSortOrder,
3170 + sidebarThreadPreviewCount,
3171 + expandedThreadListsByProject,
3172 + } = input;
3173 + const sidebarThreads = useThreadShells();
3174 + const projectExpandedById = useUiStateStore((store) => store.projectExpandedById);
3175 + const sidebarThreadByKey = new Map(
3176 + sidebarThreads.map(
3177 + (thread) =>
3178 + [scopedThreadKey(scopeThreadRef(thread.environmentId, thread.id)), thread] as const,
3179 + ),
3180 );
3182 -});
3181 + const logicalProjectKeyForThread = (thread: SidebarThreadSummary) => {
3182 + const physicalKey =
3183 + projectPhysicalKeyByScopedRef.get(
3184 + scopedProjectKey(scopeProjectRef(thread.environmentId, thread.projectId)),
3185 + ) ?? scopedProjectKey(scopeProjectRef(thread.environmentId, thread.projectId));
3186 + return physicalToLogicalKey.get(physicalKey) ?? physicalKey;
3187 + };
3188 + const activeRouteThread = routeThreadKey ? sidebarThreadByKey.get(routeThreadKey) : undefined;
3189 + const activeRouteProjectKey = activeRouteThread
3190 + ? logicalProjectKeyForThread(activeRouteThread)
3191 + : null;
3192 + const threadsByProjectKey = new Map<string, SidebarThreadSummary[]>();
3193 + for (const thread of sidebarThreads) {
3194 + const logicalKey = logicalProjectKeyForThread(thread);
3195 + const existing = threadsByProjectKey.get(logicalKey);
3196 + if (existing) {
3197 + existing.push(thread);
3198 + } else {
3199 + threadsByProjectKey.set(logicalKey, [thread]);
3200 + }
3201 + }
3202 + const visibleSidebarThreadKeys = sortedProjects.flatMap((project) => {
3203 + const projectThreads = sortThreads(
3204 + (threadsByProjectKey.get(project.projectKey) ?? []).filter(
3205 + (thread) => thread.archivedAt === null,
3206 + ),
3207 + sidebarThreadSortOrder,
3208 + );
3209 + const projectExpanded = resolveProjectExpanded(
3210 + projectExpandedById,
3211 + projectExpansionPreferenceKeys(project),
3212 + );
3213 + const activeThreadKey = routeThreadKey ?? undefined;
3214 + const pinnedCollapsedThread =
3215 + !projectExpanded && activeThreadKey
3216 + ? (projectThreads.find(
3217 + (thread) =>
3218 + scopedThreadKey(scopeThreadRef(thread.environmentId, thread.id)) === activeThreadKey,
3219 + ) ?? null)
3220 + : null;
3221 + const shouldShowThreadPanel = projectExpanded || pinnedCollapsedThread !== null;
3222 + if (!shouldShowThreadPanel) {
3223 + return [];
3224 + }
3225 + const isThreadListExpanded = expandedThreadListsByProject.has(project.projectKey);
3226 + const hasOverflowingThreads = projectThreads.length > sidebarThreadPreviewCount;
3227 + const previewThreads =
3228 + isThreadListExpanded || !hasOverflowingThreads
3229 + ? projectThreads
3230 + : projectThreads.slice(0, sidebarThreadPreviewCount);
3231 + const renderedThreads = pinnedCollapsedThread ? [pinnedCollapsedThread] : previewThreads;
3232 + return renderedThreads.map((thread) =>
3233 + scopedThreadKey(scopeThreadRef(thread.environmentId, thread.id)),
3234 + );
3235 + });
3236 + const threadJumpCommandByKey = new Map<
3237 + string,
3238 + NonNullable<ReturnType<typeof threadJumpCommandForIndex>>
3239 + >();
3240 + for (const [visibleThreadIndex, threadKey] of visibleSidebarThreadKeys.entries()) {
3241 + const jumpCommand = threadJumpCommandForIndex(visibleThreadIndex);
3242 + if (!jumpCommand) {
3243 + break;
3244 + }
3245 + threadJumpCommandByKey.set(threadKey, jumpCommand);
3246 + }
3247 + const prewarmedSidebarThreadRefs = getSidebarThreadIdsToPrewarm(visibleSidebarThreadKeys).flatMap(
3248 + (threadKey) => {
3249 + const ref = parseScopedThreadKey(threadKey);
3250 + return ref ? [ref] : [];
3251 + },
3252 + );
3253 + return {
3254 + sidebarThreadByKey,
3255 + activeRouteProjectKey,
3256 + visibleSidebarThreadKeys,
3257 + threadJumpCommandByKey,
3258 + threadJumpThreadKeys: [...threadJumpCommandByKey.keys()],
3259 + prewarmedSidebarThreadRefs,
3260 + };
3261 +}
3262
3263 export default function LegacySidebar() {
3185 - const projects = useProjects();
3186 - const sidebarThreads = useThreadShells();
3187 - const projectExpandedById = useUiStateStore((store) => store.projectExpandedById);
3188 - const projectOrder = useUiStateStore((store) => store.projectOrder);
3264 const reorderProjects = useUiStateStore((store) => store.reorderProjects);
3265 const navigate = useNavigate();
3266 const sidebarThreadSortOrder = useClientSettings((s) => s.sidebarThreadSortOrder);
3267 const sidebarProjectSortOrder = useClientSettings((s) => s.sidebarProjectSortOrder);
3193 - const projectGroupingSettings = useClientSettings(selectProjectGroupingSettings);
3268 const sidebarThreadPreviewCount = useClientSettings((s) => s.sidebarThreadPreviewCount);
3269 const updateSettings = useUpdateClientSettings();
3270 const handleNewThread = useNewThreadHandler();
@@ -3203,10 +3277,7 @@ export default function LegacySidebar() {
3277 const routeDraftThread = useComposerDraftStore((store) =>
3278 routeTarget?.kind === "draft" ? store.getDraftSession(routeTarget.draftId) : null,
3279 );
3206 - const routeThreadRef = useMemo(
3207 - () => resolveActiveThreadRouteRef(routeTarget, routeDraftThread),
3208 - [routeDraftThread, routeTarget],
3209 - );
3280 + const routeThreadRef = resolveActiveThreadRouteRef(routeTarget, routeDraftThread);
3281 const routeThreadKey = routeThreadRef ? scopedThreadKey(routeThreadRef) : null;
3282 const routeTerminalOpen = useTerminalUiStateStore((state) =>
3283 routeThreadRef
@@ -3214,10 +3285,6 @@ export default function LegacySidebar() {
3285 : false,
3286 );
3287 const keybindings = useAtomValue(primaryServerKeybindingsAtom);
3217 - const openAddProjectCommandPalette = useCallback(
3218 - () => openCommandPalette({ open: "add-project" }),
3219 - [],
3220 - );
3288 const [expandedThreadListsByProject, setExpandedThreadListsByProject] = useState<
3289 ReadonlySet<string>
3290 >(() => new Set());
@@ -3232,346 +3299,124 @@ export default function LegacySidebar() {
3299 const platform = navigator.platform;
3300 const shortcutModifiers = useShortcutModifierState();
3301 const terminalFocused = useTerminalFocus();
3235 - const { environments } = useEnvironments();
3236 - const primaryEnvironmentId = usePrimaryEnvironmentId();
3237 - const environmentLabelById = useMemo(
3238 - () =>
3239 - new Map(
3240 - environments.map((environment) => [environment.environmentId, environment.label] as const),
3241 - ),
3242 - [environments],
3243 - );
3244 - const desktopLocalEnvironmentIds = useMemo(
3245 - () =>
3246 - new Set(
3247 - environments
3248 - .filter((environment) => isDesktopLocalConnectionTarget(environment.entry.target))
3249 - .map((environment) => environment.environmentId),
3250 - ),
3251 - [environments],
3252 - );
3253 - const wslEnvironmentIds = useMemo(
3254 - () =>
3255 - new Set(
3256 - environments
3257 - .filter((environment) => isWslConnectionTarget(environment.entry.target))
3258 - .map((environment) => environment.environmentId),
3259 - ),
3260 - [environments],
3261 - );
3262 - const orderedProjects = useMemo(() => {
3263 - return orderItemsByPreferredIds({
3264 - items: projects,
3265 - preferredIds: projectOrder,
3266 - getId: getProjectOrderKey,
3267 - getPreferenceIds: (project) => [
3268 - getProjectOrderKey(project),
3269 - legacyProjectCwdPreferenceKey(project.workspaceRoot),
3270 - ],
3271 - });
3272 - }, [projectOrder, projects]);
3273 -
3274 - const physicalToLogicalKey = useMemo(() => {
3275 - return buildPhysicalToLogicalProjectKeyMap({
3276 - projects: orderedProjects,
3277 - settings: projectGroupingSettings,
3278 - primaryEnvironmentId,
3279 - });
3280 - }, [orderedProjects, projectGroupingSettings, primaryEnvironmentId]);
3281 - const projectPhysicalKeyByScopedRef = useMemo(
3282 - () =>
3283 - new Map(
3284 - orderedProjects.map((project) => [
3285 - scopedProjectKey(scopeProjectRef(project.environmentId, project.id)),
3286 - derivePhysicalProjectKey(project),
3287 - ]),
3288 - ),
3289 - [orderedProjects],
3290 - );
3291 -
3292 - const sidebarProjects = useMemo<SidebarProjectSnapshot[]>(() => {
3293 - return buildSidebarProjectSnapshots({
3294 - projects: orderedProjects,
3295 - settings: projectGroupingSettings,
3296 - primaryEnvironmentId,
3297 - resolveEnvironmentLabel: (environmentId) => environmentLabelById.get(environmentId) ?? null,
3298 - isDesktopLocalEnvironment: (environmentId) => desktopLocalEnvironmentIds.has(environmentId),
3299 - isWslEnvironment: (environmentId) => wslEnvironmentIds.has(environmentId),
3300 - });
3301 - }, [
3302 - environmentLabelById,
3303 - desktopLocalEnvironmentIds,
3304 - wslEnvironmentIds,
3302 + const {
3303 + projectsLength,
3304 orderedProjects,
3306 - projectGroupingSettings,
3307 - primaryEnvironmentId,
3308 - ]);
3309 -
3310 - const sidebarProjectByKey = useMemo(
3311 - () => new Map(sidebarProjects.map((project) => [project.projectKey, project] as const)),
3312 - [sidebarProjects],
3313 - );
3314 - const sidebarThreadByKey = useMemo(
3315 - () =>
3316 - new Map(
3317 - sidebarThreads.map(
3318 - (thread) =>
3319 - [scopedThreadKey(scopeThreadRef(thread.environmentId, thread.id)), thread] as const,
3320 - ),
3321 - ),
3322 - [sidebarThreads],
3323 - );
3324 - const activeRouteProjectKey = useMemo(() => {
3325 - if (!routeThreadKey) {
3326 - return null;
3327 - }
3328 - const activeThread = sidebarThreadByKey.get(routeThreadKey);
3329 - if (!activeThread) return null;
3330 - const physicalKey =
3331 - projectPhysicalKeyByScopedRef.get(
3332 - scopedProjectKey(scopeProjectRef(activeThread.environmentId, activeThread.projectId)),
3333 - ) ?? scopedProjectKey(scopeProjectRef(activeThread.environmentId, activeThread.projectId));
3334 - return physicalToLogicalKey.get(physicalKey) ?? physicalKey;
3335 - }, [routeThreadKey, sidebarThreadByKey, physicalToLogicalKey, projectPhysicalKeyByScopedRef]);
3336 -
3337 - const threadsByProjectKey = useMemo(() => {
3338 - const next = new Map<string, SidebarThreadSummary[]>();
3339 - for (const thread of sidebarThreads) {
3340 - const physicalKey =
3341 - projectPhysicalKeyByScopedRef.get(
3342 - scopedProjectKey(scopeProjectRef(thread.environmentId, thread.projectId)),
3343 - ) ?? scopedProjectKey(scopeProjectRef(thread.environmentId, thread.projectId));
3344 - const logicalKey = physicalToLogicalKey.get(physicalKey) ?? physicalKey;
3345 - const existing = next.get(logicalKey);
3346 - if (existing) {
3347 - existing.push(thread);
3348 - } else {
3349 - next.set(logicalKey, [thread]);
3350 - }
3351 - }
3352 - return next;
3353 - }, [sidebarThreads, physicalToLogicalKey, projectPhysicalKeyByScopedRef]);
3354 - const getCurrentSidebarShortcutContext = useCallback(
3355 - () => ({
3356 - terminalFocus: isTerminalFocused(),
3357 - terminalOpen: routeTerminalOpen,
3358 - modelPickerOpen: isModelPickerOpen(),
3359 - }),
3360 - [routeTerminalOpen],
3361 - );
3362 - const newThreadShortcutLabelOptions = useMemo(
3363 - () => ({
3364 - platform,
3365 - context: {
3366 - terminalFocus: false,
3367 - terminalOpen: false,
3368 - },
3369 - }),
3370 - [platform],
3371 - );
3305 + physicalToLogicalKey,
3306 + projectPhysicalKeyByScopedRef,
3307 + sidebarProjects,
3308 + } = useLegacySidebarProjects();
3309 + const { sortedProjects, sortedProjectKeys } = useSortedLegacySidebarProjects({
3310 + sidebarProjects,
3311 + physicalToLogicalKey,
3312 + projectPhysicalKeyByScopedRef,
3313 + sidebarProjectSortOrder,
3314 + });
3315 + const {
3316 + sidebarThreadByKey,
3317 + activeRouteProjectKey,
3318 + visibleSidebarThreadKeys,
3319 + threadJumpCommandByKey,
3320 + threadJumpThreadKeys,
3321 + prewarmedSidebarThreadRefs,
3322 + } = useLegacySidebarThreads({
3323 + sortedProjects,
3324 + physicalToLogicalKey,
3325 + projectPhysicalKeyByScopedRef,
3326 + routeThreadKey,
3327 + sidebarThreadSortOrder,
3328 + sidebarThreadPreviewCount,
3329 + expandedThreadListsByProject,
3330 + });
3331 + const newThreadShortcutLabelOptions = {
3332 + platform,
3333 + context: {
3334 + terminalFocus: false,
3335 + terminalOpen: false,
3336 + },
3337 + };
3338 const newThreadShortcutLabel =
3339 shortcutLabelForCommand(keybindings, "chat.newLocal", newThreadShortcutLabelOptions) ??
3340 shortcutLabelForCommand(keybindings, "chat.new", newThreadShortcutLabelOptions);
3341
3376 - const navigateToThread = useCallback(
3377 - (threadRef: ScopedThreadRef) => {
3378 - if (useThreadSelectionStore.getState().selectedThreadKeys.size > 0) {
3379 - clearSelection();
3380 - }
3381 - setSelectionAnchor(scopedThreadKey(threadRef));
3382 - if (isMobile) {
3383 - setOpenMobile(false);
3384 - }
3385 - void navigate({
3386 - to: "/$environmentId/$threadId",
3387 - params: buildThreadRouteParams(threadRef),
3388 - });
3389 - },
3390 - [clearSelection, isMobile, navigate, setOpenMobile, setSelectionAnchor],
3391 - );
3392 -
3393 - const projectDnDSensors = useSensors(
3394 - useSensor(PointerSensor, {
3395 - activationConstraint: { distance: 6 },
3396 - }),
3397 - );
3398 - const projectCollisionDetection = useCallback<CollisionDetection>((args) => {
3399 - const pointerCollisions = pointerWithin(args);
3400 - if (pointerCollisions.length > 0) {
3401 - return pointerCollisions;
3342 + const navigateToThread = (threadRef: ScopedThreadRef) => {
3343 + if (useThreadSelectionStore.getState().selectedThreadKeys.size > 0) {
3344 + clearSelection();
3345 }
3346 + setSelectionAnchor(scopedThreadKey(threadRef));
3347 + if (isMobile) {
3348 + setOpenMobile(false);
3349 + }
3350 + void navigate({
3351 + to: "/$environmentId/$threadId",
3352 + params: buildThreadRouteParams(threadRef),
3353 + });
3354 + };
3355
3404 - return closestCorners(args);
3405 - }, []);
3356 + const projectDnDSensors = useSensors(useSensor(PointerSensor, PROJECT_POINTER_SENSOR_OPTIONS));
3357
3407 - const handleProjectDragEnd = useCallback(
3408 - (event: DragEndEvent) => {
3409 - if (sidebarProjectSortOrder !== "manual") {
3410 - dragInProgressRef.current = false;
3411 - return;
3412 - }
3358 + // DndContext keeps these across a drag, so they keep one identity and read the
3359 + // latest projects when called.
3360 + const handleProjectDragEnd = useStableCallback((event: DragEndEvent) => {
3361 + if (sidebarProjectSortOrder !== "manual") {
3362 dragInProgressRef.current = false;
3414 - const { active, over } = event;
3415 - if (!over || active.id === over.id) return;
3416 - const activeProject = sidebarProjects.find((project) => project.projectKey === active.id);
3417 - const overProject = sidebarProjects.find((project) => project.projectKey === over.id);
3418 - if (!activeProject || !overProject) return;
3419 - const activeMemberKeys = activeProject.memberProjects.map(
3420 - (member) => member.physicalProjectKey,
3421 - );
3422 - const overMemberKeys = overProject.memberProjects.map((member) => member.physicalProjectKey);
3423 - reorderProjects(orderedProjects.map(getProjectOrderKey), activeMemberKeys, overMemberKeys);
3424 - },
3425 - [orderedProjects, sidebarProjectSortOrder, reorderProjects, sidebarProjects],
3426 - );
3363 + return;
3364 + }
3365 + dragInProgressRef.current = false;
3366 + const { active, over } = event;
3367 + if (!over || active.id === over.id) return;
3368 + const activeProject = sidebarProjects.find((project) => project.projectKey === active.id);
3369 + const overProject = sidebarProjects.find((project) => project.projectKey === over.id);
3370 + if (!activeProject || !overProject) return;
3371 + const activeMemberKeys = activeProject.memberProjects.map(
3372 + (member) => member.physicalProjectKey,
3373 + );
3374 + const overMemberKeys = overProject.memberProjects.map((member) => member.physicalProjectKey);
3375 + reorderProjects(orderedProjects.map(getProjectOrderKey), activeMemberKeys, overMemberKeys);
3376 + });
3377
3428 - const handleProjectDragStart = useCallback(
3429 - (_event: DragStartEvent) => {
3430 - if (sidebarProjectSortOrder !== "manual") {
3431 - return;
3432 - }
3433 - dragInProgressRef.current = true;
3434 - suppressProjectClickAfterDragRef.current = true;
3435 - },
3436 - [sidebarProjectSortOrder],
3437 - );
3378 + const handleProjectDragStart = useStableCallback((_event: DragStartEvent) => {
3379 + if (sidebarProjectSortOrder !== "manual") {
3380 + return;
3381 + }
3382 + dragInProgressRef.current = true;
3383 + suppressProjectClickAfterDragRef.current = true;
3384 + });
3385
3439 - const handleProjectDragCancel = useCallback((_event: DragCancelEvent) => {
3386 + const handleProjectDragCancel = (_event: DragCancelEvent) => {
3387 dragInProgressRef.current = false;
3441 - }, []);
3388 + };
3389
3390 const animatedProjectListsRef = useRef(new WeakSet<HTMLElement>());
3444 - const attachProjectListAutoAnimateRef = useCallback((node: HTMLElement | null) => {
3391 + const attachProjectListAutoAnimateRef = (node: HTMLElement | null) => {
3392 if (!node || animatedProjectListsRef.current.has(node)) {
3393 return;
3394 }
3395 autoAnimate(node, SIDEBAR_LIST_ANIMATION_OPTIONS);
3396 animatedProjectListsRef.current.add(node);
3450 - }, []);
3397 + };
3398
3399 const animatedThreadListsRef = useRef(new WeakSet<HTMLElement>());
3453 - const attachThreadListAutoAnimateRef = useCallback((node: HTMLElement | null) => {
3400 + const attachThreadListAutoAnimateRef = (node: HTMLElement | null) => {
3401 if (!node || animatedThreadListsRef.current.has(node)) {
3402 return;
3403 }
3404 autoAnimate(node, SIDEBAR_LIST_ANIMATION_OPTIONS);
3405 animatedThreadListsRef.current.add(node);
3459 - }, []);
3406 + };
3407
3461 - const visibleThreads = useMemo(
3462 - () => sidebarThreads.filter((thread) => thread.archivedAt === null),
3463 - [sidebarThreads],
3464 - );
3465 - const sortedProjects = useMemo(() => {
3466 - const sortableProjects = sidebarProjects.map((project) => ({
3467 - ...project,
3468 - id: project.projectKey,
3469 - }));
3470 - const sortableThreads = visibleThreads.map((thread) => {
3471 - const physicalKey =
3472 - projectPhysicalKeyByScopedRef.get(
3473 - scopedProjectKey(scopeProjectRef(thread.environmentId, thread.projectId)),
3474 - ) ?? scopedProjectKey(scopeProjectRef(thread.environmentId, thread.projectId));
3475 - return {
3476 - ...thread,
3477 - projectId: (physicalToLogicalKey.get(physicalKey) ?? physicalKey) as ProjectId,
3478 - };
3479 - });
3480 - return sortProjectsForSidebar(
3481 - sortableProjects,
3482 - sortableThreads,
3483 - sidebarProjectSortOrder,
3484 - ).flatMap((project) => {
3485 - const resolvedProject = sidebarProjectByKey.get(project.id);
3486 - return resolvedProject ? [resolvedProject] : [];
3487 - });
3488 - }, [
3489 - sidebarProjectSortOrder,
3490 - physicalToLogicalKey,
3491 - projectPhysicalKeyByScopedRef,
3492 - sidebarProjectByKey,
3493 - sidebarProjects,
3494 - visibleThreads,
3495 - ]);
3408 const isManualProjectSorting = sidebarProjectSortOrder === "manual";
3497 - const visibleSidebarThreadKeys = useMemo(
3498 - () =>
3499 - sortedProjects.flatMap((project) => {
3500 - const projectThreads = sortThreads(
3501 - (threadsByProjectKey.get(project.projectKey) ?? []).filter(
3502 - (thread) => thread.archivedAt === null,
3503 - ),
3504 - sidebarThreadSortOrder,
3505 - );
3506 - const projectExpanded = resolveProjectExpanded(
3507 - projectExpandedById,
3508 - projectExpansionPreferenceKeys(project),
3509 - );
3510 - const activeThreadKey = routeThreadKey ?? undefined;
3511 - const pinnedCollapsedThread =
3512 - !projectExpanded && activeThreadKey
3513 - ? (projectThreads.find(
3514 - (thread) =>
3515 - scopedThreadKey(scopeThreadRef(thread.environmentId, thread.id)) ===
3516 - activeThreadKey,
3517 - ) ?? null)
3518 - : null;
3519 - const shouldShowThreadPanel = projectExpanded || pinnedCollapsedThread !== null;
3520 - if (!shouldShowThreadPanel) {
3521 - return [];
3522 - }
3523 - const isThreadListExpanded = expandedThreadListsByProject.has(project.projectKey);
3524 - const hasOverflowingThreads = projectThreads.length > sidebarThreadPreviewCount;
3525 - const previewThreads =
3526 - isThreadListExpanded || !hasOverflowingThreads
3527 - ? projectThreads
3528 - : projectThreads.slice(0, sidebarThreadPreviewCount);
3529 - const renderedThreads = pinnedCollapsedThread ? [pinnedCollapsedThread] : previewThreads;
3530 - return renderedThreads.map((thread) =>
3531 - scopedThreadKey(scopeThreadRef(thread.environmentId, thread.id)),
3532 - );
3533 - }),
3534 - [
3535 - sidebarThreadSortOrder,
3536 - sidebarThreadPreviewCount,
3537 - expandedThreadListsByProject,
3538 - projectExpandedById,
3539 - routeThreadKey,
3540 - sortedProjects,
3541 - threadsByProjectKey,
3542 - ],
3543 - );
3544 - const threadJumpCommandByKey = useMemo(() => {
3545 - const mapping = new Map<string, NonNullable<ReturnType<typeof threadJumpCommandForIndex>>>();
3546 - for (const [visibleThreadIndex, threadKey] of visibleSidebarThreadKeys.entries()) {
3547 - const jumpCommand = threadJumpCommandForIndex(visibleThreadIndex);
3548 - if (!jumpCommand) {
3549 - return mapping;
3550 - }
3551 - mapping.set(threadKey, jumpCommand);
3552 - }
3553 -
3554 - return mapping;
3555 - }, [visibleSidebarThreadKeys]);
3556 - const threadJumpThreadKeys = useMemo(
3557 - () => [...threadJumpCommandByKey.keys()],
3558 - [threadJumpCommandByKey],
3559 - );
3409 const sidebarShortcutContext = {
3410 terminalFocus: terminalFocused,
3411 terminalOpen: routeTerminalOpen,
3412 modelPickerOpen: isModelPickerOpen(),
3413 };
3565 - const threadJumpLabelByKey = useMemo(
3566 - () =>
3567 - buildThreadJumpLabelMap({
3568 - keybindings,
3569 - platform,
3570 - terminalOpen: sidebarShortcutContext.terminalOpen,
3571 - threadJumpCommandByKey,
3572 - }),
3573 - [keybindings, platform, sidebarShortcutContext.terminalOpen, threadJumpCommandByKey],
3574 - );
3414 + const threadJumpLabelByKey = useThreadJumpLabelMap({
3415 + keybindings,
3416 + platform,
3417 + terminalOpen: routeTerminalOpen,
3418 + threadJumpCommandByKey,
3419 + });
3420 const shouldShowThreadJumpHintsNow = shouldShowThreadJumpHintsForModifiers(
3421 shortcutModifiers,
3422 keybindings,
@@ -3584,62 +3429,33 @@ export default function LegacySidebar() {
3429 ? threadJumpLabelByKey
3430 : EMPTY_THREAD_JUMP_LABELS;
3431 const orderedSidebarThreadKeys = visibleSidebarThreadKeys;
3587 - const prewarmedSidebarThreadKeys = useMemo(
3588 - () => getSidebarThreadIdsToPrewarm(visibleSidebarThreadKeys),
3589 - [visibleSidebarThreadKeys],
3590 - );
3591 - const prewarmedSidebarThreadRefs = useMemo(
3592 - () =>
3593 - prewarmedSidebarThreadKeys.flatMap((threadKey) => {
3594 - const ref = parseScopedThreadKey(threadKey);
3595 - return ref ? [ref] : [];
3596 - }),
3597 - [prewarmedSidebarThreadKeys],
3598 - );
3432
3433 useEffect(() => {
3434 updateThreadJumpHintsVisibility(shouldShowThreadJumpHintsNow);
3435 }, [shouldShowThreadJumpHintsNow, updateThreadJumpHintsVisibility]);
3436
3604 - useEffect(() => {
3605 - const onWindowKeyDown = (event: globalThis.KeyboardEvent) => {
3606 - const shortcutContext = getCurrentSidebarShortcutContext();
3437 + const onWindowKeyDown = useEffectEvent((event: globalThis.KeyboardEvent) => {
3438 + const shortcutContext = {
3439 + terminalFocus: isTerminalFocused(),
3440 + terminalOpen: routeTerminalOpen,
3441 + modelPickerOpen: isModelPickerOpen(),
3442 + };
3443
3608 - if (event.defaultPrevented || event.repeat || isCommandPaletteOpen() || isModelPickerOpen()) {
3609 - return;
3610 - }
3444 + if (event.defaultPrevented || event.repeat || isCommandPaletteOpen() || isModelPickerOpen()) {
3445 + return;
3446 + }
3447
3612 - const command = resolveShortcutCommand(event, keybindings, {
3613 - platform,
3614 - context: shortcutContext,
3448 + const command = resolveShortcutCommand(event, keybindings, {
3449 + platform,
3450 + context: shortcutContext,
3451 + });
3452 + const traversalDirection = threadTraversalDirectionFromCommand(command);
3453 + if (traversalDirection !== null) {
3454 + const targetThreadKey = resolveAdjacentThreadId({
3455 + threadIds: orderedSidebarThreadKeys,
3456 + currentThreadId: routeThreadKey,
3457 + direction: traversalDirection,
3458 });
3616 - const traversalDirection = threadTraversalDirectionFromCommand(command);
3617 - if (traversalDirection !== null) {
3618 - const targetThreadKey = resolveAdjacentThreadId({
3619 - threadIds: orderedSidebarThreadKeys,
3620 - currentThreadId: routeThreadKey,
3621 - direction: traversalDirection,
3622 - });
3623 - if (!targetThreadKey) {
3624 - return;
3625 - }
3626 - const targetThread = sidebarThreadByKey.get(targetThreadKey);
3627 - if (!targetThread) {
3628 - return;
3629 - }
3630 -
3631 - event.preventDefault();
3632 - event.stopPropagation();
3633 - navigateToThread(scopeThreadRef(targetThread.environmentId, targetThread.id));
3634 - return;
3635 - }
3636 -
3637 - const jumpIndex = threadJumpIndexFromCommand(command ?? "");
3638 - if (jumpIndex === null) {
3639 - return;
3640 - }
3641 -
3642 - const targetThreadKey = threadJumpThreadKeys[jumpIndex];
3459 if (!targetThreadKey) {
3460 return;
3461 }
@@ -3651,23 +3467,34 @@ export default function LegacySidebar() {
3467 event.preventDefault();
3468 event.stopPropagation();
3469 navigateToThread(scopeThreadRef(targetThread.environmentId, targetThread.id));
3654 - };
3470 + return;
3471 + }
3472 +
3473 + const jumpIndex = threadJumpIndexFromCommand(command ?? "");
3474 + if (jumpIndex === null) {
3475 + return;
3476 + }
3477
3656 - window.addEventListener("keydown", onWindowKeyDown);
3478 + const targetThreadKey = threadJumpThreadKeys[jumpIndex];
3479 + if (!targetThreadKey) {
3480 + return;
3481 + }
3482 + const targetThread = sidebarThreadByKey.get(targetThreadKey);
3483 + if (!targetThread) {
3484 + return;
3485 + }
3486
3487 + event.preventDefault();
3488 + event.stopPropagation();
3489 + navigateToThread(scopeThreadRef(targetThread.environmentId, targetThread.id));
3490 + });
3491 + useEffect(() => {
3492 + const handleWindowKeyDown = (event: globalThis.KeyboardEvent) => onWindowKeyDown(event);
3493 + window.addEventListener("keydown", handleWindowKeyDown);
3494 return () => {
3659 - window.removeEventListener("keydown", onWindowKeyDown);
3495 + window.removeEventListener("keydown", handleWindowKeyDown);
3496 };
3661 - }, [
3662 - getCurrentSidebarShortcutContext,
3663 - keybindings,
3664 - navigateToThread,
3665 - orderedSidebarThreadKeys,
3666 - platform,
3667 - routeThreadKey,
3668 - sidebarThreadByKey,
3669 - threadJumpThreadKeys,
3670 - ]);
3497 + }, []);
3498
3499 useEffect(() => {
3500 const onMouseDown = (event: globalThis.MouseEvent) => {
@@ -3696,7 +3523,7 @@ export default function LegacySidebar() {
3523 const commandPaletteShortcutLabel = isMobile
3524 ? null
3525 : shortcutLabelForCommand(keybindings, "commandPalette.toggle", newThreadShortcutLabelOptions);
3699 - const handleDesktopUpdateButtonClick = useCallback(async () => {
3526 + const handleDesktopUpdateButtonClick = async () => {
3527 const bridge = window.desktopBridge;
3528 if (!bridge || !desktopUpdateState) return;
3529 if (
@@ -3786,30 +3613,25 @@ export default function LegacySidebar() {
3613 })
3614 .finally(() => setDesktopUpdateActionPending(false));
3615 }
3789 - }, [
3790 - desktopUpdateActionPending,
3791 - desktopUpdateButtonAction,
3792 - desktopUpdateButtonDisabled,
3793 - desktopUpdateState,
3794 - ]);
3616 + };
3617
3796 - const expandThreadListForProject = useCallback((projectKey: string) => {
3618 + const expandThreadListForProject = (projectKey: string) => {
3619 setExpandedThreadListsByProject((current) => {
3620 if (current.has(projectKey)) return current;
3621 const next = new Set(current);
3622 next.add(projectKey);
3623 return next;
3624 });
3803 - }, []);
3625 + };
3626
3805 - const collapseThreadListForProject = useCallback((projectKey: string) => {
3627 + const collapseThreadListForProject = (projectKey: string) => {
3628 setExpandedThreadListsByProject((current) => {
3629 if (!current.has(projectKey)) return current;
3630 const next = new Set(current);
3631 next.delete(projectKey);
3632 return next;
3633 });
3812 - }, []);
3634 + };
3635
3636 return (
3637 <>
@@ -3841,6 +3663,7 @@ export default function LegacySidebar() {
3663 deleteThread={deleteThread}
3664 markThreadUnread={markThreadUnread}
3665 sortedProjects={sortedProjects}
3666 + sortedProjectKeys={sortedProjectKeys}
3667 expandedThreadListsByProject={expandedThreadListsByProject}
3668 activeRouteProjectKey={activeRouteProjectKey}
3669 routeThreadKey={routeThreadKey}
@@ -3855,7 +3678,7 @@ export default function LegacySidebar() {
3678 suppressProjectClickAfterDragRef={suppressProjectClickAfterDragRef}
3679 suppressProjectClickForContextMenuRef={suppressProjectClickForContextMenuRef}
3680 attachProjectListAutoAnimateRef={attachProjectListAutoAnimateRef}
3858 - projectsLength={projects.length}
3681 + projectsLength={projectsLength}
3682 />
3683 <SidebarChromeFooter />
3684 </>