10
TerminalIcon,
11
TriangleAlertIcon,
12
} from "lucide-react";
13
-import { useCallback, useEffect, useMemo, useRef, useState } from "react";
13
+import { useCallback, useEffect, useMemo, useRef, useState, type MouseEvent } from "react";
14
import {
15
DndContext,
16
type DragCancelEvent,
40
import { useAppSettings } from "../appSettings";
41
import { isElectron } from "../env";
42
import { APP_STAGE_LABEL } from "../branding";
43
-import { newCommandId, newProjectId, newThreadId } from "../lib/utils";
43
+import { isMacPlatform, newCommandId, newProjectId, newThreadId } from "../lib/utils";
44
import { useStore } from "../store";
45
import { isChatNewLocalShortcut, isChatNewShortcut, shortcutLabelForCommand } from "../keybindings";
46
import { derivePendingApprovals, derivePendingUserInputs } from "../session-logic";
80
SidebarSeparator,
81
SidebarTrigger,
82
} from "./ui/sidebar";
83
+import { useThreadSelectionStore } from "../threadSelectionStore";
84
import { formatWorktreePathForDisplay, getOrphanedWorktreePathForThread } from "../worktreeCleanup";
85
import { isNonEmpty as isNonEmptyString } from "effect/String";
85
-import { resolveThreadStatusPill } from "./Sidebar.logic";
86
+import {
87
+ resolveThreadStatusPill,
88
+ shouldClearThreadSelectionOnMouseDown,
89
+} from "./Sidebar.logic";
90
91
const EMPTY_KEYBINDINGS: ResolvedKeybindingsConfig = [];
92
const THREAD_PREVIEW_LIMIT = 6;
305
const dragInProgressRef = useRef(false);
306
const suppressProjectClickAfterDragRef = useRef(false);
307
const [desktopUpdateState, setDesktopUpdateState] = useState<DesktopUpdateState | null>(null);
308
+ const selectedThreadIds = useThreadSelectionStore((s) => s.selectedThreadIds);
309
+ const toggleThreadSelection = useThreadSelectionStore((s) => s.toggleThread);
310
+ const rangeSelectTo = useThreadSelectionStore((s) => s.rangeSelectTo);
311
+ const clearSelection = useThreadSelectionStore((s) => s.clearSelection);
312
+ const removeFromSelection = useThreadSelectionStore((s) => s.removeFromSelection);
313
+ const setSelectionAnchor = useThreadSelectionStore((s) => s.setAnchor);
314
const shouldBrowseForProjectImmediately = isElectron;
315
const shouldShowProjectPathEntry = addingProject && !shouldBrowseForProjectImmediately;
316
const pendingApprovalByThreadId = useMemo(() => {
638
[],
639
);
640
631
- const handleThreadContextMenu = useCallback(
632
- async (threadId: ThreadId, position: { x: number; y: number }) => {
641
+ /**
642
+ * Delete a single thread: stop session, close terminal, dispatch delete,
643
+ * clean up drafts/state, and optionally remove orphaned worktree.
644
+ * Callers handle thread-level confirmation; this still prompts for worktree removal.
645
+ */
646
+ const deleteThread = useCallback(
647
+ async (
648
+ threadId: ThreadId,
649
+ opts: { deletedThreadIds?: ReadonlySet<ThreadId> } = {},
650
+ ): Promise<void> => {
651
const api = readNativeApi();
652
if (!api) return;
635
- const clicked = await api.contextMenu.show(
636
- [
637
- { id: "rename", label: "Rename thread" },
638
- { id: "mark-unread", label: "Mark unread" },
639
- { id: "copy-thread-id", label: "Copy Thread ID" },
640
- { id: "delete", label: "Delete", destructive: true },
641
- ],
642
- position,
643
- );
653
const thread = threads.find((t) => t.id === threadId);
654
if (!thread) return;
655
647
- if (clicked === "rename") {
648
- setRenamingThreadId(threadId);
649
- setRenamingTitle(thread.title);
650
- renamingCommittedRef.current = false;
651
- return;
652
- }
653
-
654
- if (clicked === "mark-unread") {
655
- markThreadUnread(threadId);
656
- return;
657
- }
658
- if (clicked === "copy-thread-id") {
659
- try {
660
- await copyTextToClipboard(threadId);
661
- toastManager.add({
662
- type: "success",
663
- title: "Thread ID copied",
664
- description: threadId,
665
- });
666
- } catch (error) {
667
- toastManager.add({
668
- type: "error",
669
- title: "Failed to copy thread ID",
670
- description: error instanceof Error ? error.message : "An error occurred.",
671
- });
672
- }
673
- return;
674
- }
675
- if (clicked !== "delete") return;
676
- if (appSettings.confirmThreadDelete) {
677
- const confirmed = await api.dialogs.confirm(
678
- [
679
- `Delete thread "${thread.title}"?`,
680
- "This permanently clears conversation history for this thread.",
681
- ].join("\n"),
682
- );
683
- if (!confirmed) {
684
- return;
685
- }
686
- }
656
const threadProject = projects.find((project) => project.id === thread.projectId);
688
- const orphanedWorktreePath = getOrphanedWorktreePathForThread(threads, threadId);
657
+ // When bulk-deleting, exclude the other threads being deleted so
658
+ // getOrphanedWorktreePathForThread correctly detects that no surviving
659
+ // threads will reference this worktree.
660
+ const deletedIds = opts.deletedThreadIds;
661
+ const survivingThreads =
662
+ deletedIds && deletedIds.size > 0
663
+ ? threads.filter((t) => t.id === threadId || !deletedIds.has(t.id))
664
+ : threads;
665
+ const orphanedWorktreePath = getOrphanedWorktreePathForThread(survivingThreads, threadId);
666
const displayWorktreePath = orphanedWorktreePath
667
? formatWorktreePathForDisplay(orphanedWorktreePath)
668
: null;
690
}
691
692
try {
716
- await api.terminal.close({
717
- threadId,
718
- deleteHistory: true,
719
- });
693
+ await api.terminal.close({ threadId, deleteHistory: true });
694
} catch {
695
// Terminal may already be closed
696
}
697
698
+ const allDeletedIds = deletedIds ?? new Set<ThreadId>();
699
const shouldNavigateToFallback = routeThreadId === threadId;
725
- const fallbackThreadId = threads.find((entry) => entry.id !== threadId)?.id ?? null;
700
+ const fallbackThreadId =
701
+ threads.find((entry) => entry.id !== threadId && !allDeletedIds.has(entry.id))?.id ?? null;
702
await api.orchestration.dispatchCommand({
703
type: "thread.delete",
704
commandId: newCommandId(),
745
}
746
},
747
[
772
- appSettings.confirmThreadDelete,
748
clearComposerDraftForThread,
749
clearProjectDraftThreadById,
750
clearTerminalState,
776
- markThreadUnread,
751
navigate,
752
projects,
753
removeWorktreeMutation,
756
],
757
);
758
759
+ const handleThreadContextMenu = useCallback(
760
+ async (threadId: ThreadId, position: { x: number; y: number }) => {
761
+ const api = readNativeApi();
762
+ if (!api) return;
763
+ const clicked = await api.contextMenu.show(
764
+ [
765
+ { id: "rename", label: "Rename thread" },
766
+ { id: "mark-unread", label: "Mark unread" },
767
+ { id: "copy-thread-id", label: "Copy Thread ID" },
768
+ { id: "delete", label: "Delete", destructive: true },
769
+ ],
770
+ position,
771
+ );
772
+ const thread = threads.find((t) => t.id === threadId);
773
+ if (!thread) return;
774
+
775
+ if (clicked === "rename") {
776
+ setRenamingThreadId(threadId);
777
+ setRenamingTitle(thread.title);
778
+ renamingCommittedRef.current = false;
779
+ return;
780
+ }
781
+
782
+ if (clicked === "mark-unread") {
783
+ markThreadUnread(threadId);
784
+ return;
785
+ }
786
+ if (clicked === "copy-thread-id") {
787
+ try {
788
+ await copyTextToClipboard(threadId);
789
+ toastManager.add({
790
+ type: "success",
791
+ title: "Thread ID copied",
792
+ description: threadId,
793
+ });
794
+ } catch (error) {
795
+ toastManager.add({
796
+ type: "error",
797
+ title: "Failed to copy thread ID",
798
+ description: error instanceof Error ? error.message : "An error occurred.",
799
+ });
800
+ }
801
+ return;
802
+ }
803
+ if (clicked !== "delete") return;
804
+ if (appSettings.confirmThreadDelete) {
805
+ const confirmed = await api.dialogs.confirm(
806
+ [
807
+ `Delete thread "${thread.title}"?`,
808
+ "This permanently clears conversation history for this thread.",
809
+ ].join("\n"),
810
+ );
811
+ if (!confirmed) {
812
+ return;
813
+ }
814
+ }
815
+ await deleteThread(threadId);
816
+ },
817
+ [appSettings.confirmThreadDelete, deleteThread, markThreadUnread, threads],
818
+ );
819
+
820
+ const handleMultiSelectContextMenu = useCallback(
821
+ async (position: { x: number; y: number }) => {
822
+ const api = readNativeApi();
823
+ if (!api) return;
824
+ const ids = [...selectedThreadIds];
825
+ if (ids.length === 0) return;
826
+ const count = ids.length;
827
+
828
+ const clicked = await api.contextMenu.show(
829
+ [
830
+ { id: "mark-unread", label: `Mark unread (${count})` },
831
+ { id: "delete", label: `Delete (${count})`, destructive: true },
832
+ ],
833
+ position,
834
+ );
835
+
836
+ if (clicked === "mark-unread") {
837
+ for (const id of ids) {
838
+ markThreadUnread(id);
839
+ }
840
+ clearSelection();
841
+ return;
842
+ }
843
+
844
+ if (clicked !== "delete") return;
845
+
846
+ if (appSettings.confirmThreadDelete) {
847
+ const confirmed = await api.dialogs.confirm(
848
+ [
849
+ `Delete ${count} thread${count === 1 ? "" : "s"}?`,
850
+ "This permanently clears conversation history for these threads.",
851
+ ].join("\n"),
852
+ );
853
+ if (!confirmed) return;
854
+ }
855
+
856
+ const deletedIds = new Set<ThreadId>(ids);
857
+ for (const id of ids) {
858
+ await deleteThread(id, { deletedThreadIds: deletedIds });
859
+ }
860
+ removeFromSelection(ids);
861
+ },
862
+ [
863
+ appSettings.confirmThreadDelete,
864
+ clearSelection,
865
+ deleteThread,
866
+ markThreadUnread,
867
+ removeFromSelection,
868
+ selectedThreadIds,
869
+ ],
870
+ );
871
+
872
+ const handleThreadClick = useCallback(
873
+ (event: MouseEvent, threadId: ThreadId, orderedProjectThreadIds: readonly ThreadId[]) => {
874
+ const isMac = isMacPlatform(navigator.platform);
875
+ const isModClick = isMac ? event.metaKey : event.ctrlKey;
876
+ const isShiftClick = event.shiftKey;
877
+
878
+ if (isModClick) {
879
+ event.preventDefault();
880
+ toggleThreadSelection(threadId);
881
+ return;
882
+ }
883
+
884
+ if (isShiftClick) {
885
+ event.preventDefault();
886
+ rangeSelectTo(threadId, orderedProjectThreadIds);
887
+ return;
888
+ }
889
+
890
+ // Plain click — clear selection, set anchor for future shift-clicks, and navigate
891
+ if (selectedThreadIds.size > 0) {
892
+ clearSelection();
893
+ }
894
+ setSelectionAnchor(threadId);
895
+ void navigate({
896
+ to: "/$threadId",
897
+ params: { threadId },
898
+ });
899
+ },
900
+ [clearSelection, navigate, rangeSelectTo, selectedThreadIds.size, setSelectionAnchor, toggleThreadSelection],
901
+ );
902
+
903
const handleProjectContextMenu = useCallback(
904
async (projectId: ProjectId, position: { x: number; y: number }) => {
905
const api = readNativeApi();
1012
event.stopPropagation();
1013
return;
1014
}
1015
+ if (selectedThreadIds.size > 0) {
1016
+ clearSelection();
1017
+ }
1018
toggleProject(projectId);
1019
},
899
- [toggleProject],
1020
+ [clearSelection, selectedThreadIds.size, toggleProject],
1021
);
1022
1023
const handleProjectTitleKeyDown = useCallback(
1034
1035
useEffect(() => {
1036
const onWindowKeyDown = (event: KeyboardEvent) => {
1037
+ if (event.key === "Escape" && selectedThreadIds.size > 0) {
1038
+ event.preventDefault();
1039
+ clearSelection();
1040
+ return;
1041
+ }
1042
+
1043
const activeThread = routeThreadId
1044
? threads.find((thread) => thread.id === routeThreadId)
1045
: undefined;
1064
});
1065
};
1066
1067
+ const onMouseDown = (event: globalThis.MouseEvent) => {
1068
+ if (selectedThreadIds.size === 0) return;
1069
+ const target = event.target instanceof HTMLElement ? event.target : null;
1070
+ if (!shouldClearThreadSelectionOnMouseDown(target)) return;
1071
+ clearSelection();
1072
+ };
1073
+
1074
window.addEventListener("keydown", onWindowKeyDown);
1075
+ window.addEventListener("mousedown", onMouseDown);
1076
return () => {
1077
window.removeEventListener("keydown", onWindowKeyDown);
1078
+ window.removeEventListener("mousedown", onMouseDown);
1079
};
944
- }, [getDraftThread, handleNewThread, keybindings, projects, routeThreadId, threads]);
1080
+ }, [clearSelection, getDraftThread, handleNewThread, keybindings, projects, routeThreadId, selectedThreadIds.size, threads]);
1081
1082
useEffect(() => {
1083
if (!isElectron) return;
1413
hasHiddenThreads && !isThreadListExpanded
1414
? projectThreads.slice(0, THREAD_PREVIEW_LIMIT)
1415
: projectThreads;
1416
+ const orderedProjectThreadIds = projectThreads.map((t) => t.id);
1417
1418
return (
1419
<SortableProjectItem key={project.id} projectId={project.id}>
1480
</div>
1481
1482
<CollapsibleContent keepMounted>
1346
- <SidebarMenuSub className="mx-1 my-0 w-full translate-x-0 gap-0 px-1.5 py-0">
1483
+ <SidebarMenuSub className="mx-1 my-0 w-full translate-x-0 gap-0.5 px-1.5 py-0">
1484
{visibleThreads.map((thread) => {
1485
const isActive = routeThreadId === thread.id;
1486
+ const isSelected = selectedThreadIds.has(thread.id);
1487
+ const isHighlighted = isActive || isSelected;
1488
const threadStatus = resolveThreadStatusPill({
1489
thread,
1490
hasPendingApprovals: pendingApprovalByThreadId.get(thread.id) === true,
1497
);
1498
1499
return (
1361
- <SidebarMenuSubItem key={thread.id} className="w-full">
1500
+ <SidebarMenuSubItem key={thread.id} className="w-full" data-thread-item>
1501
<SidebarMenuSubButton
1502
render={<div role="button" tabIndex={0} />}
1503
size="sm"
1504
isActive={isActive}
1366
- className={`h-7 w-full translate-x-0 cursor-default justify-start px-2 text-left hover:bg-accent hover:text-foreground ${
1367
- isActive
1368
- ? "bg-accent/85 text-foreground font-medium ring-1 ring-border/70 dark:bg-accent/55 dark:ring-border/50"
1369
- : "text-muted-foreground"
1505
+ className={`h-7 w-full translate-x-0 cursor-default justify-start px-2 text-left select-none hover:bg-accent hover:text-foreground focus-visible:ring-0 ${
1506
+ isSelected
1507
+ ? "bg-primary/15 text-foreground dark:bg-primary/10"
1508
+ : isActive
1509
+ ? "bg-accent/85 text-foreground font-medium dark:bg-accent/55"
1510
+ : "text-muted-foreground"
1511
}`}
1371
- onClick={() => {
1372
- void navigate({
1373
- to: "/$threadId",
1374
- params: { threadId: thread.id },
1375
- });
1512
+ onClick={(event) => {
1513
+ handleThreadClick(event, thread.id, orderedProjectThreadIds);
1514
}}
1515
onKeyDown={(event) => {
1516
if (event.key !== "Enter" && event.key !== " ") return;
1517
event.preventDefault();
1518
+ if (selectedThreadIds.size > 0) {
1519
+ clearSelection();
1520
+ }
1521
+ setSelectionAnchor(thread.id);
1522
void navigate({
1523
to: "/$threadId",
1524
params: { threadId: thread.id },
1526
}}
1527
onContextMenu={(event) => {
1528
event.preventDefault();
1387
- void handleThreadContextMenu(thread.id, {
1388
- x: event.clientX,
1389
- y: event.clientY,
1390
- });
1529
+ if (selectedThreadIds.size > 0 && selectedThreadIds.has(thread.id)) {
1530
+ void handleMultiSelectContextMenu({
1531
+ x: event.clientX,
1532
+ y: event.clientY,
1533
+ });
1534
+ } else {
1535
+ if (selectedThreadIds.size > 0) {
1536
+ clearSelection();
1537
+ }
1538
+ void handleThreadContextMenu(thread.id, {
1539
+ x: event.clientX,
1540
+ y: event.clientY,
1541
+ });
1542
+ }
1543
}}
1544
>
1545
<div className="flex min-w-0 flex-1 items-center gap-1.5 text-left">
1626
)}
1627
<span
1628
className={`text-[10px] ${
1477
- isActive ? "text-foreground/65" : "text-muted-foreground/40"
1629
+ isHighlighted ? "text-foreground/65" : "text-muted-foreground/40"
1630
}`}
1631
>
1632
{formatRelativeTime(thread.createdAt)}
1641
<SidebarMenuSubItem className="w-full">
1642
<SidebarMenuSubButton
1643
render={<button type="button" />}
1644
+ data-thread-selection-safe
1645
size="sm"
1646
className="h-6 w-full translate-x-0 justify-start px-2 text-left text-[10px] text-muted-foreground/60 hover:bg-accent hover:text-muted-foreground/80"
1647
onClick={() => {
1656
<SidebarMenuSubItem className="w-full">
1657
<SidebarMenuSubButton
1658
render={<button type="button" />}
1659
+ data-thread-selection-safe
1660
size="sm"
1661
className="h-6 w-full translate-x-0 justify-start px-2 text-left text-[10px] text-muted-foreground/60 hover:bg-accent hover:text-muted-foreground/80"
1662
onClick={() => {