-
Notifications
You must be signed in to change notification settings - Fork 95
Expand file tree
/
Copy pathProjectSidebar.tsx
More file actions
3042 lines (2814 loc) · 134 KB
/
ProjectSidebar.tsx
File metadata and controls
3042 lines (2814 loc) · 134 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import React, { useState, useEffect, useCallback, useRef } from "react";
import { cn } from "@/common/lib/utils";
import { isDesktopMode } from "@/browser/hooks/useDesktopTitlebar";
import MuxLogoDark from "@/browser/assets/logos/mux-logo-dark.svg?react";
import MuxLogoLight from "@/browser/assets/logos/mux-logo-light.svg?react";
import { useTheme } from "@/browser/contexts/ThemeContext";
import type { FrontendWorkspaceMetadata } from "@/common/types/workspace";
import {
readPersistedState,
updatePersistedState,
usePersistedState,
} from "@/browser/hooks/usePersistedState";
import { useDebouncedValue } from "@/browser/hooks/useDebouncedValue";
import { useRuntimeStatusStoreRaw } from "@/browser/stores/RuntimeStatusStore";
import { useWorkspaceStoreRaw, type WorkspaceStore } from "@/browser/stores/WorkspaceStore";
import {
EXPANDED_PROJECTS_KEY,
MOBILE_LEFT_SIDEBAR_SCROLL_TOP_KEY,
getDraftScopeId,
getInputAttachmentsKey,
getInputKey,
getWorkspaceLastReadKey,
getWorkspaceNameStateKey,
} from "@/common/constants/storage";
import { getDisplayTitleFromPersistedState } from "@/browser/hooks/useWorkspaceName";
import { DndProvider } from "react-dnd";
import { HTML5Backend, getEmptyImage } from "react-dnd-html5-backend";
import { useDrag, useDrop, useDragLayer } from "react-dnd";
import {
sortProjectsByOrder,
reorderProjects,
normalizeOrder,
} from "@/common/utils/projectOrdering";
import {
matchesKeybind,
formatKeybind,
isEditableElement,
KEYBINDS,
} from "@/browser/utils/ui/keybinds";
import { useAPI } from "@/browser/contexts/API";
import {
CUSTOM_EVENTS,
getStorageChangeEvent,
type CustomEventType,
} from "@/common/constants/events";
import { PlatformPaths } from "@/common/utils/paths";
import {
partitionWorkspacesByAge,
partitionWorkspacesBySection,
formatDaysThreshold,
AGE_THRESHOLDS_DAYS,
computeWorkspaceDepthMap,
filterVisibleAgentRows,
computeAgentRowRenderMeta,
findNextNonEmptyTier,
getTierKey,
getSectionExpandedKey,
getSectionTierKey,
sortSectionsByLinkedList,
type AgentRowRenderMeta,
} from "@/browser/utils/ui/workspaceFiltering";
import { Tooltip, TooltipTrigger, TooltipContent } from "../Tooltip/Tooltip";
import { SidebarCollapseButton } from "../SidebarCollapseButton/SidebarCollapseButton";
import { ConfirmationModal } from "../ConfirmationModal/ConfirmationModal";
import {
buildArchiveConfirmDescription,
buildArchiveConfirmWarning,
} from "@/browser/utils/archiveConfirmation";
import { ProjectDeleteConfirmationModal } from "../ProjectDeleteConfirmationModal/ProjectDeleteConfirmationModal";
import { useSettings } from "@/browser/contexts/SettingsContext";
import { AgentListItem, type WorkspaceSelection } from "../AgentListItem/AgentListItem";
import { TaskGroupListItem } from "./TaskGroupListItem";
import { TitleEditProvider, useTitleEdit } from "@/browser/contexts/WorkspaceTitleEditContext";
import { useConfirmDialog } from "@/browser/contexts/ConfirmDialogContext";
import { useProjectContext } from "@/browser/contexts/ProjectContext";
import { stopKeyboardPropagation } from "@/browser/utils/events";
import { useContextMenuPosition } from "@/browser/hooks/useContextMenuPosition";
import {
PositionedMenu,
PositionedMenuItem,
} from "@/browser/components/PositionedMenu/PositionedMenu";
import {
ChevronRight,
EllipsisVertical,
Folder,
FolderOpen,
KeyRound,
Palette,
Pencil,
Trash,
Plus,
} from "lucide-react";
import { useWorkspaceActions } from "@/browser/contexts/WorkspaceContext";
import { useRouter } from "@/browser/contexts/RouterContext";
import { usePopoverError } from "@/browser/hooks/usePopoverError";
import { forkWorkspace } from "@/browser/utils/chatCommands";
import { PopoverError } from "../PopoverError/PopoverError";
import { SectionHeader } from "../SectionHeader/SectionHeader";
import { WorkspaceSectionDropZone } from "../WorkspaceSectionDropZone/WorkspaceSectionDropZone";
import { WorkspaceDragLayer } from "../WorkspaceDragLayer/WorkspaceDragLayer";
import { SectionDragLayer } from "../SectionDragLayer/SectionDragLayer";
import { DraggableSection } from "../DraggableSection/DraggableSection";
import { Separator } from "../Separator/Separator";
import { ScrollArea } from "../ScrollArea/ScrollArea";
import type { SectionConfig } from "@/common/types/project";
import { getErrorMessage } from "@/common/utils/errors";
import { isMultiProject } from "@/common/utils/multiProject";
import { MULTI_PROJECT_SIDEBAR_SECTION_ID } from "@/common/constants/multiProject";
import { getProjectWorkspaceCounts } from "@/common/utils/projectRemoval";
import { getTaskGroupKindFromMetadata } from "@/common/utils/tools/taskGroups";
import { hasCompletedAgentReport } from "@/common/utils/agentTaskCompletion";
import { useExperimentValue } from "@/browser/hooks/useExperiments";
import { EXPERIMENT_IDS } from "@/common/constants/experiments";
import { HexColorPicker } from "react-colorful";
import { resolveSectionColor, SECTION_COLOR_PALETTE } from "@/common/constants/ui";
// Re-export WorkspaceSelection for backwards compatibility
export type { WorkspaceSelection } from "../AgentListItem/AgentListItem";
// Draggable project item moved to module scope to avoid remounting on every parent render.
// Defining components inside another component causes a new function identity each render,
// which forces React to unmount/remount the subtree. That led to hover flicker and high CPU.
/**
* Subscribe sidebar-level attention derivation to workspace updates.
*
* Project/section highlighting is computed in this parent component, so it must
* re-render for both:
* - unread storage writes (localStorage-backed "last read" timestamps)
* - attention-relevant workspace transitions (streaming, awaiting question, system errors)
*/
interface WorkspaceAttentionSignal {
isWorking: boolean;
awaitingUserQuestion: boolean;
hasSystemError: boolean;
}
function getWorkspaceAttentionSignal(
workspaceStore: WorkspaceStore,
workspaceId: string
): WorkspaceAttentionSignal | null {
try {
const sidebarState = workspaceStore.getWorkspaceSidebarState(workspaceId);
const isWorking =
(sidebarState.canInterrupt || sidebarState.isStarting) && !sidebarState.awaitingUserQuestion;
return {
isWorking,
awaitingUserQuestion: sidebarState.awaitingUserQuestion,
hasSystemError: sidebarState.lastAbortReason?.reason === "system",
};
} catch {
// Workspace may have been removed while subscriptions are being torn down.
return null;
}
}
function isWorkspaceWorkingForSidebar(
workspaceStore: WorkspaceStore,
workspaceId: string
): boolean {
return getWorkspaceAttentionSignal(workspaceStore, workspaceId)?.isWorking ?? false;
}
function didWorkspaceAttentionSignalChange(
prev: WorkspaceAttentionSignal | undefined,
next: WorkspaceAttentionSignal
): boolean {
if (!prev) {
return true;
}
return (
prev.isWorking !== next.isWorking ||
prev.awaitingUserQuestion !== next.awaitingUserQuestion ||
prev.hasSystemError !== next.hasSystemError
);
}
function useWorkspaceAttentionSubscription(
sortedWorkspacesByProject: Map<string, FrontendWorkspaceMetadata[]>,
workspaceStore: WorkspaceStore
): void {
const [, setVersion] = useState(0);
useEffect(() => {
if (typeof window === "undefined") {
return;
}
const workspaceIds = new Set<string>();
const workspaceLastReadKeys = new Set<string>();
for (const workspaces of sortedWorkspacesByProject.values()) {
for (const workspace of workspaces) {
workspaceIds.add(workspace.id);
workspaceLastReadKeys.add(getWorkspaceLastReadKey(workspace.id));
}
}
if (workspaceIds.size === 0 && workspaceLastReadKeys.size === 0) {
return;
}
const bumpVersion = () => {
setVersion((currentVersion) => currentVersion + 1);
};
const attentionSignalsByWorkspaceId = new Map<string, WorkspaceAttentionSignal>();
for (const workspaceId of workspaceIds) {
const signal = getWorkspaceAttentionSignal(workspaceStore, workspaceId);
if (signal) {
attentionSignalsByWorkspaceId.set(workspaceId, signal);
}
}
const handleStorage = (event: StorageEvent) => {
if (event.key && workspaceLastReadKeys.has(event.key)) {
bumpVersion();
}
};
const unsubscribeWorkspaceStore = Array.from(workspaceIds.values()).map((workspaceId) =>
workspaceStore.subscribeKey(workspaceId, () => {
const nextSignal = getWorkspaceAttentionSignal(workspaceStore, workspaceId);
if (!nextSignal) {
return;
}
const previousSignal = attentionSignalsByWorkspaceId.get(workspaceId);
if (!didWorkspaceAttentionSignalChange(previousSignal, nextSignal)) {
return;
}
attentionSignalsByWorkspaceId.set(workspaceId, nextSignal);
bumpVersion();
})
);
window.addEventListener("storage", handleStorage);
for (const key of workspaceLastReadKeys) {
window.addEventListener(getStorageChangeEvent(key), bumpVersion);
}
return () => {
for (const unsubscribe of unsubscribeWorkspaceStore) {
unsubscribe();
}
window.removeEventListener("storage", handleStorage);
for (const key of workspaceLastReadKeys) {
window.removeEventListener(getStorageChangeEvent(key), bumpVersion);
}
};
}, [sortedWorkspacesByProject, workspaceStore]);
}
// Keep the project header visible while scrolling through long workspace lists.
// Project rows are also drag handles, so disable text selection to avoid
// highlighting the whole sidebar before a reorder gesture locks in.
// pr-2 matches AgentListItem LIST_ITEM_BASE_CLASSES so project kebab aligns with workspace rows.
const PROJECT_ITEM_BASE_CLASS =
"group sticky top-0 z-10 py-2 pl-2 pr-1 flex select-none items-center border-l-transparent bg-surface-primary transition-colors duration-150";
function getProjectFallbackLabel(projectPath: string): string {
const abbreviatedPath = PlatformPaths.abbreviate(projectPath);
const { basename } = PlatformPaths.splitAbbreviated(abbreviatedPath);
return basename;
}
function getProjectNameFromPath(path: string): string {
if (!path || typeof path !== "string") {
return "Unknown";
}
return PlatformPaths.getProjectName(path);
}
function normalizeDisplayNameInput(value: string): string | null {
const trimmedValue = value.trim();
return trimmedValue.length > 0 ? trimmedValue : null;
}
function getProjectItemClassName(opts: {
isDragging: boolean;
isOver: boolean;
selected: boolean;
}): string {
return cn(
PROJECT_ITEM_BASE_CLASS,
opts.isDragging ? "cursor-grabbing opacity-35 [&_*]:!cursor-grabbing" : "cursor-grab",
opts.isOver && "bg-accent/[0.08]",
opts.selected && "bg-hover border-l-accent",
"hover:[&_button]:opacity-100 hover:[&_button]:pointer-events-auto hover:[&_[data-drag-handle]]:opacity-100"
);
}
type DraggableProjectItemProps = React.PropsWithChildren<{
projectPath: string;
onReorder: (draggedPath: string, targetPath: string) => void;
selected?: boolean;
onClick?: () => void;
onContextMenu?: (e: React.MouseEvent) => void;
onTouchStart?: (e: React.TouchEvent) => void;
onTouchEnd?: (e: React.TouchEvent) => void;
onTouchMove?: (e: React.TouchEvent) => void;
onKeyDown?: (e: React.KeyboardEvent) => void;
role?: string;
tabIndex?: number;
"aria-expanded"?: boolean;
"aria-controls"?: string;
"aria-label"?: string;
"data-project-path"?: string;
}>;
const DraggableProjectItemBase: React.FC<DraggableProjectItemProps> = ({
projectPath,
onReorder,
children,
selected,
...rest
}) => {
const [{ isDragging }, drag, dragPreview] = useDrag(
() => ({
type: "PROJECT",
item: { type: "PROJECT" as const, projectPath },
collect: (monitor) => ({ isDragging: monitor.isDragging() }),
}),
[projectPath]
);
// Hide native drag preview; we render a custom preview via DragLayer
useEffect(() => {
dragPreview(getEmptyImage(), { captureDraggingState: true });
}, [dragPreview]);
const [{ isOver }, drop] = useDrop(
() => ({
accept: "PROJECT",
drop: (item: { projectPath: string }) => {
if (item.projectPath !== projectPath) {
onReorder(item.projectPath, projectPath);
}
},
collect: (monitor) => ({ isOver: monitor.isOver({ shallow: true }) }),
}),
[projectPath, onReorder]
);
return (
<div
ref={(node) => drag(drop(node))}
className={getProjectItemClassName({
isDragging,
isOver,
selected: !!selected,
})}
{...rest}
>
{children}
</div>
);
};
const DraggableProjectItem = DraggableProjectItemBase;
/**
* Wrapper that fetches draft data from localStorage and renders via unified AgentListItem.
* Keeps data-fetching logic colocated with sidebar while delegating rendering to shared component.
*/
interface DraftAgentListItemWrapperProps {
projectPath: string;
draftId: string;
draftNumber: number;
isSelected: boolean;
sectionId?: string;
onVisibilityChange?: (isVisible: boolean) => void;
onOpen: () => void;
onDelete: () => void;
}
// Debounce delay for sidebar preview updates during typing.
// Prevents constant re-renders while still providing timely feedback.
const DRAFT_PREVIEW_DEBOUNCE_MS = 1000;
function isDraftVisible(
projectPath: string,
draftId: string,
values?: {
draftPrompt?: string;
workspaceNameState?: unknown;
draftAttachments?: unknown[];
}
): boolean {
const scopeId = getDraftScopeId(projectPath, draftId);
const draftPrompt = values?.draftPrompt ?? readPersistedState<string>(getInputKey(scopeId), "");
const workspaceNameState =
values?.workspaceNameState ??
readPersistedState<unknown>(getWorkspaceNameStateKey(scopeId), null);
const draftAttachments =
values?.draftAttachments ?? readPersistedState<unknown[]>(getInputAttachmentsKey(scopeId), []);
const hasTextContent = typeof draftPrompt === "string" && draftPrompt.trim().length > 0;
const hasAttachments = Array.isArray(draftAttachments) && draftAttachments.length > 0;
const hasNameState = workspaceNameState !== null;
return hasTextContent || hasAttachments || hasNameState;
}
function DraftAgentListItemWrapper(props: DraftAgentListItemWrapperProps) {
const scopeId = getDraftScopeId(props.projectPath, props.draftId);
const onVisibilityChange = props.onVisibilityChange;
const [draftPrompt] = usePersistedState<string>(getInputKey(scopeId), "", {
listener: true,
});
const [workspaceNameState] = usePersistedState<unknown>(getWorkspaceNameStateKey(scopeId), null, {
listener: true,
});
const [draftAttachments] = usePersistedState<unknown[]>(getInputAttachmentsKey(scopeId), [], {
listener: true,
});
// Debounce the preview values to avoid constant sidebar updates while typing.
const debouncedPrompt = useDebouncedValue(draftPrompt, DRAFT_PREVIEW_DEBOUNCE_MS);
const debouncedNameState = useDebouncedValue(workspaceNameState, DRAFT_PREVIEW_DEBOUNCE_MS);
// Keep empty drafts reusable without immediately surfacing them in the sidebar.
// Show the row when the draft has any user-provided content (typed text,
// attachments, or workspace-name edits), mirroring the isDraftEmpty() contract
// so non-empty drafts never become hidden orphans.
// Uses raw (non-debounced) values so the row appears immediately, while the
// preview text below still updates at the debounced cadence.
const isVisible = isDraftVisible(props.projectPath, props.draftId, {
draftPrompt,
workspaceNameState,
draftAttachments: Array.isArray(draftAttachments) ? draftAttachments : [],
});
useEffect(() => {
onVisibilityChange?.(isVisible);
}, [isVisible, onVisibilityChange]);
if (!isVisible) {
return null;
}
const workspaceTitle = getDisplayTitleFromPersistedState(debouncedNameState);
// Collapse whitespace so multi-line prompts show up nicely as a single-line preview.
const promptPreview =
typeof debouncedPrompt === "string" ? debouncedPrompt.trim().replace(/\s+/g, " ") : "";
const titleText = workspaceTitle.trim().length > 0 ? workspaceTitle.trim() : "Draft";
return (
<AgentListItem
variant="draft"
projectPath={props.projectPath}
isSelected={props.isSelected}
sectionId={props.sectionId}
draft={{
draftId: props.draftId,
draftNumber: props.draftNumber,
title: titleText,
promptPreview,
onOpen: props.onOpen,
onDelete: props.onDelete,
}}
/>
);
}
// Custom drag layer to show a semi-transparent preview and enforce grabbing cursor
interface ProjectDragItem {
type: "PROJECT";
projectPath: string;
}
interface SectionDragItemLocal {
type: "SECTION_REORDER";
sectionId: string;
projectPath: string;
}
type DragItem = ProjectDragItem | SectionDragItemLocal | null;
const ProjectDragLayer: React.FC = () => {
const dragState = useDragLayer<{
isDragging: boolean;
item: unknown;
currentOffset: { x: number; y: number } | null;
}>((monitor) => ({
isDragging: monitor.isDragging(),
item: monitor.getItem(),
currentOffset: monitor.getClientOffset(),
}));
const isDragging = dragState.isDragging;
const item = dragState.item as DragItem;
const currentOffset = dragState.currentOffset;
React.useEffect(() => {
if (!isDragging) return;
const originalBody = document.body.style.cursor;
const originalHtml = document.documentElement.style.cursor;
document.body.style.cursor = "grabbing";
document.documentElement.style.cursor = "grabbing";
return () => {
document.body.style.cursor = originalBody;
document.documentElement.style.cursor = originalHtml;
};
}, [isDragging]);
// Only render for PROJECT type drags (not section reorder)
if (!isDragging || !currentOffset || !item?.projectPath || item.type !== "PROJECT") return null;
const abbrevPath = PlatformPaths.abbreviate(item.projectPath);
const { basename } = PlatformPaths.splitAbbreviated(abbrevPath);
return (
<div className="pointer-events-none fixed inset-0 z-9999 cursor-grabbing">
<div style={{ transform: `translate(${currentOffset.x + 10}px, ${currentOffset.y + 10}px)` }}>
<div className={cn(PROJECT_ITEM_BASE_CLASS, "w-fit max-w-64 rounded-sm shadow-lg")}>
<span className="text-secondary mr-2 flex h-5 w-5 shrink-0 items-center justify-center">
<ChevronRight className="h-4 w-4" />
</span>
<div className="flex min-w-0 flex-1 items-center pr-2">
<span className="text-foreground truncate text-sm font-medium">{basename}</span>
</div>
</div>
</div>
</div>
);
};
/**
* Handles F2 (edit title) and Shift+F2 (generate new title) keybinds.
* Rendered inside TitleEditProvider so it can access useTitleEdit().
*/
function SidebarTitleEditKeybinds(props: {
selectedWorkspace: WorkspaceSelection | undefined;
sortedWorkspacesByProject: Map<string, FrontendWorkspaceMetadata[]>;
collapsed: boolean;
}) {
const { requestEdit, wrapGenerateTitle } = useTitleEdit();
const { api } = useAPI();
const regenerateTitleForWorkspace = useCallback(
(workspaceId: string) => {
wrapGenerateTitle(workspaceId, () => {
if (!api) {
return Promise.resolve({ success: false, error: "Not connected to server" });
}
return api.workspace.regenerateTitle({ workspaceId });
});
},
[wrapGenerateTitle, api]
);
useEffect(() => {
const handleKeyDown = (e: KeyboardEvent) => {
if (props.collapsed) return;
if (!props.selectedWorkspace) return;
if (isEditableElement(e.target)) return;
const wsId = props.selectedWorkspace.workspaceId;
if (matchesKeybind(e, KEYBINDS.EDIT_WORKSPACE_TITLE)) {
e.preventDefault();
const meta = props.sortedWorkspacesByProject
.get(props.selectedWorkspace.projectPath)
?.find((m) => m.id === wsId);
const displayTitle = meta?.title ?? meta?.name ?? "";
requestEdit(wsId, displayTitle);
} else if (matchesKeybind(e, KEYBINDS.GENERATE_WORKSPACE_TITLE)) {
e.preventDefault();
regenerateTitleForWorkspace(wsId);
}
};
window.addEventListener("keydown", handleKeyDown);
return () => window.removeEventListener("keydown", handleKeyDown);
}, [
props.collapsed,
props.selectedWorkspace,
props.sortedWorkspacesByProject,
requestEdit,
regenerateTitleForWorkspace,
]);
useEffect(() => {
const handleGenerateTitleRequest: EventListener = (event) => {
const customEvent = event as CustomEventType<
typeof CUSTOM_EVENTS.WORKSPACE_GENERATE_TITLE_REQUESTED
>;
regenerateTitleForWorkspace(customEvent.detail.workspaceId);
};
window.addEventListener(
CUSTOM_EVENTS.WORKSPACE_GENERATE_TITLE_REQUESTED,
handleGenerateTitleRequest
);
return () => {
window.removeEventListener(
CUSTOM_EVENTS.WORKSPACE_GENERATE_TITLE_REQUESTED,
handleGenerateTitleRequest
);
};
}, [regenerateTitleForWorkspace]);
return null;
}
interface ProjectSidebarProps {
collapsed: boolean;
onToggleCollapsed: () => void;
sortedWorkspacesByProject: Map<string, FrontendWorkspaceMetadata[]>;
workspaceRecency: Record<string, number>;
}
function didUntrackedPathSetChange(
acknowledgedUntrackedPaths: string[],
latestUntrackedPaths: string[]
): boolean {
if (acknowledgedUntrackedPaths.length !== latestUntrackedPaths.length) {
return true;
}
const acknowledgedSet = new Set(acknowledgedUntrackedPaths);
return latestUntrackedPaths.some((path) => !acknowledgedSet.has(path));
}
const ProjectSidebarInner: React.FC<ProjectSidebarProps> = ({
collapsed,
onToggleCollapsed,
sortedWorkspacesByProject,
workspaceRecency,
}) => {
// Use the narrow actions context — does NOT subscribe to workspaceMetadata
// changes, preventing the entire sidebar tree from re-rendering on every
// workspace create/archive/rename.
const {
selectedWorkspace,
setSelectedWorkspace: onSelectWorkspace,
preflightArchiveWorkspace,
archiveWorkspace: onArchiveWorkspace,
removeWorkspace,
updateWorkspaceTitle: onUpdateTitle,
refreshWorkspaceMetadata,
pendingNewWorkspaceProject,
pendingNewWorkspaceDraftId,
workspaceDraftsByProject,
workspaceDraftPromotionsByProject,
createWorkspaceDraft,
openWorkspaceDraft,
deleteWorkspaceDraft,
} = useWorkspaceActions();
const workspaceStore = useWorkspaceStoreRaw();
useWorkspaceAttentionSubscription(sortedWorkspacesByProject, workspaceStore);
const runtimeStatusStore = useRuntimeStatusStoreRaw();
const { navigateToProject } = useRouter();
const { api } = useAPI();
const { confirm: confirmDialog } = useConfirmDialog();
const settings = useSettings();
// Get project state and operations from context
const {
userProjects,
openProjectCreateModal: onAddProject,
removeProject: onRemoveProject,
updateDisplayName,
updateColor: updateProjectColor,
createSection,
updateSection,
removeSection,
reorderSections,
assignWorkspaceToSection,
} = useProjectContext();
// Theme for logo variant
const { theme } = useTheme();
const MuxLogo = theme === "dark" || theme.endsWith("-dark") ? MuxLogoDark : MuxLogoLight;
const multiProjectWorkspacesEnabled = useExperimentValue(EXPERIMENT_IDS.MULTI_PROJECT_WORKSPACES);
// Mobile breakpoint for auto-closing sidebar
const MOBILE_BREAKPOINT = 768;
const NEW_SUB_FOLDER_PLACEHOLDER_NAME = "New sub-folder";
const projectListScrollRef = useRef<HTMLDivElement | null>(null);
const mobileScrollTopRef = useRef(0);
const wasCollapsedRef = useRef(collapsed);
const normalizeMobileScrollTop = useCallback((scrollTop: number): number => {
return Number.isFinite(scrollTop) ? Math.max(0, Math.round(scrollTop)) : 0;
}, []);
const persistMobileSidebarScrollTop = useCallback(
(scrollTop: number) => {
if (window.innerWidth > MOBILE_BREAKPOINT) {
return;
}
// Keep the last viewed list position so reopening the touch sidebar returns
// users to where they were browsing instead of jumping back to the top.
const normalizedScrollTop = normalizeMobileScrollTop(scrollTop);
updatePersistedState<number>(MOBILE_LEFT_SIDEBAR_SCROLL_TOP_KEY, normalizedScrollTop, 0);
},
[MOBILE_BREAKPOINT, normalizeMobileScrollTop]
);
useEffect(() => {
if (collapsed || window.innerWidth > MOBILE_BREAKPOINT) {
return;
}
const persistedScrollTop = readPersistedState<unknown>(MOBILE_LEFT_SIDEBAR_SCROLL_TOP_KEY, 0);
const normalizedScrollTop =
typeof persistedScrollTop === "number" ? normalizeMobileScrollTop(persistedScrollTop) : 0;
mobileScrollTopRef.current = normalizedScrollTop;
if (projectListScrollRef.current) {
projectListScrollRef.current.scrollTop = normalizedScrollTop;
}
}, [collapsed, MOBILE_BREAKPOINT, normalizeMobileScrollTop]);
useEffect(() => {
const wasCollapsed = wasCollapsedRef.current;
if (!wasCollapsed && collapsed) {
persistMobileSidebarScrollTop(mobileScrollTopRef.current);
}
wasCollapsedRef.current = collapsed;
}, [collapsed, persistMobileSidebarScrollTop]);
const handleProjectListScroll = useCallback(
(event: React.UIEvent<HTMLDivElement>) => {
mobileScrollTopRef.current = normalizeMobileScrollTop(event.currentTarget.scrollTop);
},
[normalizeMobileScrollTop]
);
// Wrapper to close sidebar on mobile after workspace selection
const handleSelectWorkspace = useCallback(
(selection: WorkspaceSelection) => {
onSelectWorkspace(selection);
if (window.innerWidth <= MOBILE_BREAKPOINT && !collapsed) {
persistMobileSidebarScrollTop(mobileScrollTopRef.current);
onToggleCollapsed();
}
},
[onSelectWorkspace, collapsed, onToggleCollapsed, persistMobileSidebarScrollTop]
);
// Wrapper to close sidebar on mobile after adding workspace
const handleAddWorkspace = useCallback(
(projectPath: string, sectionId?: string) => {
createWorkspaceDraft(projectPath, sectionId);
if (window.innerWidth <= MOBILE_BREAKPOINT && !collapsed) {
persistMobileSidebarScrollTop(mobileScrollTopRef.current);
onToggleCollapsed();
}
},
[createWorkspaceDraft, collapsed, onToggleCollapsed, persistMobileSidebarScrollTop]
);
// Wrapper to close sidebar on mobile after opening an existing draft
const handleOpenWorkspaceDraft = useCallback(
(projectPath: string, draftId: string, sectionId?: string | null) => {
openWorkspaceDraft(projectPath, draftId, sectionId);
if (window.innerWidth <= MOBILE_BREAKPOINT && !collapsed) {
persistMobileSidebarScrollTop(mobileScrollTopRef.current);
onToggleCollapsed();
}
},
[openWorkspaceDraft, collapsed, onToggleCollapsed, persistMobileSidebarScrollTop]
);
const handleGoHome = useCallback(() => {
// Selecting null delegates to WorkspaceContext's home-navigation + selection reset flow.
onSelectWorkspace(null);
// Close sidebar on mobile
if (window.innerWidth <= MOBILE_BREAKPOINT && !collapsed) {
persistMobileSidebarScrollTop(mobileScrollTopRef.current);
onToggleCollapsed();
}
}, [onSelectWorkspace, collapsed, onToggleCollapsed, persistMobileSidebarScrollTop]);
// Workspace-specific subscriptions moved to AgentListItem component
// Store as array in localStorage, convert to Set for usage
const [expandedProjectsArray, setExpandedProjectsArray] = usePersistedState<string[]>(
EXPANDED_PROJECTS_KEY,
[]
);
// Handle corrupted localStorage data (old Set stored as {}).
// Use a plain array with .includes() instead of new Set() on every render —
// the React Compiler cannot stabilize Set allocations (see AGENTS.md).
// For typical sidebar sizes (< 20 projects) .includes() is equivalent perf.
const expandedProjectsList = Array.isArray(expandedProjectsArray) ? expandedProjectsArray : [];
// Track which projects have old workspaces expanded (per-project, per-tier)
// Key format: getTierKey(projectPath, tierIndex) where tierIndex is 0, 1, 2 for 1/7/30 days
const [expandedOldWorkspaces, setExpandedOldWorkspaces] = usePersistedState<
Record<string, boolean>
>("expandedOldWorkspaces", {});
// Track which sections are expanded
const [expandedSections, setExpandedSections] = usePersistedState<Record<string, boolean>>(
"expandedSections",
{}
);
// Track parent workspaces whose reported child tasks are expanded.
const [expandedCompletedSubAgents, setExpandedCompletedSubAgents] = usePersistedState<
Record<string, boolean>
>("expandedCompletedSubAgents", {});
const toggleCompletedChildrenExpansion = useCallback(
(workspaceId: string) => {
setExpandedCompletedSubAgents((prev) => ({
...prev,
[workspaceId]: !prev[workspaceId],
}));
},
[setExpandedCompletedSubAgents]
);
const expandedCompletedParentIds = new Set(
Object.entries(expandedCompletedSubAgents)
.filter(([, expanded]) => expanded)
.map(([workspaceId]) => workspaceId)
);
const [expandedTaskGroups, setExpandedTaskGroups] = useState<Record<string, boolean>>({});
const toggleTaskGroupExpansion = (groupId: string) => {
setExpandedTaskGroups((prev) => ({
...prev,
[groupId]: !prev[groupId],
}));
};
const [archivingWorkspaceIds, setArchivingWorkspaceIds] = useState<Set<string>>(new Set());
const [removingWorkspaceIds, setRemovingWorkspaceIds] = useState<Set<string>>(new Set());
const [draftVisibilityByProject, setDraftVisibilityByProject] = useState<
Record<string, Record<string, boolean>>
>({});
const workspaceArchiveError = usePopoverError();
const workspaceForkError = usePopoverError();
const workspaceStopRuntimeError = usePopoverError();
const workspaceRemoveError = usePopoverError();
const [archiveConfirmation, setArchiveConfirmation] = useState<{
workspaceId: string;
displayTitle: string;
buttonElement?: HTMLElement;
/** When set, the confirmation warns about permanent deletion of untracked files. */
untrackedPaths?: string[];
/** Whether the workspace has an active stream that will be interrupted. */
isStreaming?: boolean;
} | null>(null);
const [deleteConfirmation, setDeleteConfirmation] = useState<{
projectPath: string;
projectName: string;
activeCount: number;
archivedCount: number;
} | null>(null);
const projectRemoveError = usePopoverError();
const sectionRemoveError = usePopoverError();
const handleDraftVisibilityChange = useCallback(
(projectPath: string, draftId: string, isVisible: boolean) => {
setDraftVisibilityByProject((prev) => {
const existing = prev[projectPath] ?? {};
if (existing[draftId] === isVisible) {
return prev;
}
return {
...prev,
[projectPath]: {
...existing,
[draftId]: isVisible,
},
};
});
},
[]
);
const projectContextMenu = useContextMenuPosition({ longPress: true });
const [projectMenuTargetPath, setProjectMenuTargetPath] = useState<string | null>(null);
const [editingProjectPath, setEditingProjectPath] = useState<string | null>(null);
const [editingProjectDisplayName, setEditingProjectDisplayName] = useState("");
const [autoEditingSection, setAutoEditingSection] = useState<{
projectPath: string;
sectionId: string;
} | null>(null);
const [showProjectColorPicker, setShowProjectColorPicker] = useState(false);
const [projectColorHexInput, setProjectColorHexInput] = useState("");
const [projectColorPickerValue, setProjectColorPickerValue] = useState("#000000");
const [projectColorPickerDirty, setProjectColorPickerDirty] = useState(false);
const skipNextProjectNameBlurCommitRef = useRef(false);
// Use functional update to avoid stale closure issues when clicking rapidly
const toggleProject = useCallback(
(projectPath: string) => {
setExpandedProjectsArray((prev) => {
const prevSet = new Set(Array.isArray(prev) ? prev : []);
if (prevSet.has(projectPath)) {
prevSet.delete(projectPath);
} else {
prevSet.add(projectPath);
}
return Array.from(prevSet);
});
},
[setExpandedProjectsArray]
);
const toggleSection = (projectPath: string, sectionId: string) => {
const key = getSectionExpandedKey(projectPath, sectionId);
setExpandedSections((prev) => ({
...prev,
[key]: !prev[key],
}));
};
const handleForkWorkspace = useCallback(
async (workspaceId: string, buttonElement?: HTMLElement) => {
if (!api) {
workspaceForkError.showError(workspaceId, "Not connected to server");
return;
}
let anchor: { top: number; left: number } | undefined;
if (buttonElement) {
const rect = buttonElement.getBoundingClientRect();
anchor = {
top: rect.top + window.scrollY,
left: rect.right + 10,
};
}
try {
const result = await forkWorkspace({
client: api,
sourceWorkspaceId: workspaceId,
});
if (result.success) {
return;
}
workspaceForkError.showError(workspaceId, result.error ?? "Failed to fork chat", anchor);
} catch (error) {
// IPC/transport failures throw instead of returning { success: false }
const message = getErrorMessage(error);
workspaceForkError.showError(workspaceId, message, anchor);
}
},
[api, workspaceForkError]
);
const handleStopRuntime = useCallback(
async (workspaceId: string, buttonElement?: HTMLElement) => {
let anchor: { top: number; left: number } | undefined;
if (buttonElement) {
const rect = buttonElement.getBoundingClientRect();
anchor = {
top: rect.top + window.scrollY,
left: rect.right + 10,
};
}
if (!api) {
workspaceStopRuntimeError.showError(workspaceId, "Not connected to server", anchor);
return;
}
try {
const result = await api.workspace.stopRuntime({ workspaceId });
if (!result.success) {
workspaceStopRuntimeError.showError(
workspaceId,
result.error ?? "Failed to stop container",
anchor
);
return;
}
// A successful stop should hide the running indicator and menu action without
// forcing rows to own their own optimistic runtime state.
runtimeStatusStore.invalidateWorkspace(workspaceId);
} catch (error) {
workspaceStopRuntimeError.showError(workspaceId, getErrorMessage(error), anchor);
}
},
[api, runtimeStatusStore, workspaceStopRuntimeError]
);
const performArchiveWorkspace = useCallback(
async (
workspaceId: string,
buttonElement?: HTMLElement,
acknowledgedUntrackedPaths?: string[]
) => {
// Mark workspace as being archived for UI feedback
setArchivingWorkspaceIds((prev) => new Set(prev).add(workspaceId));
try {
const result = await onArchiveWorkspace(
workspaceId,
acknowledgedUntrackedPaths ? { acknowledgedUntrackedPaths } : undefined
);
if (result.success && result.data?.kind === "confirm-lossy-untracked-files") {
const metadata = workspaceStore.getWorkspaceMetadata(workspaceId);
const displayTitle = metadata?.title ?? metadata?.name ?? workspaceId;
const isStreaming = isWorkspaceWorkingForSidebar(workspaceStore, workspaceId);