Open History to see the last commit
1import { useAtomValue } from "@effect/atom-react";
2import * as Schema from "effect/Schema";
3import {
4 useEffect,
5 useRef,
6 useState,
7 useSyncExternalStore,
8 type CSSProperties,
9 type ReactNode,
10} from "react";
11import { useLocation, useNavigate } from "@tanstack/react-router";
12
13import { isCommandPaletteOpen } from "../commandPaletteBus";
14import { isElectron } from "../env";
15import {
16 releaseThreadUndoShortcut,
17 threadUndoClaimsShortcut,
18 undoLatestThreadAction,
19} from "../hooks/showThreadUndoNotice";
20import { getLocalStorageItem, removeLocalStorageItem } from "../hooks/useLocalStorage";
21import {
22 isRichTextBoldShortcut,
23 resolveShortcutCommand,
24 shortcutLabelForCommand,
25} from "../keybindings";
26import { isEditableFocused } from "../lib/editableFocus";
27import { isPreviewFocused } from "../lib/previewFocus";
28import { isTerminalFocused } from "../lib/terminalFocus";
29import { isModelPickerOpen } from "../modelPickerVisibility";
30import { selectActiveRightPanel, useRightPanelStore } from "../rightPanelStore";
31import { selectThreadTerminalUiState, useTerminalUiStateStore } from "../terminalUiStateStore";
32import { cn, isMacPlatform } from "../lib/utils";
33import { primaryServerKeybindingsAtom } from "../state/server";
34import { useEnvironmentIdentificationMode, useLegacySidebarEnabled } from "../hooks/useSettings";
35import {
36 PanelAnimationSuppressionProvider,
37 usePanelAnimationSettings,
38 usePanelNavigationSuppression,
39} from "../panelAnimations";
40import LegacyThreadSidebar from "./LegacySidebar";
41import { useThreadVisitedMigration } from "../hooks/useThreadVisitedMigration";
42import ThreadSidebar from "./Sidebar";
43import { SettingsSidebarNav } from "./settings/SettingsSidebarNav";
44import { SidebarBrandWidthProbe, SidebarChromeHeader } from "./sidebar/SidebarChrome";
45import { MainAppLocationTracker } from "./sidebar/mainAppLocation";
46import type { SidebarRouteReveal } from "./sidebar/routeReveal";
47import { useSidebarStageBackdropVariant } from "./SidebarStageBackdrop";
48import { useProjects } from "../state/entities";
49import {
50 clampThreadSidebarWidth,
51 resolveInitialThreadSidebarWidth,
52 resolveThreadSidebarMaximumWidth,
53 resolveThreadSidebarMinimumWidth,
54 THREAD_MAIN_CONTENT_MIN_WIDTH,
55 THREAD_SIDEBAR_WIDTH_STORAGE_KEY,
56} from "./threadSidebarWidth";
57import {
58 Sidebar,
59 SidebarProvider,
60 SidebarRail,
61 SidebarTrigger,
62 useSidebar,
63 useSidebarVisibility,
64} from "./ui/sidebar";
65import { Tooltip, TooltipPopup, TooltipTrigger } from "./ui/tooltip";
66import { useThreadRouteRef } from "../hooks/useThreadRouteTarget";
67
68const MACOS_TRAFFIC_LIGHTS_LEFT_INSET = "var(--desktop-window-controls-inset, 90px)";
69
70function subscribeToViewportWidth(onChange: () => void): () => void {
71 window.addEventListener("resize", onChange);
72 return () => window.removeEventListener("resize", onChange);
73}
74
75function readViewportWidth(): number {
76 return window.innerWidth;
77}
78
79// getWindowFullscreenState is a synchronous IPC round trip, so the snapshot is cached
80// and only re-read when a subscription starts.
81let windowFullscreenSnapshot: boolean | null = null;
82
83function macosDesktopBridge() {
84 if (!isElectron || !isMacPlatform(navigator.platform)) return null;
85 return window.desktopBridge ?? null;
86}
87
88function subscribeToWindowFullscreen(onChange: () => void): () => void {
89 const bridge = macosDesktopBridge();
90 if (
91 typeof bridge?.getWindowFullscreenState !== "function" ||
92 typeof bridge.onWindowFullscreenStateChange !== "function"
93 ) {
94 return () => {};
95 }
96 const unsubscribe = bridge.onWindowFullscreenStateChange((fullscreen) => {
97 windowFullscreenSnapshot = fullscreen;
98 onChange();
99 });
100 // The window may have changed state between the first render and this subscription.
101 windowFullscreenSnapshot = bridge.getWindowFullscreenState();
102 return () => {
103 unsubscribe();
104 windowFullscreenSnapshot = null;
105 };
106}
107
108function readWindowFullscreen(): boolean {
109 if (windowFullscreenSnapshot === null) {
110 const getWindowFullscreenState = macosDesktopBridge()?.getWindowFullscreenState;
111 windowFullscreenSnapshot =
112 typeof getWindowFullscreenState === "function" ? getWindowFullscreenState() : false;
113 }
114 return windowFullscreenSnapshot;
115}
116
117function readInitialThreadSidebarWidth(): number {
118 try {
119 return resolveInitialThreadSidebarWidth(
120 getLocalStorageItem(THREAD_SIDEBAR_WIDTH_STORAGE_KEY, Schema.Finite),
121 window.innerWidth,
122 );
123 } catch (error) {
124 console.error("Could not read persisted thread sidebar width.", error);
125 return resolveInitialThreadSidebarWidth(null, window.innerWidth);
126 }
127}
128
129function SidebarControl() {
130 const usagePageOpen = useLocation({ select: (location) => location.pathname === "/usage" });
131 const keybindings = useAtomValue(primaryServerKeybindingsAtom);
132 const { toggleSidebar, isMobile, mobileSheetMounted } = useSidebar();
133 const isSidebarVisible = useSidebarVisibility();
134 const environmentIdentificationMode = useEnvironmentIdentificationMode();
135 const stageBackdropVariant = useSidebarStageBackdropVariant(
136 environmentIdentificationMode === "artwork",
137 );
138 const shortcutLabel = shortcutLabelForCommand(keybindings, "sidebar.toggle", {
139 context: { usagePageOpen },
140 });
141
142 useEffect(() => {
143 const onKeyDown = (event: KeyboardEvent) => {
144 if (event.defaultPrevented) return;
145 if (
146 event.target instanceof HTMLElement &&
147 event.target.closest("[data-keybinding-capture]")
148 ) {
149 return;
150 }
151 if (
152 isRichTextBoldShortcut(event, window.getSelection()) &&
153 event.target instanceof HTMLElement &&
154 event.target.closest('[data-composer-rich-text="true"]')
155 ) {
156 // The rich-text composer claims Mod+B only to bold selected text;
157 // the toggle stays available everywhere else.
158 return;
159 }
160 if (
161 resolveShortcutCommand(event, keybindings, { context: { usagePageOpen } }) !==
162 "sidebar.toggle"
163 )
164 return;
165
166 event.preventDefault();
167 event.stopPropagation();
168 toggleSidebar();
169 };
170
171 window.addEventListener("keydown", onKeyDown, true);
172 const unsubscribe = window.desktopBridge?.onMenuAction((action) => {
173 if (action === "sidebar.toggle") toggleSidebar();
174 });
175 return () => {
176 window.removeEventListener("keydown", onKeyDown, true);
177 unsubscribe?.();
178 };
179 }, [keybindings, toggleSidebar, usagePageOpen]);
180
181 return (
182 <div
183 className={cn(
184 "pointer-events-none fixed left-[var(--workspace-controls-left)] top-[var(--workspace-controls-top)] z-50 ml-px flex h-[var(--workspace-topbar-height)] items-center",
185 isMobile && mobileSheetMounted && "hidden",
186 )}
187 data-sidebar-control=""
188 >
189 <Tooltip>
190 <TooltipTrigger
191 render={
192 <SidebarTrigger
193 variant={isSidebarVisible && stageBackdropVariant ? "media-navigation" : "ghost"}
194 className={cn(
195 "pointer-events-auto",
196 isSidebarVisible && stageBackdropVariant && "relative top-auto translate-y-0",
197 )}
198 aria-label="Toggle main sidebar"
199 />
200 }
201 />
202 <TooltipPopup side="bottom">
203 Toggle main sidebar{shortcutLabel ? ` (${shortcutLabel})` : ""}
204 </TooltipPopup>
205 </Tooltip>
206 </div>
207 );
208}
209
210function routePanelsOpen(routeThreadRef: ReturnType<typeof useThreadRouteRef>) {
211 if (!routeThreadRef) return { terminalOpen: false, previewOpen: false };
212 return {
213 terminalOpen: selectThreadTerminalUiState(
214 useTerminalUiStateStore.getState().terminalUiStateByThreadKey,
215 routeThreadRef,
216 ).terminalOpen,
217 previewOpen:
218 selectActiveRightPanel(useRightPanelStore.getState().byThreadKey, routeThreadRef) ===
219 "preview",
220 };
221}
222
223export function NavigationHistoryShortcuts() {
224 const usagePageOpen = useLocation({ select: (location) => location.pathname === "/usage" });
225 const keybindings = useAtomValue(primaryServerKeybindingsAtom);
226 const routeThreadRef = useThreadRouteRef();
227
228 useEffect(() => {
229 const onKeyDown = (event: KeyboardEvent) => {
230 if (event.defaultPrevented) return;
231 if (
232 event.target instanceof HTMLElement &&
233 event.target.closest("[data-keybinding-capture]")
234 ) {
235 return;
236 }
237 const command = resolveShortcutCommand(event, keybindings, {
238 context: {
239 terminalFocus: isTerminalFocused(),
240 previewFocus: isPreviewFocused(),
241 ...routePanelsOpen(routeThreadRef),
242 editableFocus: isEditableFocused(event.target),
243 modelPickerOpen: isModelPickerOpen(),
244 usagePageOpen,
245 },
246 });
247 if (command !== "navigation.back" && command !== "navigation.forward") return;
248
249 event.preventDefault();
250 event.stopPropagation();
251 if (command === "navigation.back") window.history.back();
252 else window.history.forward();
253 };
254
255 window.addEventListener("keydown", onKeyDown);
256 return () => window.removeEventListener("keydown", onKeyDown);
257 }, [keybindings, routeThreadRef, usagePageOpen]);
258
259 return null;
260}
261
262const MODIFIER_KEYS = new Set(["Alt", "Control", "Meta", "Shift"]);
263
264// Undoes the thread actions in the sidebar's notice. Mounted wherever the
265// thread sidebar can show; Settings replaces it. Listens in the capture phase
266// so mod+z reaches it before the composer's own undo handler consumes the key.
267function ThreadUndoShortcut() {
268 const keybindings = useAtomValue(primaryServerKeybindingsAtom);
269 const routeThreadRef = useThreadRouteRef();
270 // A collapsed sidebar hides the notice, so text fields keep their own undo.
271 const noticeVisible = useSidebarVisibility();
272 // Outlives the effect: undoing an archive navigates, which re-runs it mid-hold.
273 const heldUndoKey = useRef<string | null>(null);
274
275 useEffect(() => {
276 const onKeyDown = (event: KeyboardEvent) => {
277 // A held key undoes once. Cancel its repeats so they cannot fall through
278 // to the editor's own undo, even after the last notice is gone.
279 if (event.repeat) {
280 if (event.code === heldUndoKey.current) {
281 event.preventDefault();
282 event.stopPropagation();
283 }
284 return;
285 }
286 // A modifier tapped mid-hold leaves the held key repeating.
287 if (!MODIFIER_KEYS.has(event.key)) heldUndoKey.current = null;
288 const command = resolveShortcutCommand(event, keybindings, {
289 context: {
290 terminalFocus: isTerminalFocused(),
291 previewFocus: isPreviewFocused(),
292 ...routePanelsOpen(routeThreadRef),
293 editableFocus:
294 isEditableFocused(event.target) && !(noticeVisible && threadUndoClaimsShortcut()),
295 modelPickerOpen: isModelPickerOpen(),
296 },
297 });
298 if (command !== "thread.undo") {
299 if (!MODIFIER_KEYS.has(event.key)) releaseThreadUndoShortcut();
300 return;
301 }
302 if (isCommandPaletteOpen() || isModelPickerOpen()) return;
303 if (undoLatestThreadAction()) {
304 heldUndoKey.current = event.code;
305 event.preventDefault();
306 event.stopPropagation();
307 }
308 };
309 // Pastes from a menu, dictation and drops edit text without a keypress.
310 const onInput = () => releaseThreadUndoShortcut();
311
312 window.addEventListener("keydown", onKeyDown, true);
313 window.addEventListener("input", onInput, true);
314 return () => {
315 window.removeEventListener("keydown", onKeyDown, true);
316 window.removeEventListener("input", onInput, true);
317 };
318 }, [keybindings, noticeVisible, routeThreadRef]);
319
320 return null;
321}
322
323// Settings swaps the thread sidebar out of the tree. Keep the lightweight
324// project projection subscribed so returning to a draft never renders the
325// zero-project state while the environment snapshot reconnects.
326function ProjectProjectionRetention() {
327 useProjects();
328 return null;
329}
330
331export function AppSidebarLayout({ children }: { children: ReactNode }) {
332 const navigate = useNavigate();
333 const legacySidebarEnabled = useLegacySidebarEnabled();
334 const [sidebarRouteReveal] = useState<SidebarRouteReveal>(() => ({
335 observedKey: null,
336 pendingKey: null,
337 }));
338 const { active: panelAnimationsActive, durationMs: panelAnimationDurationMs } =
339 usePanelAnimationSettings();
340 useThreadVisitedMigration();
341 const pathname = useLocation({ select: (location) => location.pathname });
342 const panelAnimationsSuppressed = usePanelNavigationSuppression(pathname);
343 const routePanelAnimationsActive = panelAnimationsActive && !panelAnimationsSuppressed;
344 const isOnSettings = pathname === "/settings" || pathname.startsWith("/settings/");
345 const isMacosDesktop = isElectron && isMacPlatform(navigator.platform);
346 const [sidebarWidth, setSidebarWidth] = useState(readInitialThreadSidebarWidth);
347 // Subscribed rather than read once: the clamp must track live window size,
348 // and a clamped drag ends with an unchanged width, which skips the re-render
349 // that would otherwise refresh a render-time snapshot.
350 const viewportWidth = useSyncExternalStore(subscribeToViewportWidth, readViewportWidth);
351 const [brandWidth, setBrandWidth] = useState(0);
352 const sidebarMinimumWidth = resolveThreadSidebarMinimumWidth(brandWidth);
353 const sidebarMaximumWidth = resolveThreadSidebarMaximumWidth(viewportWidth, sidebarMinimumWidth);
354 const resetSidebarWidth = () => {
355 try {
356 removeLocalStorageItem(THREAD_SIDEBAR_WIDTH_STORAGE_KEY);
357 } catch (error) {
358 console.error("Could not clear persisted thread sidebar width.", error);
359 }
360 setSidebarWidth(resolveInitialThreadSidebarWidth(null, viewportWidth));
361 };
362 const isWindowFullscreen = useSyncExternalStore(
363 subscribeToWindowFullscreen,
364 readWindowFullscreen,
365 );
366 const windowControlsInsetStyle = (
367 isMacosDesktop && !isWindowFullscreen
368 ? { "--workspace-controls-left": MACOS_TRAFFIC_LIGHTS_LEFT_INSET }
369 : {}
370 ) as CSSProperties;
371 const sidebarProviderStyle = {
372 "--sidebar-width": `${clampThreadSidebarWidth(sidebarWidth, sidebarMinimumWidth, sidebarMaximumWidth)}px`,
373 "--panel-animation-duration": `${panelAnimationDurationMs}ms`,
374 ...windowControlsInsetStyle,
375 } as CSSProperties;
376
377 useEffect(() => {
378 const onMenuAction = window.desktopBridge?.onMenuAction;
379 if (typeof onMenuAction !== "function") {
380 return;
381 }
382
383 const unsubscribe = onMenuAction((action) => {
384 if (action === "open-settings") {
385 const isSettingsRoute = /^\/settings(\/|$)/.test(pathname);
386 if (!isSettingsRoute) {
387 void navigate({ to: "/settings" });
388 }
389 }
390 });
391
392 return () => {
393 unsubscribe?.();
394 };
395 }, [navigate, pathname]);
396
397 return (
398 <PanelAnimationSuppressionProvider value={panelAnimationsSuppressed}>
399 <SidebarProvider
400 className="h-dvh! min-h-0!"
401 data-panel-animations={routePanelAnimationsActive ? "true" : "false"}
402 defaultOpen
403 style={sidebarProviderStyle}
404 >
405 <SidebarBrandWidthProbe onWidthChange={setBrandWidth} />
406 <ProjectProjectionRetention />
407 <Sidebar
408 side="left"
409 collapsible="offcanvas"
410 data-app-sidebar=""
411 role="navigation"
412 aria-label={isOnSettings ? "Settings" : "Threads"}
413 resizable={{
414 maxWidth: sidebarMaximumWidth,
415 minWidth: sidebarMinimumWidth,
416 shouldAcceptWidth: ({ currentWidth, nextWidth, wrapper }) =>
417 nextWidth <= currentWidth ||
418 wrapper.clientWidth - nextWidth >= THREAD_MAIN_CONTENT_MIN_WIDTH,
419 storageKey: THREAD_SIDEBAR_WIDTH_STORAGE_KEY,
420 onResize: setSidebarWidth,
421 }}
422 style={windowControlsInsetStyle}
423 >
424 {isOnSettings ? (
425 <>
426 <SidebarChromeHeader isElectron={isElectron} />
427 <SettingsSidebarNav pathname={pathname} />
428 </>
429 ) : legacySidebarEnabled ? (
430 <LegacyThreadSidebar routeReveal={sidebarRouteReveal} />
431 ) : (
432 <ThreadSidebar routeReveal={sidebarRouteReveal} />
433 )}
434 <SidebarRail onDoubleClick={resetSidebarWidth} />
435 </Sidebar>
436 {children}
437 <SidebarControl />
438 <NavigationHistoryShortcuts />
439 {isOnSettings ? null : <ThreadUndoShortcut />}
440 <MainAppLocationTracker />
441 </SidebarProvider>
442 </PanelAnimationSuppressionProvider>
443 );
444}