-
Notifications
You must be signed in to change notification settings - Fork 106
Expand file tree
/
Copy pathApp.tsx
More file actions
1282 lines (1157 loc) · 49.8 KB
/
App.tsx
File metadata and controls
1282 lines (1157 loc) · 49.8 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 { useEffect, useCallback, useRef, useState } from "react";
import { useRouter } from "./contexts/RouterContext";
import { useLocation, useNavigate } from "react-router-dom";
import "./styles/globals.css";
import { useWorkspaceContext, toWorkspaceSelection } from "./contexts/WorkspaceContext";
import { useProjectContext } from "./contexts/ProjectContext";
import type { WorkspaceSelection } from "./components/ProjectSidebar/ProjectSidebar";
import { LeftSidebar } from "./components/LeftSidebar/LeftSidebar";
import { ProjectCreateModal } from "./components/ProjectCreateModal/ProjectCreateModal";
import { MultiProjectWorkspaceCreateModal } from "./components/MultiProjectWorkspaceCreateModal/MultiProjectWorkspaceCreateModal";
import { AIView } from "./components/AIView/AIView";
import { ErrorBoundary } from "./components/ErrorBoundary/ErrorBoundary";
import {
usePersistedState,
updatePersistedState,
readPersistedState,
} from "./hooks/usePersistedState";
import { useResizableSidebar } from "./hooks/useResizableSidebar";
import { matchesKeybind, KEYBINDS } from "./utils/ui/keybinds";
import { handleLayoutSlotHotkeys } from "./utils/ui/layoutSlotHotkeys";
import { buildSortedWorkspacesByProject } from "./utils/ui/workspaceFiltering";
import { getVisibleWorkspaceIds } from "./utils/ui/workspaceDomNav";
import { useUnreadTracking } from "./hooks/useUnreadTracking";
import { useWorkspaceStoreRaw, useWorkspaceRecency } from "./stores/WorkspaceStore";
import {
getResponseCompleteNotificationBody,
shouldNotifyOnResponseComplete,
type ResponseCompleteEvent,
} from "./utils/messages/responseCompletionMetadata";
import { showBrowserNotification } from "./utils/ui/showBrowserNotification";
import { useStableReference, compareMaps } from "./hooks/useStableReference";
import { CommandRegistryProvider, useCommandRegistry } from "./contexts/CommandRegistryContext";
import { useOpenTerminal } from "./hooks/useOpenTerminal";
import type { CommandAction } from "./contexts/CommandRegistryContext";
import { useTheme, type ThemePreference } from "./contexts/ThemeContext";
import { CommandPalette } from "./components/CommandPalette/CommandPalette";
import {
LEFT_SIDEBAR_DEFAULT_WIDTH_PX,
LEFT_SIDEBAR_MAX_WIDTH_PX,
LEFT_SIDEBAR_MIN_WIDTH_PX,
} from "@/constants/layout";
import { buildCoreSources, type BuildSourcesParams } from "./utils/commands/sources";
import { THINKING_LEVELS, type ThinkingLevel } from "@/common/types/thinking";
import { CUSTOM_EVENTS } from "@/common/constants/events";
import { isWorkspaceForkSwitchEvent } from "./utils/workspaceEvents";
import {
getAgentIdKey,
getAgentsInitNudgeKey,
getModelKey,
getNotifyOnResponseKey,
getThinkingLevelByModelKey,
getThinkingLevelKey,
getWorkspaceAISettingsByAgentKey,
getWorkspaceLastReadKey,
EXPANDED_PROJECTS_KEY,
LEFT_SIDEBAR_COLLAPSED_KEY,
LEFT_SIDEBAR_WIDTH_KEY,
} from "@/common/constants/storage";
import { normalizeSelectedModel, normalizeToCanonical } from "@/common/utils/ai/models";
import { getDefaultModel } from "@/browser/hooks/useModelsFromSettings";
import type { BranchListResult } from "@/common/orpc/types";
import { useTelemetry } from "./hooks/useTelemetry";
import { getRuntimeTypeForTelemetry } from "@/common/telemetry";
import { useStartWorkspaceCreation } from "./hooks/useStartWorkspaceCreation";
import { useAPI } from "@/browser/contexts/API";
import {
clearPendingWorkspaceAiSettings,
markPendingWorkspaceAiSettings,
} from "@/browser/utils/workspaceAiSettingsSync";
import { AuthTokenModal } from "@/browser/components/AuthTokenModal/AuthTokenModal";
import { ProjectPage } from "@/browser/components/ProjectPage/ProjectPage";
import { SettingsProvider, useSettings } from "./contexts/SettingsContext";
import { AboutDialogProvider } from "./contexts/AboutDialogContext";
import { ConfirmDialogProvider, useConfirmDialog } from "./contexts/ConfirmDialogContext";
import { AboutDialog } from "./features/About/AboutDialog";
import { SettingsPage } from "@/browser/features/Settings/SettingsPage";
import { AnalyticsDashboard } from "@/browser/features/Analytics/AnalyticsDashboard";
import { MuxGatewaySessionExpiredDialog } from "./components/MuxGatewaySessionExpiredDialog/MuxGatewaySessionExpiredDialog";
import { SshPromptDialog } from "./components/SshPromptDialog/SshPromptDialog";
import { SplashScreenProvider } from "./features/SplashScreens/SplashScreenProvider";
import { TutorialProvider } from "./contexts/TutorialContext";
import { PowerModeProvider } from "./contexts/PowerModeContext";
import { TooltipProvider } from "./components/Tooltip/Tooltip";
import { UILayoutsProvider, useUILayouts } from "@/browser/contexts/UILayoutsContext";
import { ExperimentsProvider } from "./contexts/ExperimentsContext";
import { ProviderOptionsProvider } from "./contexts/ProviderOptionsContext";
import { getWorkspaceSidebarKey } from "./utils/workspace";
import { WindowsToolchainBanner } from "./components/WindowsToolchainBanner/WindowsToolchainBanner";
import { RosettaBanner } from "./components/RosettaBanner/RosettaBanner";
import { useExperimentValue } from "@/browser/hooks/useExperiments";
import { EXPERIMENT_IDS } from "@/common/constants/experiments";
import { getErrorMessage } from "@/common/utils/errors";
import assert from "@/common/utils/assert";
import { createProjectRefs } from "@/common/utils/multiProject";
import { MULTI_PROJECT_SIDEBAR_SECTION_ID } from "@/common/constants/multiProject";
import { WORKSPACE_DEFAULTS } from "@/constants/workspaceDefaults";
import { isDesktopMode } from "@/browser/hooks/useDesktopTitlebar";
import { prependInitialAppProxyBasePath } from "@/browser/utils/frontendBasePath";
import { LoadingScreen } from "@/browser/components/LoadingScreen/LoadingScreen";
function RootRouteShell(props: {
leftSidebarCollapsed: boolean;
onToggleLeftSidebarCollapsed: () => void;
}) {
return (
<div className="bg-surface-primary flex flex-1 flex-col overflow-hidden">
{props.leftSidebarCollapsed ? (
<div
className={`bg-sidebar border-border-light flex shrink-0 items-center border-b px-4 py-2 ${isDesktopMode() ? "titlebar-drag" : ""}`}
>
<button
type="button"
onClick={props.onToggleLeftSidebarCollapsed}
className={`border-border-medium bg-background-secondary text-foreground hover:bg-hover rounded-md border px-3 py-1.5 text-sm transition-colors ${isDesktopMode() ? "titlebar-no-drag" : ""}`}
aria-label="Open sidebar menu"
>
Open sidebar
</button>
</div>
) : null}
<div className="flex flex-1 items-center justify-center px-6">
<p className="text-muted text-sm">Select or add a project to get started.</p>
</div>
</div>
);
}
function AppInner() {
// Get workspace state from context
const {
workspaceMetadata,
loading,
setWorkspaceMetadata,
removeWorkspace,
updateWorkspaceTitle,
selectedWorkspace,
setSelectedWorkspace,
pendingNewWorkspaceProject,
pendingNewWorkspaceSectionId,
pendingNewWorkspaceDraftId,
beginWorkspaceCreation,
} = useWorkspaceContext();
const {
currentWorkspaceId,
currentSettingsSection,
isAnalyticsOpen,
navigateToAnalytics,
navigateFromAnalytics,
} = useRouter();
const { themePreference, setTheme, toggleTheme } = useTheme();
const { open: openSettings, isOpen: isSettingsOpen } = useSettings();
const { confirm: confirmDialog } = useConfirmDialog();
const setThemePreference = useCallback(
(nextTheme: ThemePreference) => {
setTheme(nextTheme);
},
[setTheme]
);
const { layoutPresets, applySlotToWorkspace, saveCurrentWorkspaceToSlot } = useUILayouts();
const { api, status, error, authenticate, retry } = useAPI();
const {
userProjects,
refreshProjects,
removeProject,
openProjectCreateModal,
isProjectCreateModalOpen,
closeProjectCreateModal,
addProject,
} = useProjectContext();
// Auto-collapse sidebar on mobile by default
const isMobile = typeof window !== "undefined" && window.innerWidth <= 768;
const [sidebarCollapsed, setSidebarCollapsed] = usePersistedState(
LEFT_SIDEBAR_COLLAPSED_KEY,
isMobile,
{
listener: true,
}
);
const [isMultiProjectWorkspaceModalOpen, setMultiProjectWorkspaceModalOpen] = useState(false);
const multiProjectWorkspacesEnabled = useExperimentValue(EXPERIMENT_IDS.MULTI_PROJECT_WORKSPACES);
// Left sidebar is drag-resizable (mirrors RightSidebar). Width is persisted globally;
// collapse remains a separate toggle and the drag handle is hidden in mobile-touch overlay mode.
const leftSidebar = useResizableSidebar({
enabled: true,
defaultWidth: LEFT_SIDEBAR_DEFAULT_WIDTH_PX,
minWidth: LEFT_SIDEBAR_MIN_WIDTH_PX,
maxWidth: LEFT_SIDEBAR_MAX_WIDTH_PX,
// Keep enough room for the main content so you can't drag-resize the left sidebar
// to a point where the chat pane becomes unusably narrow.
getMaxWidthPx: () => {
// Match LeftSidebar's mobile overlay gate. In that mode we don't want viewport-based clamping
// because the sidebar width is controlled by CSS and shouldn't rewrite the user's desktop
// width preference.
const isMobileTouch =
typeof window !== "undefined" &&
window.matchMedia("(max-width: 768px) and (pointer: coarse)").matches;
if (isMobileTouch) {
return Number.POSITIVE_INFINITY;
}
const viewportWidth = typeof window !== "undefined" ? window.innerWidth : 1200;
// ChatPane uses tailwind `min-w-96`.
return viewportWidth - 384;
},
storageKey: LEFT_SIDEBAR_WIDTH_KEY,
side: "left",
});
// Sync sidebar collapse state to the root element for non-React consumers like
// Storybook play helpers that need to know whether the sidebar is currently collapsed.
useEffect(() => {
document.documentElement.dataset.leftSidebarCollapsed = String(sidebarCollapsed);
}, [sidebarCollapsed]);
const creationProjectPath =
!selectedWorkspace && !currentWorkspaceId ? pendingNewWorkspaceProject : null;
// History navigation (back/forward)
const navigate = useNavigate();
const location = useLocation();
const locationRef = useRef(location);
locationRef.current = location;
const startWorkspaceCreation = useStartWorkspaceCreation({
projects: userProjects,
beginWorkspaceCreation,
});
// ProjectPage handles its own focus when mounted
const handleToggleSidebar = useCallback(() => {
setSidebarCollapsed((prev) => !prev);
}, [setSidebarCollapsed]);
// Telemetry tracking
const telemetry = useTelemetry();
// Get workspace store for command palette
const workspaceStore = useWorkspaceStoreRaw();
// Track telemetry when workspace selection changes
const prevWorkspaceRef = useRef<WorkspaceSelection | null>(null);
// Ref for selectedWorkspace to access in callbacks without stale closures
const selectedWorkspaceRef = useRef(selectedWorkspace);
selectedWorkspaceRef.current = selectedWorkspace;
// Ref for route-level workspace visibility to avoid stale closure in response callbacks
const currentWorkspaceIdRef = useRef(currentWorkspaceId);
currentWorkspaceIdRef.current = currentWorkspaceId;
useEffect(() => {
const prev = prevWorkspaceRef.current;
if (prev && selectedWorkspace && prev.workspaceId !== selectedWorkspace.workspaceId) {
telemetry.workspaceSwitched(prev.workspaceId, selectedWorkspace.workspaceId);
}
prevWorkspaceRef.current = selectedWorkspace;
}, [selectedWorkspace, telemetry]);
// Track last-read timestamps for unread indicators.
// Read-marking is gated on chat-route visibility (currentWorkspaceId).
useUnreadTracking(selectedWorkspace, currentWorkspaceId);
const workspaceMetadataRef = useRef(workspaceMetadata);
useEffect(() => {
workspaceMetadataRef.current = workspaceMetadata;
}, [workspaceMetadata]);
// Update window title based on selected workspace
// URL syncing is now handled by RouterContext
useEffect(() => {
if (selectedWorkspace) {
// Update window title with workspace title (or name for legacy workspaces)
const metadata = workspaceMetadata.get(selectedWorkspace.workspaceId);
const workspaceTitle = metadata?.title ?? metadata?.name ?? selectedWorkspace.workspaceId;
const title = `${workspaceTitle} - ${selectedWorkspace.projectName} - mux`;
// Set document.title locally for browser mode, call backend for Electron
document.title = title;
void api?.window.setTitle({ title });
} else {
// Set document.title locally for browser mode, call backend for Electron
document.title = "mux";
void api?.window.setTitle({ title: "mux" });
}
}, [selectedWorkspace, workspaceMetadata, api]);
// Validate selected workspace exists and has all required fields
// Note: workspace validity is now primarily handled by RouterContext deriving
// selectedWorkspace from URL + metadata. This effect handles edge cases like
// stale localStorage or missing fields in legacy workspaces.
useEffect(() => {
if (selectedWorkspace) {
const metadata = workspaceMetadata.get(selectedWorkspace.workspaceId);
if (!metadata) {
// Workspace metadata disappeared while this route was active. Clear the stale
// selection so the router can self-heal to the compatibility root route.
console.warn(
`Workspace ${selectedWorkspace.workspaceId} no longer exists, clearing selection`
);
setSelectedWorkspace(null);
} else if (!selectedWorkspace.namedWorkspacePath && metadata.namedWorkspacePath) {
// Old localStorage entry missing namedWorkspacePath - update it once
console.log(`Updating workspace ${selectedWorkspace.workspaceId} with missing fields`);
setSelectedWorkspace(toWorkspaceSelection(metadata));
}
}
}, [selectedWorkspace, workspaceMetadata, setSelectedWorkspace]);
const openWorkspaceInTerminal = useOpenTerminal();
const handleRemoveProject = useCallback(
async (path: string) => {
if (selectedWorkspace?.projectPath === path) {
setSelectedWorkspace(null);
}
return removeProject(path);
},
// eslint-disable-next-line react-hooks/exhaustive-deps
[selectedWorkspace, setSelectedWorkspace]
);
// Memoize callbacks to prevent LeftSidebar/ProjectSidebar re-renders
// NEW: Get workspace recency from store
const workspaceRecency = useWorkspaceRecency();
// Build sorted workspaces map including pending workspaces
// Use stable reference to prevent sidebar re-renders when sort order hasn't changed
const sortedWorkspacesByProject = useStableReference(
() => buildSortedWorkspacesByProject(userProjects, workspaceMetadata, workspaceRecency),
(prev, next) =>
compareMaps(prev, next, (a, b) => {
if (a.length !== b.length) return false;
return a.every((meta, i) => {
const other = b[i];
// Compare all fields that affect sidebar display.
// If you add a new display-relevant field to WorkspaceMetadata,
// add it to getWorkspaceSidebarKey() in src/browser/utils/workspace.ts
return other && getWorkspaceSidebarKey(meta) === getWorkspaceSidebarKey(other);
});
}),
[userProjects, workspaceMetadata, workspaceRecency]
);
const handleNavigateWorkspace = useCallback(
(direction: "next" | "prev") => {
// Read actual rendered workspace order from DOM — impossible to drift from sidebar.
const visibleIds = getVisibleWorkspaceIds();
if (visibleIds.length === 0) return;
const currentIndex = selectedWorkspace
? visibleIds.indexOf(selectedWorkspace.workspaceId)
: -1;
let targetIndex: number;
if (currentIndex === -1) {
targetIndex = direction === "next" ? 0 : visibleIds.length - 1;
} else if (direction === "next") {
targetIndex = (currentIndex + 1) % visibleIds.length;
} else {
targetIndex = currentIndex === 0 ? visibleIds.length - 1 : currentIndex - 1;
}
const targetMeta = workspaceMetadata.get(visibleIds[targetIndex]);
if (targetMeta) setSelectedWorkspace(toWorkspaceSelection(targetMeta));
},
[selectedWorkspace, workspaceMetadata, setSelectedWorkspace]
);
// Register command sources with registry
const {
registerSource,
isOpen: isCommandPaletteOpen,
open: openCommandPalette,
close: closeCommandPalette,
} = useCommandRegistry();
/**
* Get the selected model for a workspace, preserving explicit gateway prefixes.
*/
const getModelForWorkspace = useCallback((workspaceId: string): string => {
const defaultModel = getDefaultModel();
const rawModel = readPersistedState<string>(getModelKey(workspaceId), defaultModel);
return normalizeSelectedModel(rawModel || defaultModel);
}, []);
const getThinkingLevelForWorkspace = useCallback(
(workspaceId: string): ThinkingLevel => {
if (!workspaceId) {
return "off";
}
const scopedKey = getThinkingLevelKey(workspaceId);
const scoped = readPersistedState<ThinkingLevel | undefined>(scopedKey, undefined);
if (scoped !== undefined) {
return THINKING_LEVELS.includes(scoped) ? scoped : "off";
}
// Migration: fall back to legacy per-model thinking and seed the workspace-scoped key.
const model = getModelForWorkspace(workspaceId);
const legacy = readPersistedState<ThinkingLevel | undefined>(
getThinkingLevelByModelKey(model),
undefined
);
if (legacy !== undefined && THINKING_LEVELS.includes(legacy)) {
updatePersistedState(scopedKey, legacy);
return legacy;
}
// Fallback: check canonical key for legacy entries stored before gateway-aware normalization.
const canonicalModel = normalizeToCanonical(model);
if (canonicalModel !== model) {
const canonicalLegacy = readPersistedState<ThinkingLevel | undefined>(
getThinkingLevelByModelKey(canonicalModel),
undefined
);
if (canonicalLegacy !== undefined && THINKING_LEVELS.includes(canonicalLegacy)) {
updatePersistedState(scopedKey, canonicalLegacy);
return canonicalLegacy;
}
}
return "off";
},
[getModelForWorkspace]
);
const setThinkingLevelFromPalette = useCallback(
(workspaceId: string, level: ThinkingLevel) => {
if (!workspaceId) {
return;
}
const normalized = THINKING_LEVELS.includes(level) ? level : "off";
const model = getModelForWorkspace(workspaceId);
const key = getThinkingLevelKey(workspaceId);
// Use the utility function which handles localStorage and event dispatch
// ThinkingProvider will pick this up via its listener
updatePersistedState(key, normalized);
type WorkspaceAISettingsByAgentCache = Partial<
Record<string, { model: string; thinkingLevel: ThinkingLevel }>
>;
const normalizedAgentId =
readPersistedState<string>(getAgentIdKey(workspaceId), WORKSPACE_DEFAULTS.agentId)
.trim()
.toLowerCase() || WORKSPACE_DEFAULTS.agentId;
updatePersistedState<WorkspaceAISettingsByAgentCache>(
getWorkspaceAISettingsByAgentKey(workspaceId),
(prev) => {
const record: WorkspaceAISettingsByAgentCache =
prev && typeof prev === "object" ? prev : {};
return {
...record,
[normalizedAgentId]: { model, thinkingLevel: normalized },
};
},
{}
);
// Persist to backend so the palette change follows the workspace across devices.
if (api) {
markPendingWorkspaceAiSettings(workspaceId, normalizedAgentId, {
model,
thinkingLevel: normalized,
});
api.workspace
.updateAgentAISettings({
workspaceId,
agentId: normalizedAgentId,
aiSettings: { model, thinkingLevel: normalized },
})
.then((result) => {
if (!result.success) {
clearPendingWorkspaceAiSettings(workspaceId, normalizedAgentId);
}
})
.catch(() => {
clearPendingWorkspaceAiSettings(workspaceId, normalizedAgentId);
// Best-effort only.
});
}
// Dispatch toast notification event for UI feedback
if (typeof window !== "undefined") {
window.dispatchEvent(
new CustomEvent(CUSTOM_EVENTS.THINKING_LEVEL_TOAST, {
detail: { workspaceId, level: normalized },
})
);
}
},
[api, getModelForWorkspace]
);
const registerParamsRef = useRef<BuildSourcesParams | null>(null);
const openNewWorkspaceFromPalette = useCallback(
(projectPath: string) => {
startWorkspaceCreation(projectPath);
},
[startWorkspaceCreation]
);
const openNewMultiProjectWorkspaceFromPalette = useCallback(() => {
if (!multiProjectWorkspacesEnabled) {
return;
}
setMultiProjectWorkspaceModalOpen(true);
}, [multiProjectWorkspacesEnabled]);
useEffect(() => {
if (multiProjectWorkspacesEnabled || !isMultiProjectWorkspaceModalOpen) {
return;
}
setMultiProjectWorkspaceModalOpen(false);
}, [isMultiProjectWorkspaceModalOpen, multiProjectWorkspacesEnabled]);
const createMultiProjectWorkspace = useCallback(
async (projectPaths: string[]) => {
assert(
projectPaths.length >= 2,
"createMultiProjectWorkspace requires at least two projects"
);
if (!api) {
throw new Error("Not connected to server");
}
const [primaryProjectPath] = projectPaths;
assert(primaryProjectPath, "createMultiProjectWorkspace requires a primary project");
const branchResult = await api.projects.listBranches({ projectPath: primaryProjectPath });
const candidateBranches = branchResult.branches.filter(
(branch): branch is string => typeof branch === "string"
);
const trunkBranch =
(branchResult.recommendedTrunk && candidateBranches.includes(branchResult.recommendedTrunk)
? branchResult.recommendedTrunk
: candidateBranches[0]) ?? null;
if (!trunkBranch) {
const primaryProjectName =
primaryProjectPath.split("/").pop() ??
primaryProjectPath.split("\\").pop() ??
primaryProjectPath;
throw new Error(
`No branches found for ${primaryProjectName}. Initialize a git repository before creating a multi-project workspace.`
);
}
// Multi-project container names must stay unique and path-separator-free.
const projects = createProjectRefs(projectPaths);
const metadata = await api.workspace.createMultiProject({
projects,
branchName: `multi-${Date.now().toString(36)}`,
trunkBranch,
});
// Make the synthetic section visible immediately after creation.
updatePersistedState<string[]>(
EXPANDED_PROJECTS_KEY,
(prev) => {
const expanded = Array.isArray(prev) ? prev : [];
return expanded.includes(MULTI_PROJECT_SIDEBAR_SECTION_ID)
? expanded
: [...expanded, MULTI_PROJECT_SIDEBAR_SECTION_ID];
},
[]
);
// Inline workspace creation bookkeeping (main removed the extracted callback)
workspaceStore.addWorkspace(metadata);
setWorkspaceMetadata((prev) => new Map(prev).set(metadata.id, metadata));
telemetry.workspaceCreated(metadata.id, getRuntimeTypeForTelemetry(metadata.runtimeConfig));
setSelectedWorkspace(toWorkspaceSelection(metadata));
setMultiProjectWorkspaceModalOpen(false);
},
[api, setSelectedWorkspace, setWorkspaceMetadata, telemetry, workspaceStore]
);
const archiveMergedWorkspacesInProjectFromPalette = useCallback(
async (projectPath: string): Promise<void> => {
const trimmedProjectPath = projectPath.trim();
if (!trimmedProjectPath) return;
if (!api) {
if (typeof window !== "undefined") {
window.alert("Cannot archive merged workspaces: API not connected");
}
return;
}
try {
const result = await api.workspace.archiveMergedInProject({
projectPath: trimmedProjectPath,
});
if (!result.success) {
if (typeof window !== "undefined") {
window.alert(result.error);
}
return;
}
const errorCount = result.data.errors.length;
if (errorCount > 0) {
const archivedCount = result.data.archivedWorkspaceIds.length;
const skippedCount = result.data.skippedWorkspaceIds.length;
const MAX_ERRORS_TO_SHOW = 5;
const shownErrors = result.data.errors
.slice(0, MAX_ERRORS_TO_SHOW)
.map((e) => `- ${e.workspaceId}: ${e.error}`)
.join("\n");
const remainingCount = Math.max(0, errorCount - MAX_ERRORS_TO_SHOW);
const remainingSuffix = remainingCount > 0 ? `\n… and ${remainingCount} more.` : "";
if (typeof window !== "undefined") {
window.alert(
`Archived merged workspaces with some errors.\n\nArchived: ${archivedCount}\nSkipped: ${skippedCount}\nErrors: ${errorCount}\n\nErrors:\n${shownErrors}${remainingSuffix}`
);
}
}
} catch (error) {
const message = getErrorMessage(error);
if (typeof window !== "undefined") {
window.alert(message);
}
}
},
[api]
);
const getBranchesForProject = useCallback(
async (projectPath: string): Promise<BranchListResult> => {
if (!api) {
return { branches: [], recommendedTrunk: null };
}
const branchResult = await api.projects.listBranches({ projectPath });
const sanitizedBranches = branchResult.branches.filter(
(branch): branch is string => typeof branch === "string"
);
const recommended =
branchResult.recommendedTrunk && sanitizedBranches.includes(branchResult.recommendedTrunk)
? branchResult.recommendedTrunk
: (sanitizedBranches[0] ?? null);
return {
branches: sanitizedBranches,
recommendedTrunk: recommended,
};
},
[api]
);
const selectWorkspaceFromPalette = useCallback(
(selection: WorkspaceSelection) => {
setSelectedWorkspace(selection);
},
[setSelectedWorkspace]
);
const removeWorkspaceFromPalette = useCallback(
async (workspaceId: string) => removeWorkspace(workspaceId),
[removeWorkspace]
);
const updateTitleFromPalette = useCallback(
async (workspaceId: string, newTitle: string) => updateWorkspaceTitle(workspaceId, newTitle),
[updateWorkspaceTitle]
);
const addProjectFromPalette = useCallback(() => {
openProjectCreateModal();
}, [openProjectCreateModal]);
const removeProjectFromPalette = useCallback(
(path: string) => {
void handleRemoveProject(path);
},
[handleRemoveProject]
);
const toggleSidebarFromPalette = useCallback(() => {
setSidebarCollapsed((prev) => !prev);
}, [setSidebarCollapsed]);
const navigateWorkspaceFromPalette = useCallback(
(dir: "next" | "prev") => {
handleNavigateWorkspace(dir);
},
[handleNavigateWorkspace]
);
registerParamsRef.current = {
userProjects,
workspaceMetadata,
selectedWorkspace,
themePreference,
getThinkingLevel: getThinkingLevelForWorkspace,
onSetThinkingLevel: setThinkingLevelFromPalette,
onStartWorkspaceCreation: openNewWorkspaceFromPalette,
onStartMultiProjectWorkspaceCreation: openNewMultiProjectWorkspaceFromPalette,
multiProjectWorkspacesEnabled,
onArchiveMergedWorkspacesInProject: archiveMergedWorkspacesInProjectFromPalette,
getBranchesForProject,
onSelectWorkspace: selectWorkspaceFromPalette,
onRemoveWorkspace: removeWorkspaceFromPalette,
onUpdateTitle: updateTitleFromPalette,
onAddProject: addProjectFromPalette,
onRemoveProject: removeProjectFromPalette,
onToggleSidebar: toggleSidebarFromPalette,
onNavigateWorkspace: navigateWorkspaceFromPalette,
onOpenWorkspaceInTerminal: (workspaceId, runtimeConfig) => {
// Best-effort only. Palette actions should never throw.
void openWorkspaceInTerminal(workspaceId, runtimeConfig).catch(() => {
// Errors are surfaced elsewhere (toasts/logs) and users can retry.
});
},
onToggleTheme: toggleTheme,
onSetTheme: setThemePreference,
onOpenSettings: openSettings,
layoutPresets,
onApplyLayoutSlot: (workspaceId, slot) => {
void applySlotToWorkspace(workspaceId, slot).catch(() => {
// Best-effort only.
});
},
onCaptureLayoutSlot: async (workspaceId, slot, name) => {
try {
await saveCurrentWorkspaceToSlot(workspaceId, slot, name);
} catch {
// Best-effort only.
}
},
onClearTimingStats: (workspaceId: string) => workspaceStore.clearTimingStats(workspaceId),
api,
confirmDialog,
};
useEffect(() => {
const unregister = registerSource(() => {
const params = registerParamsRef.current;
if (!params) return [];
// Compute streaming models here (only when command palette opens)
const allStates = workspaceStore.getAllStates();
const selectedWorkspaceState = params.selectedWorkspace
? (allStates.get(params.selectedWorkspace.workspaceId) ?? null)
: null;
const streamingModels = new Map<string, string>();
for (const [workspaceId, state] of allStates) {
if (state.canInterrupt && state.currentModel) {
streamingModels.set(workspaceId, state.currentModel);
}
}
const factories = buildCoreSources({
...params,
streamingModels,
selectedWorkspaceState,
});
const actions: CommandAction[] = [];
for (const factory of factories) {
actions.push(...factory());
}
return actions;
});
return unregister;
}, [registerSource, workspaceStore]);
// Handle keyboard shortcuts
useEffect(() => {
const handleKeyDown = (e: KeyboardEvent) => {
if (e.defaultPrevented) {
return;
}
if (matchesKeybind(e, KEYBINDS.NEXT_WORKSPACE)) {
e.preventDefault();
handleNavigateWorkspace("next");
} else if (matchesKeybind(e, KEYBINDS.PREV_WORKSPACE)) {
e.preventDefault();
handleNavigateWorkspace("prev");
} else if (
matchesKeybind(e, KEYBINDS.OPEN_COMMAND_PALETTE) ||
matchesKeybind(e, KEYBINDS.OPEN_COMMAND_PALETTE_ACTIONS)
) {
e.preventDefault();
if (isCommandPaletteOpen) {
closeCommandPalette();
} else {
// Alternate palette shortcut opens in command mode (with ">") while the
// primary Ctrl/Cmd+Shift+P shortcut opens default workspace-switch mode.
const initialQuery = matchesKeybind(e, KEYBINDS.OPEN_COMMAND_PALETTE_ACTIONS)
? ">"
: undefined;
openCommandPalette(initialQuery);
}
} else if (matchesKeybind(e, KEYBINDS.TOGGLE_SIDEBAR)) {
e.preventDefault();
setSidebarCollapsed((prev) => !prev);
} else if (matchesKeybind(e, KEYBINDS.OPEN_SETTINGS)) {
e.preventDefault();
openSettings();
} else if (matchesKeybind(e, KEYBINDS.OPEN_ANALYTICS)) {
e.preventDefault();
if (isAnalyticsOpen) {
navigateFromAnalytics();
} else {
navigateToAnalytics();
}
} else if (matchesKeybind(e, KEYBINDS.NAVIGATE_BACK)) {
e.preventDefault();
void navigate(-1);
} else if (matchesKeybind(e, KEYBINDS.NAVIGATE_FORWARD)) {
e.preventDefault();
void navigate(1);
}
};
window.addEventListener("keydown", handleKeyDown);
return () => window.removeEventListener("keydown", handleKeyDown);
}, [
handleNavigateWorkspace,
setSidebarCollapsed,
isCommandPaletteOpen,
closeCommandPalette,
openCommandPalette,
openSettings,
isAnalyticsOpen,
navigateToAnalytics,
navigateFromAnalytics,
navigate,
]);
// Mouse back/forward buttons (buttons 3 and 4)
useEffect(() => {
const handleMouseNavigation = (e: MouseEvent) => {
if (e.button === 3) {
e.preventDefault();
void navigate(-1);
} else if (e.button === 4) {
e.preventDefault();
void navigate(1);
}
};
// Capture phase fires before Chrome's default back/forward handling
window.addEventListener("mousedown", handleMouseNavigation, true);
return () => window.removeEventListener("mousedown", handleMouseNavigation, true);
}, [navigate]);
useEffect(() => {
// Only needed in standalone PWA mode — normal browser tabs should have standard back/forward behavior
const isStandalone = window.matchMedia("(display-mode: standalone)").matches;
if (window.api || !isStandalone) return;
// Push a dummy state so back button has somewhere to go without leaving the app
window.history.pushState({ mux: true }, "", window.location.href);
const handlePopState = () => {
// Re-push the correct URL from MemoryRouter, not the popped browser URL
const { pathname, search, hash } = locationRef.current;
const correctUrl = new URL(
prependInitialAppProxyBasePath(`${pathname}${search}${hash}`),
window.location.origin
);
window.history.pushState({ mux: true }, "", correctUrl);
};
window.addEventListener("popstate", handlePopState);
return () => window.removeEventListener("popstate", handlePopState);
}, []);
// Layout slot hotkeys (Ctrl/Cmd+Alt+1..9 by default)
useEffect(() => {
const handleKeyDownCapture = (e: KeyboardEvent) => {
handleLayoutSlotHotkeys(e, {
isCommandPaletteOpen,
isSettingsOpen,
selectedWorkspaceId: selectedWorkspace?.workspaceId ?? null,
layoutPresets,
applySlotToWorkspace,
});
};
window.addEventListener("keydown", handleKeyDownCapture, { capture: true });
return () => window.removeEventListener("keydown", handleKeyDownCapture, { capture: true });
}, [
isCommandPaletteOpen,
isSettingsOpen,
selectedWorkspace,
layoutPresets,
applySlotToWorkspace,
]);
// Subscribe to menu bar "Open Settings" (macOS Cmd+, from app menu)
useEffect(() => {
if (!api) return;
const abortController = new AbortController();
const signal = abortController.signal;
(async () => {
try {
const iterator = await api.menu.onOpenSettings(undefined, { signal });
for await (const _ of iterator) {
if (signal.aborted) break;
openSettings();
}
} catch {
// Subscription cancelled via abort signal - expected on cleanup
}
})();
return () => abortController.abort();
}, [api, openSettings]);
// Handle workspace fork switch event
useEffect(() => {
const handleForkSwitch = (e: Event) => {
if (!isWorkspaceForkSwitchEvent(e)) return;
const workspaceInfo = e.detail;
// Ensure the workspace's project is present in the sidebar config.
//
// IMPORTANT: don't early-return here. In practice this event can fire before
// ProjectContext has finished loading (or before a refresh runs), and returning
// would make the forked workspace appear "missing" until a later refresh.
const project = userProjects.get(workspaceInfo.projectPath);
if (!project) {
console.warn(
`[Frontend] Project not found for forked workspace path: ${workspaceInfo.projectPath} (will refresh)`
);
void refreshProjects();
}
// DEFENSIVE: Ensure createdAt exists
if (!workspaceInfo.createdAt) {
console.warn(
`[Frontend] Workspace ${workspaceInfo.id} missing createdAt in fork switch - using default (2025-01-01)`
);
workspaceInfo.createdAt = "2025-01-01T00:00:00.000Z";
}
// Update metadata Map immediately (don't wait for async metadata event)
// This ensures the title bar effect has the workspace name available
setWorkspaceMetadata((prev) => {
const updated = new Map(prev);
updated.set(workspaceInfo.id, workspaceInfo);
return updated;
});
// Switch to the new workspace
setSelectedWorkspace(toWorkspaceSelection(workspaceInfo));
};
window.addEventListener(CUSTOM_EVENTS.WORKSPACE_FORK_SWITCH, handleForkSwitch as EventListener);
return () =>
window.removeEventListener(
CUSTOM_EVENTS.WORKSPACE_FORK_SWITCH,
handleForkSwitch as EventListener
);
}, [userProjects, refreshProjects, setSelectedWorkspace, setWorkspaceMetadata]);
// Set up navigation callback for notification clicks
useEffect(() => {
const navigateToWorkspace = (workspaceId: string) => {
const metadata = workspaceMetadataRef.current.get(workspaceId);
if (metadata) {
setSelectedWorkspace(toWorkspaceSelection(metadata));
}
};
// Single source of truth: WorkspaceStore owns the navigation callback.
// Browser notifications and Electron notification clicks both route through this.
workspaceStore.setNavigateToWorkspace(navigateToWorkspace);
// Callback for "notify on response" feature - fires when any assistant response completes.
// Only notify when isFinal=true (assistant done with all work, no more active streams).
// finalText is extracted by the aggregator (text after tool calls).
// completion carries notification-policy metadata (compaction vs normal response,
// and whether another queued/auto follow-up will immediately take over).
const handleResponseComplete = (event: ResponseCompleteEvent) => {
// Only notify on final message (when assistant is done with all work).
if (!event.isFinal) {
return;
}