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