From 9e94c716f8a0e83cd08db299721669593adac0ce Mon Sep 17 00:00:00 2001 From: yuneng-jiang Date: Mon, 16 Nov 2026 22:19:54 -0800 Subject: [PATCH] refactor(ui): build the dashboard and chat shells on the shadcn Sidebar (#51257) * refactor(ui): build the dashboard and chat shells on the shadcn Sidebar Replace the hand-rolled shared/Sidebar.tsx, the per-shell collapse state and the hand-wired mobile Sheet with the base-vega shadcn Sidebar (SidebarProvider, Sidebar collapsible="icon", SidebarInset, Collapsible nav groups). The primitive and use-mobile hook come straight from the shadcn CLI's output. The only edits are the cn import pointing at @/lib/cva.config and its English strings moving into en.json. Its z-10/z-20 and the hook's setState-in-effect stay as shadcn ships them, so eslint.config.mjs turns those two rules off for those two files. Our look (280/72px widths, 34px rows, 13px text, accent bar, scrollable rail) is carried by className overrides in shared/sidebarStyles.ts. Behaviour the primitive leaves to the app is kept: per-route collapse on /logs, expanding the rail when a group is chosen while collapsed, and closing the mobile drawer on navigation, link clicks and a resize to desktop. The settings wrapper is renamed AppSidebar so it no longer collides with shadcn's SidebarProvider. * fix(ui): close the phone drawer on any link inside it Main closed the dashboard's mobile drawer whenever an a[href] inside it was clicked, which covered the version badge and the account menu's release notes link as well as nav links. One delegated click-capture handler in the nav restores that and replaces the per-link handlers. * fix(ui): keep chat search focused when Cmd+K opens the phone drawer Base UI keeps one pending initial-focus request and lets the last one win. The search dialog is nested in the drawer, so the drawer queued its focus after the search box's and the logo won. Main avoided this with initialFocus={false} on the sheet, which the shadcn Sidebar does not expose. Opening search once the drawer has taken focus restores main's behavior. * chore(ui): exempt the stock shadcn sidebar from the inline object arg budget * chore(ui): exempt shadcn primitives from the inline object arg rule and ratchet its budget * fix(ui): restore main's phone drawers, rail titles and nav semantics on the shadcn sidebar * fix(ui): reset phone drawer groups on open and restore the drawer trigger's dialog semantics * fix(ui): keep the phone drawer closed after a desktop round trip * test(ui): match the stock sidebar's data-active attribute in the customer portal nav test * fix(ui): keep the shell sidebars in step with main across the 768px breakpoint The dashboard nav keeps its scroll position when the window crosses the phone breakpoint and comes back, like main did when it hid the desktop sidebar with CSS. The phone drawer now follows the same (min-width: 768px) query as Tailwind's md variant, so it opens at fractional widths just under 768px under browser zoom. The stock useIsMobile hook only listens to (max-width: 767px), which never fires in that band. Chat search at phone width expands the desktop rail again, so widening after Cmd+K shows the rail expanded as on main. * refactor(ui): use the stock shadcn mobile sidebar and lift chat search out of it Drop the hand-rolled drawer, trigger and scroll memory in favor of the stock Sidebar mobile Sheet and SidebarTrigger. Render the chat search dialog once in ChatShell so Cmd+K on a phone opens only the search box instead of racing the drawer for focus. * test(ui): cover the phone drawer after the desktop rail is collapsed The drawer depends on treating the rail as expanded on phones, and no test failed when that guard was removed in the brand, the nav or the chat shell. Also point the chat design doc at the stock shadcn Sidebar and the lifted search dialog. * refactor(ui): rename leftnav to LeftNav Brings the sidebar component file in line with the PascalCase filename rule and drops its now unused filename-pascal-case suppression. --- .../ui/litellm-dashboard/eslint-budgets.json | 2 +- .../eslint-suppressions.json | 5 - .../ui/litellm-dashboard/eslint.config.mjs | 13 + ...rProvider.test.tsx => AppSidebar.test.tsx} | 10 +- .../{SidebarProvider.tsx => AppSidebar.tsx} | 13 +- .../(dashboard)/layout.integration.test.tsx | 9 +- .../src/app/(dashboard)/layout.test.tsx | 48 +- .../src/app/(dashboard)/layout.tsx | 80 +-- .../app/(dashboard)/legacyPageRoutes.test.ts | 2 +- .../(dashboard)/prompts/_components/README.md | 2 +- .../src/app/chat/layout.integration.test.tsx | 11 +- .../CommandPalette/useVisibleMenuGroups.ts | 2 +- .../components/CommandPalette/utils.test.ts | 2 +- .../src/components/CommandPalette/utils.ts | 2 +- .../src/components/DashboardHeader.tsx | 2 +- .../{leftnav.test.tsx => LeftNav.test.tsx} | 127 +++- .../components/{leftnav.tsx => LeftNav.tsx} | 215 +++--- .../src/components/Navbar/ViewSwitcher.tsx | 5 +- .../chat/ChatShell.integration.test.tsx | 64 +- .../src/components/chat/ChatShell.tsx | 282 ++++---- .../ConversationList.integration.test.tsx | 28 +- .../src/components/chat/ConversationList.tsx | 174 +---- .../chat/ConversationSearchDialog.test.tsx | 44 ++ .../chat/ConversationSearchDialog.tsx | 87 +++ .../src/components/chat/design.md | 11 +- .../liteadmin/LiteAdmin.integration.test.tsx | 5 +- .../src/components/liteadmin/LiteAdmin.tsx | 33 +- .../src/components/page_utils.test.ts | 4 +- .../src/components/page_utils.ts | 2 +- .../src/components/shared/MobileSidebar.tsx | 11 + .../src/components/shared/Sidebar.test.tsx | 36 - .../src/components/shared/Sidebar.tsx | 206 ------ .../src/components/shared/SidebarBrand.tsx | 47 +- .../src/components/shared/sidebarStyles.ts | 27 + .../src/components/ui/sidebar.tsx | 679 ++++++++++++++++++ .../litellm-dashboard/src/hooks/use-mobile.ts | 19 + .../src/i18n/locales/en.json | 14 +- .../tests/CreateKeyPage.expiredToken.test.tsx | 2 +- .../ui/litellm-dashboard/tests/viewport.ts | 46 ++ 39 files changed, 1505 insertions(+), 866 deletions(-) rename litellm/ui/litellm-dashboard/src/app/(dashboard)/components/{SidebarProvider.test.tsx => AppSidebar.test.tsx} (86%) rename litellm/ui/litellm-dashboard/src/app/(dashboard)/components/{SidebarProvider.tsx => AppSidebar.tsx} (67%) rename litellm/ui/litellm-dashboard/src/components/{leftnav.test.tsx => LeftNav.test.tsx} (84%) rename litellm/ui/litellm-dashboard/src/components/{leftnav.tsx => LeftNav.tsx} (80%) create mode 100644 litellm/ui/litellm-dashboard/src/components/chat/ConversationSearchDialog.test.tsx create mode 100644 litellm/ui/litellm-dashboard/src/components/chat/ConversationSearchDialog.tsx create mode 100644 litellm/ui/litellm-dashboard/src/components/shared/MobileSidebar.tsx delete mode 100644 litellm/ui/litellm-dashboard/src/components/shared/Sidebar.test.tsx delete mode 100644 litellm/ui/litellm-dashboard/src/components/shared/Sidebar.tsx create mode 100644 litellm/ui/litellm-dashboard/src/components/shared/sidebarStyles.ts create mode 100644 litellm/ui/litellm-dashboard/src/components/ui/sidebar.tsx create mode 100644 litellm/ui/litellm-dashboard/src/hooks/use-mobile.ts create mode 100644 litellm/ui/litellm-dashboard/tests/viewport.ts diff --git a/litellm/ui/litellm-dashboard/eslint-budgets.json b/litellm/ui/litellm-dashboard/eslint-budgets.json index 83b7190b355..c27bfc27db4 100644 --- a/litellm/ui/litellm-dashboard/eslint-budgets.json +++ b/litellm/ui/litellm-dashboard/eslint-budgets.json @@ -3,7 +3,7 @@ "no-console": { "max": 12, "target": 0 }, "complexity": { "max": 140, "target": 80 }, "max-depth": { "max": 70, "target": 30 }, - "local/no-large-inline-object-arg": { "max": 551, "target": 300 }, + "local/no-large-inline-object-arg": { "max": 545, "target": 300 }, "local/no-long-condition-chain": { "max": 194, "target": 120 }, "testing-library/no-container": { "max": 133, "target": 50 }, "testing-library/no-node-access": { "max": 707, "target": 500 }, diff --git a/litellm/ui/litellm-dashboard/eslint-suppressions.json b/litellm/ui/litellm-dashboard/eslint-suppressions.json index 6755900f445..0c4e897cee2 100644 --- a/litellm/ui/litellm-dashboard/eslint-suppressions.json +++ b/litellm/ui/litellm-dashboard/eslint-suppressions.json @@ -1607,11 +1607,6 @@ "count": 1 } }, - "src/components/leftnav.tsx": { - "local/filename-pascal-case": { - "count": 1 - } - }, "src/components/llm_calls/chat_completion.tsx": { "local/filename-pascal-case": { "count": 1 diff --git a/litellm/ui/litellm-dashboard/eslint.config.mjs b/litellm/ui/litellm-dashboard/eslint.config.mjs index 3f10d0c8bae..5af7d91fa31 100644 --- a/litellm/ui/litellm-dashboard/eslint.config.mjs +++ b/litellm/ui/litellm-dashboard/eslint.config.mjs @@ -308,6 +308,19 @@ const eslintConfig = [ "jest-dom/prefer-to-have-text-content": "error", }, }, + { + files: ["src/components/ui/**/*.{ts,tsx}"], + ignores: ["src/**/*.test.{ts,tsx}"], + rules: { "local/no-large-inline-object-arg": "off" }, + }, + { + files: ["src/components/ui/sidebar.tsx"], + rules: { "local/no-ad-hoc-z-index": "off" }, + }, + { + files: ["src/hooks/use-mobile.ts"], + rules: { "react-hooks/set-state-in-effect": "off" }, + }, ]; export default eslintConfig; diff --git a/litellm/ui/litellm-dashboard/src/app/(dashboard)/components/SidebarProvider.test.tsx b/litellm/ui/litellm-dashboard/src/app/(dashboard)/components/AppSidebar.test.tsx similarity index 86% rename from litellm/ui/litellm-dashboard/src/app/(dashboard)/components/SidebarProvider.test.tsx rename to litellm/ui/litellm-dashboard/src/app/(dashboard)/components/AppSidebar.test.tsx index 6cc38ddb5a2..2fe2c558642 100644 --- a/litellm/ui/litellm-dashboard/src/app/(dashboard)/components/SidebarProvider.test.tsx +++ b/litellm/ui/litellm-dashboard/src/app/(dashboard)/components/AppSidebar.test.tsx @@ -2,15 +2,15 @@ import { QueryClient, QueryClientProvider } from "@tanstack/react-query"; import { render, screen, within } from "@testing-library/react"; import type { ComponentProps } from "react"; import { expect, it, vi } from "vitest"; -import Sidebar from "@/components/leftnav"; -import SidebarProvider from "./SidebarProvider"; +import Sidebar from "@/components/LeftNav"; +import AppSidebar from "./AppSidebar"; const { getSettings } = vi.hoisted(() => ({ getSettings: vi.fn().mockResolvedValue({ values: { enable_projects_ui: true } }), })); vi.mock("@/components/networking", () => ({ getUiSettings: getSettings, getProxyBaseUrl: () => "http://localhost" })); -vi.mock("@/components/leftnav", () => ({ +vi.mock("@/components/LeftNav", () => ({ default: ({ enableProjectsUI }: ComponentProps) => ( ), @@ -21,11 +21,11 @@ it("reuses loaded navigation settings immediately when the mobile sidebar mounts const shell = (mobileOpen: boolean) => (
- +
{mobileOpen && (
- +
)}
diff --git a/litellm/ui/litellm-dashboard/src/app/(dashboard)/components/SidebarProvider.tsx b/litellm/ui/litellm-dashboard/src/app/(dashboard)/components/AppSidebar.tsx similarity index 67% rename from litellm/ui/litellm-dashboard/src/app/(dashboard)/components/SidebarProvider.tsx rename to litellm/ui/litellm-dashboard/src/app/(dashboard)/components/AppSidebar.tsx index c7794233ded..464a2e30abd 100644 --- a/litellm/ui/litellm-dashboard/src/app/(dashboard)/components/SidebarProvider.tsx +++ b/litellm/ui/litellm-dashboard/src/app/(dashboard)/components/AppSidebar.tsx @@ -1,21 +1,14 @@ "use client"; -import Sidebar from "@/components/leftnav"; +import Sidebar from "@/components/LeftNav"; import { useUISettings } from "@/app/(dashboard)/hooks/uiSettings/useUISettings"; -interface SidebarProviderProps { - sidebarCollapsed: boolean; - onToggleCollapsed?: () => void; -} - -const SidebarProvider = ({ sidebarCollapsed, onToggleCollapsed }: SidebarProviderProps) => { +const AppSidebar = () => { const { data: settings } = useUISettings(); const values = settings?.values; return ( ({ })); beforeEach(() => { + vi.stubGlobal("innerWidth", 390); testQueryClient.clear(); localStorage.clear(); deploymentWarnings = { warnings: [], ignore_available: true }; @@ -118,8 +119,8 @@ describe("dashboard overlay boundaries", () => { ); expect(await screen.findByRole("heading", { name: "Gateway page" })).toBeVisible(); - expect(screen.getByRole("button", { name: "Open navigation" })).toBeVisible(); - expect(screen.queryByRole("dialog", { name: "Navigation" })).not.toBeInTheDocument(); + expect(screen.getByRole("button", { name: "Toggle Sidebar" })).toBeVisible(); + expect(screen.queryByRole("dialog", { name: "Sidebar" })).not.toBeInTheDocument(); }); it.each([ @@ -191,9 +192,9 @@ describe("dashboard overlay boundaries", () => { , ); - const trigger = await screen.findByRole("button", { name: "Open navigation" }); + const trigger = await screen.findByRole("button", { name: "Toggle Sidebar" }); await user.click(trigger); - const navigation = await screen.findByRole("dialog", { name: "Navigation" }); + const navigation = await screen.findByRole("dialog", { name: "Sidebar" }); expect(within(navigation).getByRole("link", { name: "Virtual Keys" })).toBeVisible(); await user.keyboard("{Escape}"); await waitFor(() => expect(trigger).toHaveFocus()); diff --git a/litellm/ui/litellm-dashboard/src/app/(dashboard)/layout.test.tsx b/litellm/ui/litellm-dashboard/src/app/(dashboard)/layout.test.tsx index 0fdbd047786..cfb5b0530c3 100644 --- a/litellm/ui/litellm-dashboard/src/app/(dashboard)/layout.test.tsx +++ b/litellm/ui/litellm-dashboard/src/app/(dashboard)/layout.test.tsx @@ -42,14 +42,21 @@ vi.mock("@/components/DashboardHeader", () => ({ ), })); -vi.mock("@/app/(dashboard)/components/SidebarProvider", () => ({ - default: ({ sidebarCollapsed, onToggleCollapsed }: { sidebarCollapsed: boolean; onToggleCollapsed: () => void }) => ( -
- - Settings -
- ), -})); +vi.mock("@/app/(dashboard)/components/AppSidebar", async () => { + const { Sidebar, useSidebar } = await import("@/components/ui/sidebar"); + return { + default: function FakeAppSidebar() { + const { state, toggleSidebar } = useSidebar(); + return ( + +
+ +
+
+ ); + }, + }; +}); vi.mock("@/components/UserBanner", () => ({ UserBanner: () => null, @@ -103,7 +110,8 @@ describe("(dashboard) Layout", () => { vi.unstubAllGlobals(); }); - it("starts mobile navigation closed, opens a modal drawer and closes it after choosing a page", async () => { + it("starts mobile navigation closed, opens a modal drawer and closes it from inside", async () => { + vi.stubGlobal("innerWidth", 390); render( @@ -113,14 +121,13 @@ describe("(dashboard) Layout", () => { ); pendingUiConfig.resolve(); - const trigger = await screen.findByRole("button", { name: "Open navigation" }); - expect(screen.queryByRole("dialog", { name: "Navigation" })).not.toBeInTheDocument(); + const trigger = await screen.findByRole("button", { name: "Toggle Sidebar" }); + expect(screen.queryByRole("dialog", { name: "Sidebar" })).not.toBeInTheDocument(); fireEvent.click(trigger); - const navigation = await screen.findByRole("dialog", { name: "Navigation" }); - expect(within(navigation).getByRole("button", { name: "Close navigation" })).toBeInTheDocument(); - fireEvent.click(within(navigation).getByRole("link", { name: "Settings" })); - await waitFor(() => expect(screen.queryByRole("dialog", { name: "Navigation" })).not.toBeInTheDocument()); + const navigation = await screen.findByRole("dialog", { name: "Sidebar" }); + fireEvent.click(within(navigation).getByRole("button", { name: "Close navigation" })); + await waitFor(() => expect(screen.queryByRole("dialog", { name: "Sidebar" })).not.toBeInTheDocument()); }); it("records one page view per route segment, not per query change", async () => { @@ -133,7 +140,7 @@ describe("(dashboard) Layout", () => { ); const { rerender } = render(dashboard()); pendingUiConfig.resolve(); - await screen.findByRole("button", { name: "Open navigation" }); + await screen.findByRole("button", { name: "Toggle Sidebar" }); searchParamsValue = new URLSearchParams("tab=members"); rerender(dashboard()); vi.mocked(usePathname).mockReturnValue("/ui/teams/abc-123"); @@ -150,6 +157,7 @@ describe("(dashboard) Layout", () => { }); it("closes the mobile drawer when navigation changes outside the drawer", async () => { + vi.stubGlobal("innerWidth", 390); const dashboard = () => ( @@ -159,15 +167,15 @@ describe("(dashboard) Layout", () => { ); const { rerender } = render(dashboard()); pendingUiConfig.resolve(); - fireEvent.click(await screen.findByRole("button", { name: "Open navigation" })); - expect(await screen.findByRole("dialog", { name: "Navigation" })).toBeInTheDocument(); + fireEvent.click(await screen.findByRole("button", { name: "Toggle Sidebar" })); + expect(await screen.findByRole("dialog", { name: "Sidebar" })).toBeInTheDocument(); vi.mocked(usePathname).mockReturnValue("/ui/api-keys"); rerender(dashboard()); - await waitFor(() => expect(screen.queryByRole("dialog", { name: "Navigation" })).not.toBeInTheDocument()); + await waitFor(() => expect(screen.queryByRole("dialog", { name: "Sidebar" })).not.toBeInTheDocument()); vi.mocked(usePathname).mockReturnValue("/ui/guardrails"); rerender(dashboard()); - expect(screen.queryByRole("dialog", { name: "Navigation" })).not.toBeInTheDocument(); + expect(screen.queryByRole("dialog", { name: "Sidebar" })).not.toBeInTheDocument(); }); it("collapses the sidebar on Logs for a full-screen view and expands it again after leaving", async () => { diff --git a/litellm/ui/litellm-dashboard/src/app/(dashboard)/layout.tsx b/litellm/ui/litellm-dashboard/src/app/(dashboard)/layout.tsx index e03073b64df..ac7b0df0867 100644 --- a/litellm/ui/litellm-dashboard/src/app/(dashboard)/layout.tsx +++ b/litellm/ui/litellm-dashboard/src/app/(dashboard)/layout.tsx @@ -2,7 +2,6 @@ import React, { Suspense, useState, useRef, useEffect } from "react"; import { useTranslation } from "react-i18next"; -import { Dialog as DialogPrimitive } from "@base-ui/react/dialog"; import { DashboardHeader } from "@/components/DashboardHeader"; import Navbar from "@/components/navbar"; import LoadingScreen from "@/components/common_components/LoadingScreen"; @@ -12,7 +11,7 @@ import { useCurrentUser } from "@/app/(dashboard)/hooks/currentUser/useCurrentUs import { redirectToLogin } from "@/app/(dashboard)/hooks/redirectToLogin"; import { clearTokenCookies } from "@/utils/cookieUtils"; import { decodeToken } from "@/utils/jwtUtils"; -import SidebarProvider from "@/app/(dashboard)/components/SidebarProvider"; +import AppSidebar from "@/app/(dashboard)/components/AppSidebar"; import { usePathname, useRouter, useSearchParams } from "next/navigation"; import { createDeploymentHealthHandle, @@ -27,10 +26,10 @@ import { routeSegmentForPathname, uiHref } from "@/utils/uiHref"; import { PluginModeProvider, usePluginMode } from "@/contexts/PluginModeContext"; import { createApiClient } from "@/lib/http/client"; import { getProxyBaseUrl } from "@/components/networking"; -import { Sheet, SheetContent, SheetTitle, SheetTrigger } from "@/components/ui/sheet"; -import { Button } from "@/components/ui/button"; -import { Menu } from "lucide-react"; -import { useMediaQuery } from "usehooks-ts"; +import { SidebarInset, SidebarProvider, SidebarTrigger } from "@/components/ui/sidebar"; +import { useCloseMobileSidebarOn } from "@/components/shared/MobileSidebar"; +import { sidebarProviderClassName, sidebarWidthStyle } from "@/components/shared/sidebarStyles"; +import { cn } from "@/lib/cva.config"; import { CommandPaletteProvider } from "@/components/CommandPalette/CommandPaletteProvider"; import { recordUiEvent } from "@/lib/telemetry/uiEvents"; import TelemetryEnvBanner from "@/app/(dashboard)/telemetry/_components/TelemetryEnvBanner"; @@ -116,6 +115,11 @@ export function AgentControlPlaneView() { } const FULL_BLEED_SEGMENTS = new Set(["logs"]); + +function CloseMobileSidebarOnNavigation({ navigationKey }: { navigationKey: string }) { + useCloseMobileSidebarOn(navigationKey); + return null; +} const CUSTOMER_PORTAL_SEGMENTS = new Set(["customers"]); function DashboardShell({ children }: { children: React.ReactNode }) { @@ -134,19 +138,12 @@ function DashboardShell({ children }: { children: React.ReactNode }) { }, [routeSegment]); const searchParams = useSearchParams(); const navigationKey = `${pathname}?${searchParams.toString()}`; - const isDesktop = useMediaQuery("(min-width: 768px)", { initializeWithValue: false }); - const [mobileNavigationKey, setMobileNavigationKey] = useState(null); - const [mobileNavigationHandle] = useState(() => DialogPrimitive.createHandle()); const [deploymentHealthHandle] = useState(createDeploymentHealthHandle); - if (mobileNavigationKey !== null && (isDesktop || mobileNavigationKey !== navigationKey)) { - setMobileNavigationKey(null); - } - const mobileNavigationOpen = !isDesktop && mobileNavigationKey === navigationKey; const isFullBleed = FULL_BLEED_SEGMENTS.has(routeSegment); // A manual toggle holds only for the route it was made on; full-bleed routes default to collapsed. const [sidebarOverride, setSidebarOverride] = useState<{ segment: string; collapsed: boolean } | null>(null); const sidebarCollapsed = sidebarOverride?.segment === routeSegment ? sidebarOverride.collapsed : isFullBleed; - const toggleSidebar = () => setSidebarOverride({ segment: routeSegment, collapsed: !sidebarCollapsed }); + const setSidebarOpen = (open: boolean) => setSidebarOverride({ segment: routeSegment, collapsed: !open }); const isGateway = mode === "ai-gateway" || mode === "customer-portal"; @@ -178,53 +175,26 @@ function DashboardShell({ children }: { children: React.ReactNode }) { // so the page can't be dragged past the end of the nav. return ( -
-
- -
- setMobileNavigationKey(open ? navigationKey : null)} - > - { - if (event.target instanceof Element && event.target.closest("a[href]")) setMobileNavigationKey(null); - }} - > - {t("shell.dashboardShell.navigation")} - setMobileNavigationKey(null)} /> - - + + + -
+ - } - > - - - } + navigationTrigger={} deploymentHealth={} deploymentHealthLink={} /> -
{children} -
-
+
+ - +
); } diff --git a/litellm/ui/litellm-dashboard/src/app/(dashboard)/legacyPageRoutes.test.ts b/litellm/ui/litellm-dashboard/src/app/(dashboard)/legacyPageRoutes.test.ts index 70b2f9b0ab7..59ec880a9b5 100644 --- a/litellm/ui/litellm-dashboard/src/app/(dashboard)/legacyPageRoutes.test.ts +++ b/litellm/ui/litellm-dashboard/src/app/(dashboard)/legacyPageRoutes.test.ts @@ -1,5 +1,5 @@ import { describe, expect, it } from "vitest"; -import { menuGroups } from "@/components/leftnav"; +import { menuGroups } from "@/components/LeftNav"; import { legacyPageRedirectHref } from "./legacyPageRoutes"; const redirect = (query: string) => legacyPageRedirectHref(new URLSearchParams(query)); diff --git a/litellm/ui/litellm-dashboard/src/app/(dashboard)/prompts/_components/README.md b/litellm/ui/litellm-dashboard/src/app/(dashboard)/prompts/_components/README.md index 89c89c6fa4b..9f505a98efc 100644 --- a/litellm/ui/litellm-dashboard/src/app/(dashboard)/prompts/_components/README.md +++ b/litellm/ui/litellm-dashboard/src/app/(dashboard)/prompts/_components/README.md @@ -64,7 +64,7 @@ interface PromptItem { The component is fully integrated into the main application: -1. **Left Navigation**: Added to `leftnav.tsx` with `FileTextOutlined` icon +1. **Left Navigation**: Added to `LeftNav.tsx` with `FileTextOutlined` icon 2. **Main Routing**: Added to `page.tsx` with proper routing logic 3. **Permissions**: Restricted to admin roles (same as guardrails) diff --git a/litellm/ui/litellm-dashboard/src/app/chat/layout.integration.test.tsx b/litellm/ui/litellm-dashboard/src/app/chat/layout.integration.test.tsx index d48c68f0d69..8bfca2ffe3b 100644 --- a/litellm/ui/litellm-dashboard/src/app/chat/layout.integration.test.tsx +++ b/litellm/ui/litellm-dashboard/src/app/chat/layout.integration.test.tsx @@ -41,6 +41,7 @@ let themeResponse: unknown = { values: {} }; describe("Chat layout product navigation", () => { beforeEach(() => { + vi.stubGlobal("innerWidth", 390); themeResponse = { values: {} }; route.pathname = "/ui/chat"; localStorage.clear(); @@ -106,7 +107,7 @@ describe("Chat layout product navigation", () => { , ); - await user.click(screen.getByRole("button", { name: "Open chat navigation" })); + await user.click(screen.getByRole("button", { name: "Toggle Sidebar" })); const logo = await screen.findByRole("link", { name: "Chat home" }); const light = within(logo).getByAltText("LiteLLM"); const dark = within(logo).getByAltText(""); @@ -126,8 +127,8 @@ describe("Chat layout product navigation", () => { , ); - await user.click(screen.getByRole("button", { name: "Open chat navigation" })); - expect(await screen.findByRole("dialog", { name: "LiteLLM Chat" })).toBeInTheDocument(); + await user.click(screen.getByRole("button", { name: "Toggle Sidebar" })); + expect(await screen.findByRole("dialog", { name: "Sidebar" })).toBeInTheDocument(); expect(screen.getByAltText("LiteLLM")).toHaveAttribute("src", `${getProxyBaseUrl()}/get_image`); }); @@ -147,7 +148,7 @@ describe("Chat layout product navigation", () => { ); expect(screen.getByRole("heading", { name: "Chat content" })).toBeVisible(); - await user.click(screen.getByRole("button", { name: "Open chat navigation" })); + await user.click(screen.getByRole("button", { name: "Toggle Sidebar" })); await user.click(screen.getByRole("button", { name: "Switch workspace, current: Chat" })); expect(await screen.findByRole("menuitem", { name: "Observability" })).toBeInTheDocument(); expect(localStorage.getItem("litellm_plugin_mode")).toBe(plugin.name); @@ -181,7 +182,7 @@ describe("Chat layout product navigation", () => { ); expect(screen.getByRole("heading", { name: "Chat content" })).toBeVisible(); - await user.click(screen.getByRole("button", { name: "Open chat navigation" })); + await user.click(screen.getByRole("button", { name: "Toggle Sidebar" })); await user.click(screen.getByRole("button", { name: "Switch workspace, current: Chat" })); expect(await screen.findByRole("menuitem", { name: "Observability" })).toBeInTheDocument(); await user.click(screen.getByRole("menuitem", { name: "AI Gateway", exact: true })); diff --git a/litellm/ui/litellm-dashboard/src/components/CommandPalette/useVisibleMenuGroups.ts b/litellm/ui/litellm-dashboard/src/components/CommandPalette/useVisibleMenuGroups.ts index 8c3b9382934..89c9dd45f7d 100644 --- a/litellm/ui/litellm-dashboard/src/components/CommandPalette/useVisibleMenuGroups.ts +++ b/litellm/ui/litellm-dashboard/src/components/CommandPalette/useVisibleMenuGroups.ts @@ -6,7 +6,7 @@ import useAuthorized from "@/app/(dashboard)/hooks/useAuthorized"; import { useUISettings } from "@/app/(dashboard)/hooks/uiSettings/useUISettings"; import useIsOrgAdmin from "@/app/(dashboard)/hooks/useIsOrgAdmin"; import { isUserTeamAdminForAnyTeam } from "@/utils/roles"; -import { menuGroups, visibleMenuGroups, type MenuVisibilityContext } from "@/components/leftnav"; +import { menuGroups, visibleMenuGroups, type MenuVisibilityContext } from "@/components/LeftNav"; export const useVisibleMenuGroups = () => { const { userId, userRole, isViewOnly } = useAuthorized(); diff --git a/litellm/ui/litellm-dashboard/src/components/CommandPalette/utils.test.ts b/litellm/ui/litellm-dashboard/src/components/CommandPalette/utils.test.ts index d1f14137577..fe19d393434 100644 --- a/litellm/ui/litellm-dashboard/src/components/CommandPalette/utils.test.ts +++ b/litellm/ui/litellm-dashboard/src/components/CommandPalette/utils.test.ts @@ -1,5 +1,5 @@ import { describe, expect, it } from "vitest"; -import { visibleMenuGroups, type MenuGroup, menuGroups } from "@/components/leftnav"; +import { visibleMenuGroups, type MenuGroup, menuGroups } from "@/components/LeftNav"; import { toSiTerminology } from "@/lib/terminology"; import { effectiveSessionRole, isViewOnlySessionRole } from "@/utils/roles"; import { flattenNavItems, matchNavItems, paletteScopeForRoute, shortcutLabel, type PaletteNavItem } from "./utils"; diff --git a/litellm/ui/litellm-dashboard/src/components/CommandPalette/utils.ts b/litellm/ui/litellm-dashboard/src/components/CommandPalette/utils.ts index acd0c3487a4..d7a92137217 100644 --- a/litellm/ui/litellm-dashboard/src/components/CommandPalette/utils.ts +++ b/litellm/ui/litellm-dashboard/src/components/CommandPalette/utils.ts @@ -1,5 +1,5 @@ import type { ReactNode } from "react"; -import { labelText, routeOf, sectionText, type MenuGroup } from "@/components/leftnav"; +import { labelText, routeOf, sectionText, type MenuGroup } from "@/components/LeftNav"; import { keepTerminology, type Term } from "@/lib/terminology"; import i18n from "@/i18n/i18n"; diff --git a/litellm/ui/litellm-dashboard/src/components/DashboardHeader.tsx b/litellm/ui/litellm-dashboard/src/components/DashboardHeader.tsx index 708348602e1..7912e457cea 100644 --- a/litellm/ui/litellm-dashboard/src/components/DashboardHeader.tsx +++ b/litellm/ui/litellm-dashboard/src/components/DashboardHeader.tsx @@ -4,7 +4,7 @@ import type { ReactNode } from "react"; import ThemeToggle from "@/components/ThemeToggle/ThemeToggle"; import { usePathname } from "next/navigation"; import { useTerminology } from "@/contexts/TerminologyContext"; -import { getBreadcrumb } from "@/components/leftnav"; +import { getBreadcrumb } from "@/components/LeftNav"; import { CommandPaletteTrigger } from "@/components/CommandPalette/CommandPaletteTrigger"; import { DashboardCommunityLinks } from "@/components/Navbar/DashboardResources"; import { NotificationsBell } from "@/components/Navbar/NotificationsBell/NotificationsBell"; diff --git a/litellm/ui/litellm-dashboard/src/components/leftnav.test.tsx b/litellm/ui/litellm-dashboard/src/components/LeftNav.test.tsx similarity index 84% rename from litellm/ui/litellm-dashboard/src/components/leftnav.test.tsx rename to litellm/ui/litellm-dashboard/src/components/LeftNav.test.tsx index 19cbcf27d87..a5b45fa78d6 100644 --- a/litellm/ui/litellm-dashboard/src/components/leftnav.test.tsx +++ b/litellm/ui/litellm-dashboard/src/components/LeftNav.test.tsx @@ -1,10 +1,32 @@ import { act, fireEvent, screen, waitFor, within } from "@testing-library/react"; import userEvent from "@testing-library/user-event"; +import type { ComponentProps } from "react"; import { afterEach, describe, expect, it, vi } from "vitest"; import { renderWithProviders } from "../../tests/test-utils"; import { TerminologyProvider } from "@/contexts/TerminologyContext"; import { PluginModeProvider } from "@/contexts/PluginModeContext"; -import Sidebar, { menuGroups, getBreadcrumb } from "./leftnav"; +import { SidebarProvider, SidebarTrigger } from "@/components/ui/sidebar"; +import { useCloseMobileSidebarOn } from "@/components/shared/MobileSidebar"; +import LeftNav, { menuGroups, getBreadcrumb } from "./LeftNav"; + +const Sidebar = ({ collapsed = false, ...props }: ComponentProps & { collapsed?: boolean }) => ( + + + +); + +const CloseOnBreakpointChange = () => { + useCloseMobileSidebarOn(); + return null; +}; + +const PhoneShell = ({ railCollapsed = false }: { railCollapsed?: boolean }) => ( + + + + + +); vi.mock("../utils/roles", async (importOriginal) => { const actual = await importOriginal(); @@ -22,6 +44,7 @@ vi.mock("../utils/roles", async (importOriginal) => { }); const navState = vi.hoisted(() => ({ pathname: "/ui/api-keys" })); +const health = vi.hoisted(() => ({ version: undefined as string | undefined })); vi.mock("next/navigation", () => ({ usePathname: () => navState.pathname, @@ -96,7 +119,7 @@ vi.mock("@/contexts/ThemeContext", () => ({ // Version tag + logout target come from network hooks; keep them inert in unit tests. vi.mock("@/app/(dashboard)/hooks/healthReadiness/useHealthReadinessDetails", () => ({ - useHealthReadinessDetails: () => ({ data: undefined }), + useHealthReadinessDetails: () => ({ data: health.version ? { litellm_version: health.version } : undefined }), })); vi.mock("@/app/(dashboard)/hooks/useLogout", () => ({ useLogout: () => vi.fn(), @@ -145,6 +168,7 @@ describe("Sidebar (leftnav)", () => { }; afterEach(() => { + vi.unstubAllGlobals(); mockUseAuthorized.mockReset(); mockUseOrganizations.mockReset(); mockUseTeams.mockReset(); @@ -155,6 +179,7 @@ describe("Sidebar (leftnav)", () => { }); mockUseThemeImpl = unbrandedTheme; navState.pathname = "/ui/api-keys"; + health.version = undefined; uiConfig.data = { admin_ui_disabled: false, use_si_terminology: false }; localStorage.removeItem("litellm_plugin_mode"); }); @@ -187,7 +212,7 @@ describe("Sidebar (leftnav)", () => { , ); expect(screen.getByRole("link", { name: "Customer organizations" })).toHaveAttribute("href", "/ui/customers"); - expect(screen.getByRole("link", { name: "Customer organizations" })).toHaveAttribute("data-active", "true"); + expect(screen.getByRole("link", { name: "Customer organizations" })).toHaveAttribute("data-active"); expect(screen.queryByRole("link", { name: "End users" })).not.toBeInTheDocument(); }); @@ -680,14 +705,64 @@ describe("Sidebar (leftnav)", () => { it("marks the nav item for the current route active", () => { navState.pathname = "/ui/logs"; renderWithProviders(); - expect(screen.getByRole("link", { name: "Logs" })).toHaveAttribute("data-active", "true"); + expect(screen.getByRole("link", { name: "Logs" })).toHaveAttribute("data-active"); expect(screen.getByRole("link", { name: "Virtual Keys" })).not.toHaveAttribute("data-active"); }); + it("closes the mobile drawer after following any link in it, including the page already open", async () => { + vi.stubGlobal("innerWidth", 390); + navState.pathname = "/ui/api-keys"; + health.version = "1.2.3"; + renderWithProviders(); + for (const page of ["Virtual Keys", "Playground", "v1.2.3"]) { + fireEvent.click(await screen.findByRole("button", { name: "Toggle Sidebar" })); + fireEvent.click(within(await screen.findByRole("dialog", { name: "Sidebar" })).getByRole("link", { name: page })); + await waitFor(() => expect(screen.queryByRole("dialog", { name: "Sidebar" })).not.toBeInTheDocument()); + } + }); + + it("shows the full nav in the phone drawer when the desktop rail was left collapsed", async () => { + vi.stubGlobal("innerWidth", 390); + navState.pathname = "/ui/search-tools"; + renderWithProviders(); + fireEvent.click(await screen.findByRole("button", { name: "Toggle Sidebar" })); + const drawer = await screen.findByRole("dialog", { name: "Sidebar" }); + expect(within(drawer).getByRole("button", { name: "Collapse sidebar" })).toHaveAttribute("aria-expanded", "true"); + const tools = within(drawer).getByRole("button", { name: "Tools" }); + expect(tools).toHaveAttribute("aria-expanded", "true"); + fireEvent.click(tools); + expect(tools).toHaveAttribute("aria-expanded", "false"); + }); + + it("keeps the phone drawer closed after the window widens to desktop and narrows again", async () => { + const breakpointListeners = new Set<() => void>(); + vi.stubGlobal("matchMedia", (media: string) => ({ + matches: false, + media, + addEventListener: (_: string, listener: () => void) => breakpointListeners.add(listener), + removeEventListener: (_: string, listener: () => void) => breakpointListeners.delete(listener), + })); + const resizeTo = async (width: number) => { + vi.stubGlobal("innerWidth", width); + await act(async () => breakpointListeners.forEach((listener) => listener())); + }; + vi.stubGlobal("innerWidth", 390); + renderWithProviders(); + + fireEvent.click(await screen.findByRole("button", { name: "Toggle Sidebar" })); + expect(await screen.findByRole("dialog", { name: "Sidebar" })).toBeInTheDocument(); + await resizeTo(1200); + await waitFor(() => expect(screen.queryByRole("dialog", { name: "Sidebar" })).not.toBeInTheDocument()); + await resizeTo(390); + await act(async () => new Promise((resolve) => setTimeout(resolve, 300))); + expect(screen.queryByRole("dialog", { name: "Sidebar" })).not.toBeInTheDocument(); + expect(screen.getByRole("button", { name: "Toggle Sidebar" })).toBeInTheDocument(); + }); + it("marks Home active at the dashboard root", () => { navState.pathname = "/ui/"; renderWithProviders(); - expect(screen.getByRole("link", { name: "Home" })).toHaveAttribute("data-active", "true"); + expect(screen.getByRole("link", { name: "Home" })).toHaveAttribute("data-active"); }); it("does not highlight Home when the Aria workspace is active", () => { @@ -699,7 +774,7 @@ describe("Sidebar (leftnav)", () => { it("expands the parent group of the current nested route and marks the child active", () => { navState.pathname = "/ui/search-tools"; renderWithProviders(); - expect(screen.getByRole("link", { name: "Search Tools" })).toHaveAttribute("data-active", "true"); + expect(screen.getByRole("link", { name: "Search Tools" })).toHaveAttribute("data-active"); expect(screen.getByRole("button", { name: "Tools" })).toHaveAttribute("aria-expanded", "true"); }); @@ -730,17 +805,23 @@ describe("Sidebar (leftnav)", () => { expect(hrefs.filter((href) => href.startsWith("/ui/")).length).toBeGreaterThan(30); }); - it("hides labels but keeps items reachable (icon + link) when collapsed to the rail", () => { + it("exposes the sidebar as a complementary landmark", () => { + renderWithProviders(); + expect(within(screen.getByRole("complementary")).getByRole("link", { name: "Virtual Keys" })).toBeInTheDocument(); + }); + + it("expands the rail and opens the group when a group is chosen while collapsed", async () => { + renderWithProviders(); + fireEvent.click(screen.getByRole("button", { name: "Tools" })); + expect(await screen.findByRole("link", { name: "Search Tools" })).toBeInTheDocument(); + expect(screen.getByRole("button", { name: "Collapse sidebar" })).toHaveAttribute("aria-expanded", "true"); + }); + + it("keeps items reachable by name and icon when collapsed to the rail", () => { const { container } = renderWithProviders(); - expect(container.querySelector('[data-slot="sidebar"]')).toHaveAttribute("data-collapsed", "true"); - // The item stays navigable in the icon-only rail: its link still renders with - // an icon (asserting the + svg, not the text, so a removed icon would - // fail here), while the label is present but CSS-hidden. - const label = screen.getByText("Virtual Keys"); - const link = label.closest("a"); - expect(link).not.toBeNull(); - expect(link!.querySelector("svg")).not.toBeNull(); - expect(label).toHaveClass("group-data-[collapsed=true]/sidebar:hidden"); + expect(container.querySelector('[data-slot="sidebar"]')).toHaveAttribute("data-collapsible", "icon"); + const link = screen.getByRole("link", { name: "Virtual Keys" }); + expect(link.querySelector("svg")).not.toBeNull(); }); it("shows Cost Optimization without a Beta badge and no feature-flag gate", () => { @@ -754,11 +835,17 @@ describe("Sidebar (leftnav)", () => { expect(container.querySelector('a[href*="projects"]')).toBeNull(); }); - it("keeps a readable collapsed-rail tooltip for items whose label carries a badge", () => { - const { container } = renderWithProviders(); + it.each([ + ["Cost Optimization", "/ui/cost-optimization"], + ["Projects", "/ui/projects"], + ])("titles the collapsed-rail link for %s without its badge text", (name, href) => { + renderWithProviders(); + expect(screen.getByTitle(name)).toHaveAttribute("href", href); + }); - expect(container.querySelector('a[href*="cost-optimization"]')).toHaveAttribute("title", "Cost Optimization"); - expect(container.querySelector('a[href*="projects"]')).toHaveAttribute("title", "Projects"); + it("leaves expanded-rail links untitled", () => { + renderWithProviders(); + expect(screen.queryByTitle("Cost Optimization")).not.toBeInTheDocument(); }); }); diff --git a/litellm/ui/litellm-dashboard/src/components/leftnav.tsx b/litellm/ui/litellm-dashboard/src/components/LeftNav.tsx similarity index 80% rename from litellm/ui/litellm-dashboard/src/components/leftnav.tsx rename to litellm/ui/litellm-dashboard/src/components/LeftNav.tsx index 1bd9a472d28..4a9a92edb7a 100644 --- a/litellm/ui/litellm-dashboard/src/components/leftnav.tsx +++ b/litellm/ui/litellm-dashboard/src/components/LeftNav.tsx @@ -8,6 +8,7 @@ import { useTerminology } from "@/contexts/TerminologyContext"; import { ScrollArea } from "@/components/ui/scroll-area"; import { Sidebar, + SidebarContent, SidebarFooter, SidebarGroup, SidebarGroupLabel, @@ -15,9 +16,19 @@ import { SidebarMenuButton, SidebarMenuItem, SidebarMenuSub, + SidebarMenuSubButton, + SidebarMenuSubItem, SidebarSeparator, - sidebarMenuButtonVariants, -} from "@/components/shared/Sidebar"; + useSidebar, +} from "@/components/ui/sidebar"; +import { Collapsible, CollapsibleContent, CollapsibleTrigger } from "@/components/ui/collapsible"; +import { + navMenuButtonClassName, + navMenuClassName, + navMenuSubButtonClassName, + navMenuSubClassName, + shellSidebarClassName, +} from "@/components/shared/sidebarStyles"; import { Activity, Aperture, @@ -61,7 +72,7 @@ import ViewSwitcher from "@/components/Navbar/ViewSwitcher"; import { usePluginMode } from "@/contexts/PluginModeContext"; import { AriaSidebarLink } from "@/components/liteadmin/LiteAdmin"; import { usePathname } from "next/navigation"; -import { useMemo, useState } from "react"; +import { type MouseEvent, useMemo, useState } from "react"; import { Trans, useTranslation } from "react-i18next"; import type { ParseKeys } from "i18next"; import i18n from "@/i18n/i18n"; @@ -86,8 +97,6 @@ import { routeSegmentForPathname, uiHref } from "@/utils/uiHref"; const ICON = { strokeWidth: 1.75 } as const; interface SidebarProps { - collapsed?: boolean; - onToggleCollapsed?: () => void; enabledPagesInternalUsers?: string[] | null; enableProjectsUI?: boolean; disableAgentsForInternalUsers?: boolean; @@ -577,9 +586,12 @@ export const getBreadcrumb = (pathname: string): { section: string | null; title return { section: null, title: prettify(route) }; }; +const groupsOpenFor = (route: string) => { + const parent = findParentKey(route); + return new Set(parent ? [parent] : []); +}; + const Sidebar_: React.FC = ({ - collapsed = false, - onToggleCollapsed, enabledPagesInternalUsers, enableProjectsUI, disableAgentsForInternalUsers, @@ -595,14 +607,16 @@ const Sidebar_: React.FC = ({ const isOrgAdmin = useIsOrgAdmin(); const { data: teams } = useTeams(); const logout = useLogout(accessToken); + const { state, isMobile, setOpen, setOpenMobile } = useSidebar(); + const collapsed = state === "collapsed" && !isMobile; + const closeMobileSidebarOnLinkClick = (event: MouseEvent) => { + if (event.target instanceof Element && event.target.closest("a[href]")) setOpenMobile(false); + }; const currentRoute = routeForPathname(usePathname()); const selectedKey = currentRoute === "aria" ? null : findMenuItemKey(currentRoute); - const [openGroups, setOpenGroups] = useState>(() => { - const parent = findParentKey(currentRoute); - return new Set(parent ? [parent] : []); - }); + const [openGroups, setOpenGroups] = useState>(() => groupsOpenFor(currentRoute)); // Keep the active page's parent group expanded as the user navigates, using the // "adjust state during render" pattern rather than an effect (avoids a @@ -646,128 +660,129 @@ const Sidebar_: React.FC = ({ userRole, ]); - const toggleGroup = (key: string) => { + const setGroupOpen = (key: string, open: boolean) => { if (collapsed) { - onToggleCollapsed?.(); + setOpen(true); setOpenGroups((prev) => new Set(prev).add(key)); return; } setOpenGroups((prev) => { const next = new Set(prev); - if (next.has(key)) next.delete(key); - else next.add(key); + if (open) next.add(key); + else next.delete(key); return next; }); }; - const renderLeaf = (item: MenuItem, isChild: boolean) => { - const active = selectedKey === item.key; - const size = isChild ? "sub" : "default"; - const label = {labelOf(item)}; + const leafLink = (item: MenuItem) => + item.external_url ? ( + + ) : ( + + ); - if (item.external_url) { + const leafContent = (item: MenuItem) => ( + <> + {item.icon} + {labelOf(item)} + {item.external_url && ( + + )} + + ); + + const renderItem = (item: MenuItem) => { + const active = selectedKey === item.key; + const title = collapsed ? term(labelText(item)) : undefined; + if (!item.children?.length) { return ( - - {item.icon} - {label} - - + + + {leafContent(item)} + + ); } - return ( - - {item.icon} - {label} - - ); - }; - - const renderItem = (item: MenuItem) => { - const isGroup = !!item.children && item.children.length > 0; - if (!isGroup) { - return {renderLeaf(item, false)}; - } - - const active = selectedKey === item.key; const open = openGroups.has(item.key); return ( - - toggleGroup(item.key)} - title={collapsed ? term(labelText(item)) : undefined} + setGroupOpen(item.key, next)} + render={} + > + } > {item.icon} - {labelOf(item)} + {labelOf(item)} - - {open && ( - - {item.children!.map((child) => ( - {renderLeaf(child, true)} + + + + {item.children.map((child) => ( + + + {leafContent(child)} + + ))} - )} - + + ); }; return ( - - + +
+ -
- - -
- - - - - - {isAdminRole(userRole) && ( - + onToggleCollapsed?.()} + className="h-9 w-full max-w-none justify-start shadow-none group-data-[collapsible=icon]:size-9 group-data-[collapsible=icon]:justify-center group-data-[collapsible=icon]:p-0 [&_[data-slot=workspace-label]]:flex-1 [&_[data-slot=workspace-label]]:text-left group-data-[collapsible=icon]:[&_[data-slot=workspace-label]]:hidden" /> - )} - - + + + + + + + + + + {isAdminRole(userRole) && ( + setOpen(true)} /> + )} + + +
); }; diff --git a/litellm/ui/litellm-dashboard/src/components/Navbar/ViewSwitcher.tsx b/litellm/ui/litellm-dashboard/src/components/Navbar/ViewSwitcher.tsx index 38b051515fb..41e7d24efaf 100644 --- a/litellm/ui/litellm-dashboard/src/components/Navbar/ViewSwitcher.tsx +++ b/litellm/ui/litellm-dashboard/src/components/Navbar/ViewSwitcher.tsx @@ -10,7 +10,6 @@ import { DropdownMenuTrigger, } from "@/components/ui/dropdown-menu"; import { Check, ChevronDown, ChevronsUpDown } from "lucide-react"; -import { useSidebar } from "@/components/shared/Sidebar"; import BetaBadge from "@/components/BetaBadge"; import { usePluginMode } from "@/contexts/PluginModeContext"; import { useUISettings } from "@/app/(dashboard)/hooks/uiSettings/useUISettings"; @@ -51,15 +50,15 @@ interface ViewSwitcherItem { interface ViewSwitcherProps { className?: string; contentClassName?: string; + collapsed?: boolean; } const pluginLabel = (mode: string, plugins: readonly { name: string; display_name: string }[], portalLabel: string) => mode === CUSTOMER_PORTAL ? portalLabel : plugins.find((p) => p.name === mode)?.display_name; -export default function ViewSwitcher({ className, contentClassName }: ViewSwitcherProps) { +export default function ViewSwitcher({ className, contentClassName, collapsed = false }: ViewSwitcherProps) { const { t } = useTranslation(); const term = useTerminology(); - const { collapsed } = useSidebar(); const { mode, setMode, plugins } = usePluginMode(); const { data: uiSettings } = useUISettings(); const pathname = usePathname(); diff --git a/litellm/ui/litellm-dashboard/src/components/chat/ChatShell.integration.test.tsx b/litellm/ui/litellm-dashboard/src/components/chat/ChatShell.integration.test.tsx index 195f62d36dd..f0978812268 100644 --- a/litellm/ui/litellm-dashboard/src/components/chat/ChatShell.integration.test.tsx +++ b/litellm/ui/litellm-dashboard/src/components/chat/ChatShell.integration.test.tsx @@ -1,18 +1,18 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; -import { screen, waitFor, fireEvent } from "@testing-library/react"; +import { screen, waitFor, fireEvent, within } from "@testing-library/react"; import userEvent from "@testing-library/user-event"; import { renderWithProviders } from "@/../tests/test-utils"; +import { stubViewportMatchMedia } from "@/../tests/viewport"; import type { ReactElement } from "react"; import { ThemeProvider } from "@/contexts/ThemeContext"; import ChatShell from "./ChatShell"; const render = (ui: ReactElement) => renderWithProviders({ui}); -const { mockPush, mockUsePathname, mockUseChatShell, mockUseMediaQuery, mockLogout } = vi.hoisted(() => ({ +const { mockPush, mockUsePathname, mockUseChatShell, mockLogout } = vi.hoisted(() => ({ mockPush: vi.fn(), mockLogout: vi.fn(), mockUsePathname: vi.fn(() => "/ui/chat"), - mockUseMediaQuery: vi.fn(() => true), mockUseChatShell: vi.fn(() => ({ accessToken: "test-token", userEmail: "developer@example.com", @@ -39,7 +39,6 @@ vi.mock("@/app/(dashboard)/hooks/uiSettings/useUISettings", () => ({ useUISettings: () => ({ data: { values: { enable_chat_ui: true } } }), })); vi.mock("@/app/(dashboard)/hooks/useLogout", () => ({ useLogout: () => mockLogout })); -vi.mock("usehooks-ts", () => ({ useMediaQuery: mockUseMediaQuery })); describe("ChatShell", () => { beforeEach(() => { @@ -53,7 +52,6 @@ describe("ChatShell", () => { vi.unstubAllGlobals(); mockPush.mockClear(); mockUsePathname.mockReturnValue("/ui/chat"); - mockUseMediaQuery.mockReturnValue(true); }); it("should render the chat workspace with a single New Chat action", () => { @@ -147,7 +145,7 @@ describe("ChatShell", () => { }); it("should open mobile navigation and close it after selecting Models", async () => { - mockUseMediaQuery.mockReturnValue(false); + vi.stubGlobal("innerWidth", 390); const user = userEvent.setup(); render( @@ -156,8 +154,8 @@ describe("ChatShell", () => { ); expect(screen.queryByRole("navigation", { name: "Chat workspace" })).not.toBeInTheDocument(); - await user.click(screen.getByRole("button", { name: "Open chat navigation" })); - expect(await screen.findByRole("dialog", { name: "LiteLLM Chat" })).toBeInTheDocument(); + await user.click(screen.getByRole("button", { name: "Toggle Sidebar" })); + expect(await screen.findByRole("dialog", { name: "Sidebar" })).toBeInTheDocument(); await user.click(screen.getByRole("button", { name: "Models" })); expect(mockPush).toHaveBeenCalledWith("/ui/chat/models"); @@ -166,7 +164,7 @@ describe("ChatShell", () => { }); it("should dismiss mobile navigation when the Chat home logo is selected", async () => { - mockUseMediaQuery.mockReturnValue(false); + vi.stubGlobal("innerWidth", 390); const user = userEvent.setup(); render( @@ -174,7 +172,7 @@ describe("ChatShell", () => { , ); - await user.click(screen.getByRole("button", { name: "Open chat navigation" })); + await user.click(screen.getByRole("button", { name: "Toggle Sidebar" })); const home = await screen.findByRole("link", { name: "Chat home" }); expect(home).toHaveAttribute("href", "/ui/chat"); await user.click(home); @@ -185,7 +183,7 @@ describe("ChatShell", () => { }); it("should close mobile navigation with Escape and restore trigger focus", async () => { - mockUseMediaQuery.mockReturnValue(false); + vi.stubGlobal("innerWidth", 390); const user = userEvent.setup(); render( @@ -193,9 +191,9 @@ describe("ChatShell", () => { , ); - const trigger = screen.getByRole("button", { name: "Open chat navigation" }); + const trigger = screen.getByRole("button", { name: "Toggle Sidebar" }); await user.click(trigger); - expect(await screen.findByRole("dialog", { name: "LiteLLM Chat" })).toBeInTheDocument(); + expect(await screen.findByRole("dialog", { name: "Sidebar" })).toBeInTheDocument(); await user.keyboard("{Escape}"); await waitFor(() => expect(screen.queryByRole("dialog")).not.toBeInTheDocument()); @@ -216,8 +214,43 @@ describe("ChatShell", () => { expect(await screen.findByRole("button", { name: "Collapse sidebar" })).toHaveAttribute("aria-expanded", "true"); }); - it("should focus conversation search when the mobile sidebar starts closed", async () => { - mockUseMediaQuery.mockReturnValue(false); + it("should expand the desktop rail when search was opened at phone width", async () => { + const resizeTo = stubViewportMatchMedia(); + const user = userEvent.setup(); + render( + +
+ , + ); + await user.click(screen.getByRole("button", { name: "Collapse sidebar" })); + await resizeTo(390); + fireEvent.keyDown(document, { key: "k", code: "KeyK", ctrlKey: true }); + expect(await screen.findByRole("dialog", { name: "Search conversations" })).toBeInTheDocument(); + await resizeTo(1280); + expect(await screen.findByRole("button", { name: "Collapse sidebar", hidden: true })).toHaveAttribute( + "aria-expanded", + "true", + ); + }); + + it("should show the full sidebar in the phone drawer after the desktop rail was collapsed", async () => { + const resizeTo = stubViewportMatchMedia(); + const user = userEvent.setup(); + render( + +
+ , + ); + await user.click(screen.getByRole("button", { name: "Collapse sidebar" })); + await resizeTo(390); + await user.click(await screen.findByRole("button", { name: "Toggle Sidebar" })); + const drawer = await screen.findByRole("dialog", { name: "Sidebar" }); + expect(within(drawer).getByRole("button", { name: "Collapse sidebar" })).toHaveAttribute("aria-expanded", "true"); + expect(within(drawer).getByRole("button", { name: /^Account menu/ })).toHaveTextContent("developer@example.com"); + }); + + it("should open only conversation search at phone width and focus it", async () => { + vi.stubGlobal("innerWidth", 390); const user = userEvent.setup(); render( @@ -227,6 +260,7 @@ describe("ChatShell", () => { fireEvent.keyDown(document, { key: "k", code: "KeyK", ctrlKey: true }); const search = await screen.findByRole("textbox", { name: "Search conversations" }); await waitFor(() => expect(search).toHaveFocus()); + expect(screen.queryByRole("dialog", { name: "Sidebar" })).not.toBeInTheDocument(); await user.type(search, "release notes"); expect(search).toHaveValue("release notes"); }); diff --git a/litellm/ui/litellm-dashboard/src/components/chat/ChatShell.tsx b/litellm/ui/litellm-dashboard/src/components/chat/ChatShell.tsx index 295e46bbaf5..dbd64987fdb 100644 --- a/litellm/ui/litellm-dashboard/src/components/chat/ChatShell.tsx +++ b/litellm/ui/litellm-dashboard/src/components/chat/ChatShell.tsx @@ -3,7 +3,6 @@ import React, { useState } from "react"; import { usePathname, useRouter } from "next/navigation"; import { - Menu, Plus, Network, LayoutGrid, @@ -16,10 +15,7 @@ import { ChevronDown, Info, } from "lucide-react"; -import { useMediaQuery } from "usehooks-ts"; import { useTranslation } from "react-i18next"; -import { Button } from "@/components/ui/button"; -import { Sheet, SheetContent, SheetDescription, SheetHeader, SheetTitle, SheetTrigger } from "@/components/ui/sheet"; import { DropdownMenu, DropdownMenuContent, @@ -27,19 +23,39 @@ import { DropdownMenuSeparator, DropdownMenuTrigger, } from "@/components/ui/dropdown-menu"; -import { Sidebar, SidebarContent, SidebarFooter, SidebarMenuButton } from "@/components/shared/Sidebar"; +import { + Sidebar, + SidebarFooter, + SidebarGroup, + SidebarInset, + SidebarMenu, + SidebarMenuButton, + SidebarMenuItem, + SidebarProvider, + SidebarTrigger, + useSidebar, +} from "@/components/ui/sidebar"; +import { useCloseMobileSidebarOn } from "@/components/shared/MobileSidebar"; +import { + navMenuButtonClassName, + navMenuClassName, + shellSidebarClassName, + sidebarProviderClassName, + sidebarWidthStyle, +} from "@/components/shared/sidebarStyles"; +import { cn } from "@/lib/cva.config"; import { SidebarBrand } from "@/components/shared/SidebarBrand"; import ChatAccountMenu from "./ChatAccountMenu"; import { Kbd } from "@/components/ui/kbd"; import { useShortcutLabel } from "@/components/CommandPalette/useShortcutLabel"; import { useHotkeys } from "react-hotkeys-hook"; import { DashboardHeader } from "@/components/DashboardHeader"; -import { Dialog as DialogPrimitive } from "@base-ui/react/dialog"; import { useLogout } from "@/app/(dashboard)/hooks/useLogout"; import { uiHref } from "@/utils/uiHref"; import { useChatShell } from "@/contexts/ChatShellContext"; import ViewSwitcher from "@/components/Navbar/ViewSwitcher"; import ConversationList from "./ConversationList"; +import ConversationSearchDialog from "./ConversationSearchDialog"; const conversationUrl = (chatsRoute: string, id: string) => `${chatsRoute}?id=${encodeURIComponent(id)}`; @@ -70,41 +86,47 @@ interface NavItemProps { function NavItem({ icon, label, onClick, active = false, shortcut }: NavItemProps) { return ( - - {icon} - {label} - {shortcut && ( - - {shortcut} - - )} - + + + {icon} + {label} + {shortcut && ( + {shortcut} + )} + + ); } -const ChatShell: React.FC<{ children: React.ReactNode }> = ({ children }) => { +const ChatShell: React.FC<{ children: React.ReactNode }> = ({ children }) => ( + + {children} + +); + +function ChatShellLayout({ children }: { children: React.ReactNode }) { const { t } = useTranslation(); const router = useRouter(); const pathname = stripTrailingSlash(usePathname() ?? ""); const { accessToken, conversations, activeConversationId, deleteConversation, renameConversation } = useChatShell(); const handleLogout = useLogout(accessToken); - const isDesktop = useMediaQuery("(min-width: 768px)", { initializeWithValue: false }); - const [sidebarOpen, setSidebarOpen] = useState(false); - const [sidebarCollapsed, setSidebarCollapsed] = useState(false); + const { state, isMobile, setOpen, setOpenMobile } = useSidebar(); + const collapsed = state === "collapsed" && !isMobile; + useCloseMobileSidebarOn(); const [searchOpen, setSearchOpen] = useState(false); - if (isDesktop && sidebarOpen) setSidebarOpen(false); - const collapsed = isDesktop && sidebarCollapsed; - const [mobileNavigationHandle] = useState(() => DialogPrimitive.createHandle()); const shortcut = useShortcutLabel(); const openSearch = () => { - setSidebarCollapsed(false); - if (!isDesktop) setSidebarOpen(true); + setOpen(true); setSearchOpen(true); }; useHotkeys("mod+k", openSearch, { enableOnFormTags: true, preventDefault: true, useKey: true }); @@ -118,80 +140,81 @@ const ChatShell: React.FC<{ children: React.ReactNode }> = ({ children }) => { ]; const workspaceActive = workspaceItems.some((item) => item.route === pathname); const navigate = (href: string) => { - setSidebarOpen(false); + setOpenMobile(false); setSearchOpen(false); router.push(href); }; const sidebar = ( <> - setSidebarOpen(false)} - collapsed={collapsed} - onToggleCollapsed={() => (isDesktop ? setSidebarCollapsed(!sidebarCollapsed) : setSidebarOpen(false))} - /> -
- - } label={t("chat.shell.newChat")} onClick={() => navigate(routes.chats)} /> -
- - } - label={t("chat.shell.models")} - onClick={() => navigate(routes.models)} - active={pathname === routes.models} + + + - } - label={t("chat.shell.integrations")} - onClick={() => navigate(routes.integrations)} - active={pathname === routes.integrations} - /> - - - } - > - - - {t("chat.shell.workspace")} - - - - - {workspaceItems.map(({ label, route, Icon }) => ( - navigate(route)} + + } label={t("chat.shell.newChat")} onClick={() => navigate(routes.chats)} /> + + + +
= ({ children }) => { if (id === activeConversationId) navigate(routes.chats); }} onRename={renameConversation} - searchOpen={searchOpen} - onSearchOpenChange={setSearchOpen} - hideSearchButton - enableSearchShortcut={false} />
- + = ({ children }) => { : titles.find((item) => item.route === pathname)?.label ?? t("shell.viewSwitcher.chat"); return ( -
- {isDesktop && ( - - {sidebar} - - )} - - - - {t("chat.shell.sheetTitle")} - {t("chat.shell.sheetDescription")} - - {sidebar} - - -
+ <> + + {sidebar} + + navigate(conversationUrl(routes.chats, id))} + onClose={() => setSearchOpen(false)} + /> + - } - > - - - } + navigationTrigger={} /> -
{children}
-
-
+
{children}
+ + ); -}; +} export default ChatShell; diff --git a/litellm/ui/litellm-dashboard/src/components/chat/ConversationList.integration.test.tsx b/litellm/ui/litellm-dashboard/src/components/chat/ConversationList.integration.test.tsx index 06961348cea..e8ef96c7e65 100644 --- a/litellm/ui/litellm-dashboard/src/components/chat/ConversationList.integration.test.tsx +++ b/litellm/ui/litellm-dashboard/src/components/chat/ConversationList.integration.test.tsx @@ -1,4 +1,4 @@ -import { act, fireEvent, render, screen, waitFor, within } from "@testing-library/react"; +import { render, screen } from "@testing-library/react"; import userEvent from "@testing-library/user-event"; import { describe, expect, it, vi } from "vitest"; import ConversationList from "./ConversationList"; @@ -55,35 +55,9 @@ describe("ConversationList navigation", () => { />, ); - await user.tab(); - expect(screen.getByRole("button", { name: "Search chats" })).toHaveFocus(); await user.tab(); expect(screen.getByRole("button", { name: "Design review", exact: true })).toHaveFocus(); await user.keyboard("{Enter}"); expect(onSelect).toHaveBeenCalledWith("design"); }); - - it("should filter chats from visible search and select a result", async () => { - const onSelect = vi.fn(); - const user = userEvent.setup(); - render( - , - ); - - await user.click(screen.getByRole("button", { name: "Search chats" })); - const dialog = await screen.findByRole("dialog", { name: "Search conversations" }); - act(() => - fireEvent.change(screen.getByRole("textbox", { name: "Search conversations" }), { target: { value: "photo" } }), - ); - expect(within(dialog).queryByRole("button", { name: /Design review/ })).not.toBeInTheDocument(); - await user.click(within(dialog).getByRole("button", { name: /Photo ideas/ })); - expect(onSelect).toHaveBeenCalledWith("photos"); - await waitFor(() => expect(screen.queryByRole("dialog")).not.toBeInTheDocument()); - }); }); diff --git a/litellm/ui/litellm-dashboard/src/components/chat/ConversationList.tsx b/litellm/ui/litellm-dashboard/src/components/chat/ConversationList.tsx index daef8610867..61ff5682edd 100644 --- a/litellm/ui/litellm-dashboard/src/components/chat/ConversationList.tsx +++ b/litellm/ui/litellm-dashboard/src/components/chat/ConversationList.tsx @@ -1,10 +1,9 @@ "use client"; -import React, { useState, useEffect, useRef, useCallback } from "react"; -import { Pencil, Trash2, Search, MessageSquare, Clock3 } from "lucide-react"; +import React, { useState, useEffect, useRef } from "react"; +import { Pencil, Trash2, Clock3 } from "lucide-react"; import { Button } from "@/components/ui/button"; import { Input } from "@/components/ui/input"; -import { Dialog, DialogContent, DialogTitle } from "@/components/ui/dialog"; import { AlertDialog, AlertDialogAction, @@ -29,10 +28,6 @@ interface Props { onSelect: (id: string) => void; onDelete: (id: string) => void; onRename: (id: string, newTitle: string) => void; - searchOpen?: boolean; - onSearchOpenChange?: (open: boolean) => void; - hideSearchButton?: boolean; - enableSearchShortcut?: boolean; } type DateGroup = "Recents" | "Yesterday" | "Last 7 Days" | "Older"; @@ -234,154 +229,33 @@ const ConversationRow: React.FC = ({ conv, isActive, onSel ); }; -interface SearchModalProps { - open: boolean; - conversations: Conversation[]; - onSelect: (id: string) => void; - onClose: () => void; -} - -const SearchModal: React.FC = ({ open, conversations, onSelect, onClose }) => { +const ConversationList: React.FC = ({ conversations, activeConversationId, onSelect, onDelete, onRename }) => { const { t } = useTranslation(); - const [query, setQuery] = useState(""); - const [wasOpen, setWasOpen] = useState(open); - - if (open !== wasOpen) { - setWasOpen(open); - if (!open) setQuery(""); - } - - const filtered = query.trim() - ? conversations.filter((c) => c.title.toLowerCase().includes(query.trim().toLowerCase())) - : conversations; - - const handleSelect = (id: string) => { - onSelect(id); - onClose(); - }; - - return ( - !v && onClose()}> - - {t("chat.conversationList.searchTitle")} -
- - setQuery(e.target.value)} - className="pl-9" - /> -
- - - {filtered.length === 0 ? ( -
{t("chat.conversationList.noResults")}
- ) : ( - filtered.map((conv) => { - return ( - - ); - }) - )} -
-
-
- ); -}; - -const ConversationList: React.FC = ({ - conversations, - activeConversationId, - onSelect, - onDelete, - onRename, - searchOpen, - onSearchOpenChange, - hideSearchButton = false, - enableSearchShortcut = true, -}) => { - const { t } = useTranslation(); - const [localSearchOpen, setLocalSearchOpen] = useState(false); - const searchModalOpen = searchOpen ?? localSearchOpen; - const setSearchModalOpen = onSearchOpenChange ?? setLocalSearchOpen; - - const handleGlobalKeyDown = useCallback( - (e: KeyboardEvent) => { - const isSearchShortcut = e.key.toLowerCase() === "k" && (e.metaKey || e.ctrlKey); - if (isSearchShortcut && !e.shiftKey) { - e.preventDefault(); - setSearchModalOpen(!searchModalOpen); - } - }, - [searchModalOpen, setSearchModalOpen], - ); - - useEffect(() => { - if (!enableSearchShortcut) return; - document.addEventListener("keydown", handleGlobalKeyDown); - return () => document.removeEventListener("keydown", handleGlobalKeyDown); - }, [handleGlobalKeyDown, enableSearchShortcut]); - const grouped = groupConversations(conversations); return ( - <> -
- {!hideSearchButton && ( -
- -
- )} - - {grouped.map(({ group, items }) => ( -
-
-
- {items.map((conv) => ( - - ))} +
+ + {grouped.map(({ group, items }) => ( +
+
+
- ))} - -
- - setSearchModalOpen(false)} - /> - + {items.map((conv) => ( + + ))} +
+ ))} + +
); }; diff --git a/litellm/ui/litellm-dashboard/src/components/chat/ConversationSearchDialog.test.tsx b/litellm/ui/litellm-dashboard/src/components/chat/ConversationSearchDialog.test.tsx new file mode 100644 index 00000000000..4ab1e10dfbf --- /dev/null +++ b/litellm/ui/litellm-dashboard/src/components/chat/ConversationSearchDialog.test.tsx @@ -0,0 +1,44 @@ +import { act, fireEvent, render, screen, within } from "@testing-library/react"; +import userEvent from "@testing-library/user-event"; +import { describe, expect, it, vi } from "vitest"; +import ConversationSearchDialog from "./ConversationSearchDialog"; +import type { Conversation } from "./types"; + +const conversations: Conversation[] = [ + { + id: "design", + title: "Design review", + model: "test-model", + messages: [], + mcpServerNames: [], + createdAt: 1, + updatedAt: 1, + }, + { + id: "photos", + title: "Photo ideas", + model: "test-model", + messages: [], + mcpServerNames: [], + createdAt: 2, + updatedAt: 2, + }, +]; + +describe("ConversationSearchDialog", () => { + it("should filter chats by title and select a result", async () => { + const onSelect = vi.fn(); + const user = userEvent.setup(); + const onClose = vi.fn(); + render(); + + const dialog = await screen.findByRole("dialog", { name: "Search conversations" }); + act(() => + fireEvent.change(screen.getByRole("textbox", { name: "Search conversations" }), { target: { value: "photo" } }), + ); + expect(within(dialog).queryByRole("button", { name: /Design review/ })).not.toBeInTheDocument(); + await user.click(within(dialog).getByRole("button", { name: /Photo ideas/ })); + expect(onSelect).toHaveBeenCalledWith("photos"); + expect(onClose).toHaveBeenCalled(); + }); +}); diff --git a/litellm/ui/litellm-dashboard/src/components/chat/ConversationSearchDialog.tsx b/litellm/ui/litellm-dashboard/src/components/chat/ConversationSearchDialog.tsx new file mode 100644 index 00000000000..fd27d2fc906 --- /dev/null +++ b/litellm/ui/litellm-dashboard/src/components/chat/ConversationSearchDialog.tsx @@ -0,0 +1,87 @@ +"use client"; + +import React, { useState } from "react"; +import { MessageSquare, Search } from "lucide-react"; +import dayjs from "dayjs"; +import { useTranslation } from "react-i18next"; +import { Button } from "@/components/ui/button"; +import { Dialog, DialogContent, DialogTitle } from "@/components/ui/dialog"; +import { Input } from "@/components/ui/input"; +import { ScrollArea } from "@/components/ui/scroll-area"; +import { Conversation } from "./types"; + +interface ConversationSearchDialogProps { + open: boolean; + conversations: Conversation[]; + onSelect: (id: string) => void; + onClose: () => void; +} + +const ConversationSearchDialog: React.FC = ({ + open, + conversations, + onSelect, + onClose, +}) => { + const { t } = useTranslation(); + const [query, setQuery] = useState(""); + const [wasOpen, setWasOpen] = useState(open); + + if (open !== wasOpen) { + setWasOpen(open); + if (!open) setQuery(""); + } + + const filtered = query.trim() + ? conversations.filter((c) => c.title.toLowerCase().includes(query.trim().toLowerCase())) + : conversations; + + const handleSelect = (id: string) => { + onSelect(id); + onClose(); + }; + + return ( + !v && onClose()}> + + {t("chat.conversationList.searchTitle")} +
+ + setQuery(e.target.value)} + className="pl-9" + /> +
+ + + {filtered.length === 0 ? ( +
{t("chat.conversationList.noResults")}
+ ) : ( + filtered.map((conv) => { + return ( + + ); + }) + )} +
+
+
+ ); +}; + +export default ConversationSearchDialog; diff --git a/litellm/ui/litellm-dashboard/src/components/chat/design.md b/litellm/ui/litellm-dashboard/src/components/chat/design.md index 98fc014b19c..820de35a32d 100644 --- a/litellm/ui/litellm-dashboard/src/components/chat/design.md +++ b/litellm/ui/litellm-dashboard/src/components/chat/design.md @@ -157,9 +157,9 @@ Sizes: `default` (h-9), `sm` (h-8), `xs` (h-6), `lg` (h-10), `icon` (size-9), `i ### Sidebar nav item -Use `Sidebar`, `SidebarContent`, `SidebarFooter` and `SidebarMenuButton` from `components/shared/Sidebar`. Both workspaces use `SidebarBrand`, `ViewSwitcher` and `DashboardHeader`. Chat has a compact account menu with its existing identity, Settings and Sign out actions. Theme lives in the shared top bar. Gateway account preferences and admin controls stay in the gateway. Keep the shared 280px expanded and 72px collapsed widths, 56px header and 768px mobile breakpoint +Use `Sidebar`, `SidebarContent`, `SidebarFooter` and `SidebarMenuButton` from the stock shadcn block in `components/ui/sidebar`, with our look in the className overrides from `components/shared/sidebarStyles`. Both workspaces use `SidebarBrand`, `ViewSwitcher` and `DashboardHeader`. Chat has a compact account menu with its existing identity, Settings and Sign out actions. Theme lives in the shared top bar. Gateway account preferences and admin controls stay in the gateway. Keep the shared 280px expanded and 72px collapsed widths, 56px header and 768px mobile breakpoint -Use one New Chat action for the blank composer; do not duplicate it with a Chats destination. Chat retains Models, Integrations, Workspace and conversation history. Chat has no gateway-wide header search or worker selector. Search chats in the sidebar owns Cmd/Ctrl+K, including when the sidebar is collapsed or on mobile. Mobile navigation uses the same Sheet treatment as the dashboard +Use one New Chat action for the blank composer; do not duplicate it with a Chats destination. Chat retains Models, Integrations, Workspace and conversation history. Chat has no gateway-wide header search or worker selector. Cmd/Ctrl+K and Search chats open one conversation search that `ChatShell` renders outside the sidebar, so the shortcut also works with the sidebar collapsed and on phones opens only the search. Mobile navigation is the stock shadcn Sidebar sheet, the same as the dashboard The conversation title appears in the shared header. Do not repeat it in a second content header. Routed pages keep their content-specific headings and actions @@ -200,14 +200,15 @@ No max-width cap on panel content — matches the rest of the dashboard's own pa Card, Textarea and sonner are installed. Earlier versions of this document listed them as missing and encouraged parallel implementations; use the shared owners above -Shared sidebar primitives are available in `components/shared/Sidebar`. Use them instead of hand-writing a separate rail +The stock shadcn Sidebar is installed in `components/ui/sidebar`. Use it instead of hand-writing a separate rail ## File Structure ``` src/components/chat/ - ChatShell.tsx # Desktop navigation / mobile Sheet, shared across all /chat/* routes - ConversationList.tsx # Date-grouped chat list and conversation search + ChatShell.tsx # Sidebar, header and conversation search, shared across all /chat/* routes + ConversationList.tsx # Date-grouped chat list + ConversationSearchDialog.tsx # Cmd/Ctrl+K conversation search ChatMessages.tsx # Shared list and single-message rendering (user, assistant, tool) MCPAppsPanel.tsx # Integrations grid + detail view MCPConnectPicker.tsx # MCP server toggle popover diff --git a/litellm/ui/litellm-dashboard/src/components/liteadmin/LiteAdmin.integration.test.tsx b/litellm/ui/litellm-dashboard/src/components/liteadmin/LiteAdmin.integration.test.tsx index 68720acbc23..75ba6c873be 100644 --- a/litellm/ui/litellm-dashboard/src/components/liteadmin/LiteAdmin.integration.test.tsx +++ b/litellm/ui/litellm-dashboard/src/components/liteadmin/LiteAdmin.integration.test.tsx @@ -11,6 +11,7 @@ import userEvent from "@testing-library/user-event"; import { Fragment, useEffect, type ComponentType } from "react"; import SidebarAccountMenu from "@/components/SidebarAccountMenu/SidebarAccountMenu"; import UserDropdown from "@/components/Navbar/UserDropdown/UserDropdown"; +import { SidebarProvider } from "@/components/ui/sidebar"; import { AriaUsageTrigger, LiteAdminFrame, LiteAdminPage, AriaSidebarLink } from "./LiteAdmin"; import { MAX_INPUT_LENGTH } from "./agent"; import type { ModelGroup } from "@/components/llm_calls/fetch_models"; @@ -122,7 +123,9 @@ function renderWidget( {Menu && undefined} />} - + + + {page && } {usage && ( <> diff --git a/litellm/ui/litellm-dashboard/src/components/liteadmin/LiteAdmin.tsx b/litellm/ui/litellm-dashboard/src/components/liteadmin/LiteAdmin.tsx index 3e3cfd42507..c6db8c16a72 100644 --- a/litellm/ui/litellm-dashboard/src/components/liteadmin/LiteAdmin.tsx +++ b/litellm/ui/litellm-dashboard/src/components/liteadmin/LiteAdmin.tsx @@ -17,7 +17,8 @@ import { useTranslation } from "react-i18next"; import Link from "next/link"; import { useRouter } from "next/navigation"; import { uiHref } from "@/utils/uiHref"; -import { sidebarMenuButtonVariants } from "@/components/shared/Sidebar"; +import { SidebarMenu, SidebarMenuButton, SidebarMenuItem } from "@/components/ui/sidebar"; +import { navMenuButtonClassName } from "@/components/shared/sidebarStyles"; import { RotateCcw } from "lucide-react"; import { z } from "zod"; import useAuthorized from "@/app/(dashboard)/hooks/useAuthorized"; @@ -151,20 +152,22 @@ export function AriaSidebarLink({ active }: { active: boolean }) { const state = useContext(LiteAdminContext); if (!state) return null; return ( - - - {ARIA_AGENT_LABEL} - ⌘J - + + + + } + > + + {ARIA_AGENT_LABEL} + ⌘J + + + ); } diff --git a/litellm/ui/litellm-dashboard/src/components/page_utils.test.ts b/litellm/ui/litellm-dashboard/src/components/page_utils.test.ts index 6f55326a5be..4d3c39fbb97 100644 --- a/litellm/ui/litellm-dashboard/src/components/page_utils.test.ts +++ b/litellm/ui/litellm-dashboard/src/components/page_utils.test.ts @@ -5,7 +5,7 @@ import { describe, it, expect } from "vitest"; import { getAvailablePages } from "./page_utils"; -import { menuGroups } from "./leftnav"; +import { menuGroups } from "./LeftNav"; import { pageDescriptions } from "./page_metadata"; import { internalUserRoles } from "@/utils/roles"; @@ -162,7 +162,7 @@ describe("Page Utils - LeftNav Sync", () => { expect( orphanedDescriptions, - `These descriptions don't match any page in menuGroups: ${orphanedDescriptions.join(", ")}. Remove them or add the pages to leftnav.`, + `These descriptions don't match any page in menuGroups: ${orphanedDescriptions.join(", ")}. Remove them or add the pages to LeftNav.`, ).toHaveLength(0); }); diff --git a/litellm/ui/litellm-dashboard/src/components/page_utils.ts b/litellm/ui/litellm-dashboard/src/components/page_utils.ts index 2843ac2d9e8..5e8bf28621a 100644 --- a/litellm/ui/litellm-dashboard/src/components/page_utils.ts +++ b/litellm/ui/litellm-dashboard/src/components/page_utils.ts @@ -3,7 +3,7 @@ */ import i18n from "@/i18n/i18n"; -import { groupText, labelText, menuGroups } from "./leftnav"; +import { groupText, labelText, menuGroups } from "./LeftNav"; import { pageDescriptions, PageMetadata } from "./page_metadata"; import { internalUserRoles } from "@/utils/roles"; diff --git a/litellm/ui/litellm-dashboard/src/components/shared/MobileSidebar.tsx b/litellm/ui/litellm-dashboard/src/components/shared/MobileSidebar.tsx new file mode 100644 index 00000000000..681765fb12b --- /dev/null +++ b/litellm/ui/litellm-dashboard/src/components/shared/MobileSidebar.tsx @@ -0,0 +1,11 @@ +"use client"; + +import { useEffect } from "react"; +import { useSidebar } from "@/components/ui/sidebar"; + +export function useCloseMobileSidebarOn(navigationKey?: string) { + const { isMobile, setOpenMobile } = useSidebar(); + useEffect(() => { + setOpenMobile(false); + }, [navigationKey, isMobile, setOpenMobile]); +} diff --git a/litellm/ui/litellm-dashboard/src/components/shared/Sidebar.test.tsx b/litellm/ui/litellm-dashboard/src/components/shared/Sidebar.test.tsx deleted file mode 100644 index 8c0d2790489..00000000000 --- a/litellm/ui/litellm-dashboard/src/components/shared/Sidebar.test.tsx +++ /dev/null @@ -1,36 +0,0 @@ -import { render, screen } from "@testing-library/react"; -import { describe, expect, it } from "vitest"; - -import { SidebarMenuButton, sidebarMenuButtonVariants } from "./Sidebar"; - -const CVA_CONFIG_KEYS = ["base", "variants", "defaultVariants"]; - -describe("sidebarMenuButtonVariants", () => { - it("emits its base classes rather than the names of its own config keys", () => { - const emitted = sidebarMenuButtonVariants({}).split(" "); - - expect(emitted).toContain("rounded-md"); - expect(emitted).toContain("text-sidebar-foreground/70"); - expect(CVA_CONFIG_KEYS.filter((key) => emitted.includes(key))).toEqual([]); - }); - - it("applies the isActive variant on top of the base classes", () => { - const active = sidebarMenuButtonVariants({ isActive: true }).split(" "); - - expect(active).toContain("bg-sidebar-accent"); - expect(active).toContain("rounded-md"); - expect(sidebarMenuButtonVariants({ isActive: false }).split(" ")).not.toContain("bg-sidebar-accent"); - }); -}); - -describe("SidebarMenuButton", () => { - it("renders the variant classes onto the button", () => { - render(Keys); - const button = screen.getByRole("button", { name: "Keys" }); - - expect(button).toHaveClass("bg-sidebar-accent", "rounded-md"); - for (const key of CVA_CONFIG_KEYS) { - expect(button).not.toHaveClass(key); - } - }); -}); diff --git a/litellm/ui/litellm-dashboard/src/components/shared/Sidebar.tsx b/litellm/ui/litellm-dashboard/src/components/shared/Sidebar.tsx deleted file mode 100644 index d57d54de789..00000000000 --- a/litellm/ui/litellm-dashboard/src/components/shared/Sidebar.tsx +++ /dev/null @@ -1,206 +0,0 @@ -"use client"; - -import * as React from "react"; -import { Button as ButtonPrimitive } from "@base-ui/react/button"; - -import { cva, type VariantProps } from "class-variance-authority"; - -import { cn } from "@/lib/cva.config"; - -type SidebarContextValue = { collapsed: boolean }; -const SidebarContext = React.createContext({ collapsed: false }); - -export function useSidebar(): SidebarContextValue { - return React.useContext(SidebarContext); -} - -const Sidebar = React.forwardRef & { collapsed?: boolean }>( - ({ className, collapsed = false, children, ...props }, ref) => ( - - - - ), -); -Sidebar.displayName = "Sidebar"; - -const SidebarHeader = React.forwardRef>( - ({ className, ...props }, ref) => ( -
- ), -); -SidebarHeader.displayName = "SidebarHeader"; - -const SidebarContent = React.forwardRef>( - ({ className, ...props }, ref) => ( -