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