-
Notifications
You must be signed in to change notification settings - Fork 109
Expand file tree
/
Copy pathApp.tsx
More file actions
712 lines (637 loc) · 26.2 KB
/
App.tsx
File metadata and controls
712 lines (637 loc) · 26.2 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
import { useEffect, useCallback, useRef } from "react";
import "./styles/globals.css";
import { useWorkspaceContext } from "./contexts/WorkspaceContext";
import { useProjectContext } from "./contexts/ProjectContext";
import type { WorkspaceSelection } from "./components/ProjectSidebar";
import { LeftSidebar } from "./components/LeftSidebar";
import { ProjectCreateModal } from "./components/ProjectCreateModal";
import { AIView } from "./components/AIView";
import { ErrorBoundary } from "./components/ErrorBoundary";
import { usePersistedState, updatePersistedState } from "./hooks/usePersistedState";
import { matchesKeybind, KEYBINDS } from "./utils/ui/keybinds";
import { buildSortedWorkspacesByProject } from "./utils/ui/workspaceFiltering";
import { useResumeManager } from "./hooks/useResumeManager";
import { useUnreadTracking } from "./hooks/useUnreadTracking";
import { useWorkspaceStoreRaw, useWorkspaceRecency } from "./stores/WorkspaceStore";
import { ChatInput } from "./components/ChatInput/index";
import type { ChatInputAPI } from "./components/ChatInput/types";
import { useStableReference, compareMaps } from "./hooks/useStableReference";
import { CommandRegistryProvider, useCommandRegistry } from "./contexts/CommandRegistryContext";
import { useOpenTerminal } from "./hooks/useOpenTerminal";
import type { CommandAction } from "./contexts/CommandRegistryContext";
import { ModeProvider } from "./contexts/ModeContext";
import { ProviderOptionsProvider } from "./contexts/ProviderOptionsContext";
import { ThemeProvider, useTheme, type ThemeMode } from "./contexts/ThemeContext";
import { ThinkingProvider } from "./contexts/ThinkingContext";
import { CommandPalette } from "./components/CommandPalette";
import { buildCoreSources, type BuildSourcesParams } from "./utils/commands/sources";
import type { ThinkingLevel } from "@/common/types/thinking";
import { CUSTOM_EVENTS } from "@/common/constants/events";
import { isWorkspaceForkSwitchEvent } from "./utils/workspaceEvents";
import { getThinkingLevelKey } from "@/common/constants/storage";
import type { BranchListResult } from "@/common/orpc/types";
import { useTelemetry } from "./hooks/useTelemetry";
import { getRuntimeTypeForTelemetry } from "@/common/telemetry";
import { useStartWorkspaceCreation, getFirstProjectPath } from "./hooks/useStartWorkspaceCreation";
import { useAPI } from "@/browser/contexts/API";
import { AuthTokenModal } from "@/browser/components/AuthTokenModal";
import { SettingsProvider, useSettings } from "./contexts/SettingsContext";
import { SettingsModal } from "./components/Settings/SettingsModal";
import { TutorialProvider } from "./contexts/TutorialContext";
const THINKING_LEVELS: ThinkingLevel[] = ["off", "low", "medium", "high"];
function AppInner() {
// Get workspace state from context
const {
workspaceMetadata,
setWorkspaceMetadata,
removeWorkspace,
renameWorkspace,
selectedWorkspace,
setSelectedWorkspace,
pendingNewWorkspaceProject,
beginWorkspaceCreation,
clearPendingWorkspaceCreation,
} = useWorkspaceContext();
const { theme, setTheme, toggleTheme } = useTheme();
const { open: openSettings } = useSettings();
const setThemePreference = useCallback(
(nextTheme: ThemeMode) => {
setTheme(nextTheme);
},
[setTheme]
);
const { api, status, error, authenticate } = useAPI();
const {
projects,
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("sidebarCollapsed", isMobile);
const defaultProjectPath = getFirstProjectPath(projects);
const creationChatInputRef = useRef<ChatInputAPI | null>(null);
const creationProjectPath = !selectedWorkspace
? (pendingNewWorkspaceProject ?? (projects.size === 1 ? defaultProjectPath : null))
: null;
const handleCreationChatReady = useCallback((api: ChatInputAPI) => {
creationChatInputRef.current = api;
api.focus();
}, []);
const startWorkspaceCreation = useStartWorkspaceCreation({
projects,
beginWorkspaceCreation,
setSelectedWorkspace,
});
useEffect(() => {
if (creationProjectPath) {
creationChatInputRef.current?.focus();
}
}, [creationProjectPath]);
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);
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
const { lastReadTimestamps, onToggleUnread } = useUnreadTracking(selectedWorkspace);
// Auto-resume interrupted streams on app startup and when failures occur
useResumeManager();
// Sync selectedWorkspace with URL hash
useEffect(() => {
if (selectedWorkspace) {
// Update URL with workspace ID
const newHash = `#workspace=${encodeURIComponent(selectedWorkspace.workspaceId)}`;
if (window.location.hash !== newHash) {
window.history.replaceState(null, "", newHash);
}
// Update window title with workspace name
const metadata = workspaceMetadata.get(selectedWorkspace.workspaceId);
const workspaceName = metadata?.name ?? selectedWorkspace.workspaceId;
const title = `${workspaceName} - ${selectedWorkspace.projectName} - mux`;
// Set document.title locally for browser mode, call backend for Electron
document.title = title;
void api?.window.setTitle({ title });
} else {
// Clear hash when no workspace selected
if (window.location.hash) {
window.history.replaceState(null, "", window.location.pathname);
}
// 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
useEffect(() => {
if (selectedWorkspace) {
const metadata = workspaceMetadata.get(selectedWorkspace.workspaceId);
if (!metadata) {
// Workspace was deleted
console.warn(
`Workspace ${selectedWorkspace.workspaceId} no longer exists, clearing selection`
);
setSelectedWorkspace(null);
if (window.location.hash) {
window.history.replaceState(null, "", window.location.pathname);
}
} else if (!selectedWorkspace.namedWorkspacePath && metadata.namedWorkspacePath) {
// Old localStorage entry missing namedWorkspacePath - update it once
console.log(`Updating workspace ${selectedWorkspace.workspaceId} with missing fields`);
setSelectedWorkspace({
workspaceId: metadata.id,
projectPath: metadata.projectPath,
projectName: metadata.projectName,
namedWorkspacePath: metadata.namedWorkspacePath,
});
}
}
}, [selectedWorkspace, workspaceMetadata, setSelectedWorkspace]);
const openWorkspaceInTerminal = useOpenTerminal();
const handleRemoveProject = useCallback(
async (path: string): Promise<{ success: boolean; error?: 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(projects, workspaceMetadata, workspaceRecency),
(prev, next) =>
compareMaps(prev, next, (a, b) => {
if (a.length !== b.length) return false;
// Check ID, name, and status to detect changes
return a.every((meta, i) => {
const other = b[i];
return (
other &&
meta.id === other.id &&
meta.name === other.name &&
meta.status === other.status
);
});
}),
[projects, workspaceMetadata, workspaceRecency]
);
const handleNavigateWorkspace = useCallback(
(direction: "next" | "prev") => {
if (!selectedWorkspace) return;
// Use sorted workspaces to match visual order in sidebar
const sortedWorkspaces = sortedWorkspacesByProject.get(selectedWorkspace.projectPath);
if (!sortedWorkspaces || sortedWorkspaces.length <= 1) return;
// Find current workspace index in sorted list
const currentIndex = sortedWorkspaces.findIndex(
(metadata) => metadata.id === selectedWorkspace.workspaceId
);
if (currentIndex === -1) return;
// Calculate next/prev index with wrapping
let targetIndex: number;
if (direction === "next") {
targetIndex = (currentIndex + 1) % sortedWorkspaces.length;
} else {
targetIndex = currentIndex === 0 ? sortedWorkspaces.length - 1 : currentIndex - 1;
}
const targetMetadata = sortedWorkspaces[targetIndex];
if (!targetMetadata) return;
setSelectedWorkspace({
projectPath: selectedWorkspace.projectPath,
projectName: selectedWorkspace.projectName,
namedWorkspacePath: targetMetadata.namedWorkspacePath,
workspaceId: targetMetadata.id,
});
},
[selectedWorkspace, sortedWorkspacesByProject, setSelectedWorkspace]
);
// Register command sources with registry
const {
registerSource,
isOpen: isCommandPaletteOpen,
open: openCommandPalette,
close: closeCommandPalette,
} = useCommandRegistry();
const getThinkingLevelForWorkspace = useCallback((workspaceId: string): ThinkingLevel => {
if (!workspaceId) {
return "off";
}
if (typeof window === "undefined" || !window.localStorage) {
return "off";
}
try {
const key = getThinkingLevelKey(workspaceId);
const stored = window.localStorage.getItem(key);
if (!stored || stored === "undefined") {
return "off";
}
const parsed = JSON.parse(stored) as ThinkingLevel;
return THINKING_LEVELS.includes(parsed) ? parsed : "off";
} catch (error) {
console.warn("Failed to read thinking level", error);
return "off";
}
}, []);
const setThinkingLevelFromPalette = useCallback((workspaceId: string, level: ThinkingLevel) => {
if (!workspaceId) {
return;
}
const normalized = THINKING_LEVELS.includes(level) ? level : "off";
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);
// Dispatch toast notification event for UI feedback
if (typeof window !== "undefined") {
window.dispatchEvent(
new CustomEvent(CUSTOM_EVENTS.THINKING_LEVEL_TOAST, {
detail: { workspaceId, level: normalized },
})
);
}
}, []);
const registerParamsRef = useRef<BuildSourcesParams | null>(null);
const openNewWorkspaceFromPalette = useCallback(
(projectPath: string) => {
startWorkspaceCreation(projectPath);
},
[startWorkspaceCreation]
);
const getBranchesForProject = useCallback(
async (projectPath: string): Promise<BranchListResult> => {
if (!api) {
return { branches: [], recommendedTrunk: "" };
}
const branchResult = await api.projects.listBranches({ projectPath });
const sanitizedBranches = branchResult.branches.filter(
(branch): branch is string => typeof branch === "string"
);
const recommended = sanitizedBranches.includes(branchResult.recommendedTrunk)
? branchResult.recommendedTrunk
: (sanitizedBranches[0] ?? "");
return {
branches: sanitizedBranches,
recommendedTrunk: recommended,
};
},
[api]
);
const selectWorkspaceFromPalette = useCallback(
(selection: WorkspaceSelection) => {
setSelectedWorkspace(selection);
},
[setSelectedWorkspace]
);
const removeWorkspaceFromPalette = useCallback(
async (workspaceId: string) => removeWorkspace(workspaceId),
[removeWorkspace]
);
const renameWorkspaceFromPalette = useCallback(
async (workspaceId: string, newName: string) => renameWorkspace(workspaceId, newName),
[renameWorkspace]
);
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 = {
projects,
workspaceMetadata,
selectedWorkspace,
theme,
getThinkingLevel: getThinkingLevelForWorkspace,
onSetThinkingLevel: setThinkingLevelFromPalette,
onStartWorkspaceCreation: openNewWorkspaceFromPalette,
getBranchesForProject,
onSelectWorkspace: selectWorkspaceFromPalette,
onRemoveWorkspace: removeWorkspaceFromPalette,
onRenameWorkspace: renameWorkspaceFromPalette,
onAddProject: addProjectFromPalette,
onRemoveProject: removeProjectFromPalette,
onToggleSidebar: toggleSidebarFromPalette,
onNavigateWorkspace: navigateWorkspaceFromPalette,
onOpenWorkspaceInTerminal: openWorkspaceInTerminal,
onToggleTheme: toggleTheme,
onSetTheme: setThemePreference,
onOpenSettings: openSettings,
api,
};
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 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 });
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 (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)) {
e.preventDefault();
if (isCommandPaletteOpen) {
closeCommandPalette();
} else {
openCommandPalette();
}
} else if (matchesKeybind(e, KEYBINDS.TOGGLE_SIDEBAR)) {
e.preventDefault();
setSidebarCollapsed((prev) => !prev);
} else if (matchesKeybind(e, KEYBINDS.OPEN_SETTINGS)) {
e.preventDefault();
openSettings();
}
};
window.addEventListener("keydown", handleKeyDown);
return () => window.removeEventListener("keydown", handleKeyDown);
}, [
handleNavigateWorkspace,
setSidebarCollapsed,
isCommandPaletteOpen,
closeCommandPalette,
openCommandPalette,
openSettings,
]);
// 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;
// Find the project in config
const project = projects.get(workspaceInfo.projectPath);
if (!project) {
console.error(`Project not found for path: ${workspaceInfo.projectPath}`);
return;
}
// 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({
workspaceId: workspaceInfo.id,
projectPath: workspaceInfo.projectPath,
projectName: workspaceInfo.projectName,
namedWorkspacePath: workspaceInfo.namedWorkspacePath,
});
};
window.addEventListener(CUSTOM_EVENTS.WORKSPACE_FORK_SWITCH, handleForkSwitch as EventListener);
return () =>
window.removeEventListener(
CUSTOM_EVENTS.WORKSPACE_FORK_SWITCH,
handleForkSwitch as EventListener
);
}, [projects, setSelectedWorkspace, setWorkspaceMetadata]);
const handleProviderConfig = useCallback(
async (provider: string, keyPath: string[], value: string) => {
if (!api) {
throw new Error("API not connected");
}
const result = await api.providers.setProviderConfig({ provider, keyPath, value });
if (!result.success) {
throw new Error(result.error);
}
},
[api]
);
// Show auth modal if authentication is required
if (status === "auth_required") {
return <AuthTokenModal isOpen={true} onSubmit={authenticate} error={error} />;
}
return (
<>
<div className="bg-bg-dark mobile-layout flex h-screen overflow-hidden">
<LeftSidebar
lastReadTimestamps={lastReadTimestamps}
onToggleUnread={onToggleUnread}
collapsed={sidebarCollapsed}
onToggleCollapsed={handleToggleSidebar}
sortedWorkspacesByProject={sortedWorkspacesByProject}
workspaceRecency={workspaceRecency}
/>
<div className="mobile-main-content flex min-w-0 flex-1 flex-col overflow-hidden">
<div className="mobile-layout flex flex-1 overflow-hidden">
{selectedWorkspace ? (
(() => {
const currentMetadata = workspaceMetadata.get(selectedWorkspace.workspaceId);
// Guard: Don't render AIView if workspace metadata not found.
// This can happen when selectedWorkspace (from localStorage) refers to a
// deleted workspace, or during a race condition on reload before the
// validation effect clears the stale selection.
if (!currentMetadata) {
return null;
}
// Use metadata.name for workspace name (works for both worktree and local runtimes)
// Fallback to path-based derivation for legacy compatibility
const workspaceName =
currentMetadata.name ??
selectedWorkspace.namedWorkspacePath?.split("/").pop() ??
selectedWorkspace.workspaceId;
// Use live metadata path (updates on rename) with fallback to initial path
const workspacePath =
currentMetadata.namedWorkspacePath ?? selectedWorkspace.namedWorkspacePath ?? "";
return (
<ErrorBoundary
workspaceInfo={`${selectedWorkspace.projectName}/${workspaceName}`}
>
<AIView
key={selectedWorkspace.workspaceId}
workspaceId={selectedWorkspace.workspaceId}
projectPath={selectedWorkspace.projectPath}
projectName={selectedWorkspace.projectName}
branch={workspaceName}
namedWorkspacePath={workspacePath}
runtimeConfig={currentMetadata.runtimeConfig}
incompatibleRuntime={currentMetadata.incompatibleRuntime}
status={currentMetadata.status}
/>
</ErrorBoundary>
);
})()
) : creationProjectPath ? (
(() => {
const projectPath = creationProjectPath;
const projectName =
projectPath.split("/").pop() ?? projectPath.split("\\").pop() ?? "Project";
return (
<ModeProvider projectPath={projectPath}>
<ProviderOptionsProvider>
<ThinkingProvider projectPath={projectPath}>
<ChatInput
variant="creation"
projectPath={projectPath}
projectName={projectName}
onProviderConfig={handleProviderConfig}
onReady={handleCreationChatReady}
onWorkspaceCreated={(metadata) => {
// IMPORTANT: Add workspace to store FIRST (synchronous) to ensure
// the store knows about it before React processes the state updates.
// This prevents race conditions where the UI tries to access the
// workspace before the store has created its aggregator.
workspaceStore.addWorkspace(metadata);
// Add to workspace metadata map (triggers React state update)
setWorkspaceMetadata((prev) =>
new Map(prev).set(metadata.id, metadata)
);
// Only switch to new workspace if user hasn't selected another one
// during the creation process (selectedWorkspace was null when creation started)
setSelectedWorkspace((current) => {
if (current !== null) {
// User has already selected another workspace - don't override
return current;
}
return {
workspaceId: metadata.id,
projectPath: metadata.projectPath,
projectName: metadata.projectName,
namedWorkspacePath: metadata.namedWorkspacePath,
};
});
// Track telemetry
telemetry.workspaceCreated(
metadata.id,
getRuntimeTypeForTelemetry(metadata.runtimeConfig)
);
// Clear pending state
clearPendingWorkspaceCreation();
}}
onCancel={
pendingNewWorkspaceProject
? () => {
// User cancelled workspace creation - clear pending state
clearPendingWorkspaceCreation();
}
: undefined
}
/>
</ThinkingProvider>
</ProviderOptionsProvider>
</ModeProvider>
);
})()
) : (
<div
className="[&_p]:text-muted [&_h2]:text-foreground mx-auto w-full max-w-3xl text-center [&_h2]:mb-4 [&_h2]:font-bold [&_h2]:tracking-tight [&_p]:leading-[1.6]"
style={{
padding: "clamp(40px, 10vh, 100px) 20px",
fontSize: "clamp(14px, 2vw, 16px)",
}}
>
<h2 style={{ fontSize: "clamp(24px, 5vw, 36px)", letterSpacing: "-1px" }}>
Welcome to Mux
</h2>
<p>Select a workspace from the sidebar or add a new one to get started.</p>
</div>
)}
</div>
</div>
<CommandPalette
getSlashContext={() => ({
providerNames: [],
workspaceId: selectedWorkspace?.workspaceId,
})}
/>
<ProjectCreateModal
isOpen={isProjectCreateModalOpen}
onClose={closeProjectCreateModal}
onSuccess={addProject}
/>
<SettingsModal />
</div>
</>
);
}
function App() {
return (
<ThemeProvider>
<SettingsProvider>
<TutorialProvider>
<CommandRegistryProvider>
<AppInner />
</CommandRegistryProvider>
</TutorialProvider>
</SettingsProvider>
</ThemeProvider>
);
}
export default App;