The fastest, litest AI Gateway. Rust core with Python SDK. Call 100+ LLM APIs in OpenAI (or native) format with cost tracking, guardrails, load balancing, and logging [Bedrock, Azure, OpenAI, Anthropic, OpenAI, VertexAI, vLLM, Nvidia NIM]
Python ai-gatewayanthropicazure-openaibedrockgatewaylangchainlitellmllmllm-gatewayllmopsmcp-gatewayopenaiopenai-proxyrustrust-aivertex-ai
feat(ui): add Home entry and independent LiteAdmin chat tabs (#46068)
tin-berricca06b27e421
diff --git a/ui/litellm-dashboard/src/app/(dashboard)/home/_components/HomePage.integration.test.tsx b/ui/litellm-dashboard/src/app/(dashboard)/home/_components/HomePage.integration.test.tsxindex a17a18beee5..4e87cd06f7a 100644--- a/ui/litellm-dashboard/src/app/(dashboard)/home/_components/HomePage.integration.test.tsx+++ b/ui/litellm-dashboard/src/app/(dashboard)/home/_components/HomePage.integration.test.tsx@@ -5,6 +5,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";import type { DailyActivityAggregatedResponse } from "@/components/UsagePage/dailyActivityApi";import { EMPTY_DAILY_ACTIVITY_METADATA } from "@/components/UsagePage/dailyActivityApi";import { all_admin_roles } from "@/utils/roles";+import { LiteAdminFrame } from "@/components/liteadmin/LiteAdmin";import HomePage from "./HomePage";const auth = vi.hoisted(() => ({@@ -12,6 +13,10 @@ const auth = vi.hoisted(() => ({userRole: "",userId: "u1",isViewOnly: false,+ isAuthorized: true,+ isLoading: false,+ premiumUser: true,+ token: "test-token",}));vi.mock("@/app/(dashboard)/hooks/useAuthorized", () => ({ default: () => auth }));@@ -46,6 +51,12 @@ const requestUrl = (input: RequestInfo | URL): string => {};const fakeFetch = (input: RequestInfo | URL) => {+ if (requestUrl(input).includes("/model_group/info")) {+ return Promise.resolve(Response.json({ data: [{ model_group: "claude-sonnet-5-5", mode: "chat" }] }));+ }+ if (requestUrl(input).endsWith("/sso/get/ui_settings")) {+ return Promise.resolve(Response.json({ PROXY_BASE_URL: "http://proxy.test" }));+ }const body = requestUrl(input).endsWith("/public/whats_new") ? whatsNew : blogPosts;return Promise.resolve(new Response(JSON.stringify(body), { status: 200, headers: { "Content-Type": "application/json" } }),@@ -133,6 +144,20 @@ describe("HomePage", () => {expect(screen.queryByRole("link", { name: /create new virtual key/i })).not.toBeInTheDocument();});+ it("offers LiteAdmin on Home inside the dashboard frame", async () => {+ render(+ <QueryClientProvider client={new QueryClient({ defaultOptions: { queries: { retry: false } } })}>+ <LiteAdminFrame>+ <HomePage />+ </LiteAdminFrame>+ </QueryClientProvider>,+ );+ const entry = screen.getByRole("region", { name: "Ask LiteAdmin" });+ expect(await within(entry).findByPlaceholderText("Ask LiteAdmin…")).toBeInTheDocument();+ expect(within(entry).getByRole("button", { name: "Send message" })).toBeDisabled();+ expect(await screen.findByText("$501.74")).toBeInTheDocument();+ });+it("shows an error with a retry instead of zero totals when the usage request fails", async () => {network.aggregated.mockRejectedValueOnce(new Error("boom"));renderHome();diff --git a/ui/litellm-dashboard/src/app/(dashboard)/home/_components/HomePage.tsx b/ui/litellm-dashboard/src/app/(dashboard)/home/_components/HomePage.tsxindex bcae30795c6..dcb0cd771b6 100644--- a/ui/litellm-dashboard/src/app/(dashboard)/home/_components/HomePage.tsx+++ b/ui/litellm-dashboard/src/app/(dashboard)/home/_components/HomePage.tsx@@ -8,6 +8,7 @@ import { Skeleton } from "@/components/ui/skeleton";import { Page } from "@/components/shared/Page";import { PageHeader, PageHeaderControls, PageHeaderTitle } from "@/components/shared/PageHeader";import { uiHref } from "@/utils/uiHref";+import { LiteAdminHome } from "@/components/liteadmin/LiteAdmin";import { Leaderboard, useBreakdown } from "@/app/(dashboard)/usage/_components/components/overview/BreakdownChart";import { Panel } from "@/app/(dashboard)/usage/_components/components/overview/Primitives";import UsageStatStrip from "@/app/(dashboard)/usage/_components/components/overview/UsageStatStrip";@@ -38,6 +39,8 @@ export default function HomePage() {)}</PageHeader>+ <LiteAdminHome />+<section aria-label={`Usage, last ${HOME_USAGE_DAYS} days`}>{usage.failed ? (<div className="flex items-center justify-between gap-2 rounded-xl border bg-card px-4 py-3 text-sm">diff --git a/ui/litellm-dashboard/src/components/liteadmin/LiteAdmin.integration.test.tsx b/ui/litellm-dashboard/src/components/liteadmin/LiteAdmin.integration.test.tsxindex c2b8805b892..2bc586cd1bb 100644--- a/ui/litellm-dashboard/src/components/liteadmin/LiteAdmin.integration.test.tsx+++ b/ui/litellm-dashboard/src/components/liteadmin/LiteAdmin.integration.test.tsx@@ -9,7 +9,7 @@ import userEvent from "@testing-library/user-event";import { useEffect, type ComponentType } from "react";import SidebarAccountMenu from "@/components/SidebarAccountMenu/SidebarAccountMenu";import UserDropdown from "@/components/Navbar/UserDropdown/UserDropdown";-import LiteAdmin, { LiteAdminFrame } from "./LiteAdmin";+import LiteAdmin, { LiteAdminFrame, LiteAdminHome } from "./LiteAdmin";import { MAX_INPUT_LENGTH } from "./agent";import type { ModelGroup } from "@/components/llm_calls/fetch_models";@@ -40,7 +40,7 @@ const keyArguments = {duration: null,};-type RecordedRequest = { url: string; headers: Headers; body: Record<string, unknown> };+type RecordedRequest = { url: string; headers: Headers; body: Record<string, unknown>; signal: AbortSignal };type ModelReply = {role: "assistant";content: string | null;@@ -98,9 +98,9 @@ function Page() {return null;}-function renderWidget(Menu?: ComponentType<{ onLogout: () => void }>) {+function renderWidget(Menu?: ComponentType<{ onLogout: () => void }>, showHome = false) {const client = new QueryClient({ defaultOptions: { queries: { retry: false, gcTime: 0 } } });- const tree = () => (+ const tree = (home = showHome) => (<QueryClientProvider client={client}><Toaster /><AuthProvider>@@ -108,13 +108,14 @@ function renderWidget(Menu?: ComponentType<{ onLogout: () => void }>) {{Menu && <Menu onLogout={() => undefined} />}<LiteAdminFrame><Page />+ {home && <LiteAdminHome />}<LiteAdmin /></LiteAdminFrame></AuthProvider></QueryClientProvider>);const view = render(tree());- return { ...view, refresh: () => view.rerender(tree()), client };+ return { ...view, refresh: (home = showHome) => view.rerender(tree(home)), client };}interface GatewayOptions {@@ -130,7 +131,8 @@ function gateway(replies: (ModelReply | Promise<ModelReply>)[], options: Gatewaytransport.mockImplementation(async (input, init) => {const request = input instanceof Request ? input : new Request(new URL(String(input), "http://localhost"), init);const body: Record<string, unknown> = request.method === "GET" ? {} : await request.clone().json();- requests.push({ url: request.url, headers: request.headers, body });+ const recorded = { url: request.url, headers: request.headers, body, signal: request.signal };+ requests.push(recorded);const path = new URL(request.url).pathname;if (path.endsWith("/litellm-ui-config"))return json({ proxy_base_url: MANAGEMENT, server_root_path: "", admin_ui_disabled: false });@@ -170,10 +172,10 @@ function gateway(replies: (ModelReply | Promise<ModelReply>)[], options: Gatewayreturn requests;}-async function selectModel() {+async function selectModel(model = "chat-model") {const user = userEvent.setup();await user.click(await screen.findByRole("combobox", { name: "LiteAdmin model" }));- await user.click(await screen.findByRole("option", { name: "chat-model" }));+ await user.click(await screen.findByRole("option", { name: model }));}async function openWidget() {@@ -202,13 +204,388 @@ afterEach(() => {});describe("LiteAdmin in the gateway", () => {+ it.each(["keyboard", "click"])("continues one conversation from Home via %s and the dock", async (method) => {+ const requests = gateway([answer("First reply."), answer("Second reply."), answer("Third reply.")]);+ renderWidget(undefined, true);+ const home = await screen.findByRole("region", { name: "Ask LiteAdmin" });+ await selectModel();+ const input = within(home).getByPlaceholderText("Ask LiteAdmin…");+ fireEvent.change(input, { target: { value: "First question" } });+ if (method === "keyboard") fireEvent.keyDown(input, { key: "Enter" });+ else fireEvent.click(within(home).getByRole("button", { name: "Send message" }));+ expect(await screen.findByText("First reply.")).toBeInTheDocument();+ expect(home).not.toBeVisible();+ expect(screen.getAllByRole("complementary", { name: "LiteAdmin" })).toHaveLength(1);+ expect(requests.filter((request) => request.url.endsWith("/chat/completions"))).toHaveLength(1);+ send("Second question");+ expect(await screen.findByText("Second reply.")).toBeInTheDocument();+ fireEvent.click(screen.getByRole("button", { name: "Close LiteAdmin" }));+ expect(home).toBeVisible();+ send("Third question");+ expect(await screen.findByText("Third reply.")).toBeInTheDocument();+ const completions = requests.filter((request) => request.url.endsWith("/chat/completions"));+ expect(completions).toHaveLength(3);+ expect(completions[2].body.messages).toEqual([+ { role: "system", content: expect.any(String) },+ { role: "user", content: "First question" },+ { role: "assistant", content: "First reply." },+ { role: "user", content: "Second question" },+ { role: "assistant", content: "Second reply." },+ { role: "user", content: "Third question" },+ ]);+ });++ it("preserves the draft and chosen model when opening, closing and leaving Home", async () => {+ const requests = gateway([answer("Draft received.")], {+ models: [+ { model_group: "claude-sonnet-5-5", mode: "chat" },+ { model_group: "chat-model", mode: "chat" },+ ],+ });+ const view = renderWidget(undefined, true);+ await selectModel();+ fireEvent.change(screen.getByPlaceholderText("Ask LiteAdmin…"), { target: { value: "Keep this draft" } });+ fireEvent.click(screen.getByRole("button", { name: "LiteAdmin" }));+ expect(screen.getByPlaceholderText("Ask LiteAdmin…")).toHaveValue("Keep this draft");+ fireEvent.click(screen.getByRole("button", { name: "Close LiteAdmin" }));+ const home = screen.getByRole("region", { name: "Ask LiteAdmin" });+ expect(within(home).getByPlaceholderText("Ask LiteAdmin…")).toHaveValue("Keep this draft");+ view.refresh(false);+ expect(home).not.toBeInTheDocument();+ fireEvent.click(screen.getByRole("button", { name: "LiteAdmin" }));+ expect(screen.getByPlaceholderText("Ask LiteAdmin…")).toHaveValue("Keep this draft");+ fireEvent.click(screen.getByRole("button", { name: "Send message" }));+ expect(await screen.findByText("Draft received.")).toBeInTheDocument();+ const completion = requests.find((request) => request.url.endsWith("/chat/completions"));+ expect(completion?.body.model).toBe("chat-model");+ expect(completion?.body.messages).toContainEqual({ role: "user", content: "Keep this draft" });+ });++ it("keeps each tab's history, model and draft independent through the Home composer", async () => {+ const requests = gateway(+ [answer("First answer."), answer("Second answer."), answer("Second follow-up."), answer("First follow-up.")],+ {+ models: [+ { model_group: "chat-model", mode: "chat" },+ { model_group: "other-chat-model", mode: "chat" },+ ],+ },+ );+ renderWidget(undefined, true);+ await selectModel();+ send("First question");+ await screen.findByText("First answer.");+ expect(within(screen.getByRole("tablist", { name: "LiteAdmin chats" })).getAllByRole("tab")).toHaveLength(1);+ fireEvent.click(screen.getByRole("button", { name: "New chat" }));+ expect(screen.getByRole("tab", { name: "Chat 2" })).toHaveAttribute("aria-selected", "true");+ expect(screen.queryByText("First answer.")).not.toBeInTheDocument();+ expect(screen.getByPlaceholderText("Ask LiteAdmin…")).toHaveValue("");+ await selectModel("other-chat-model");+ send("Second question");+ await screen.findByText("Second answer.");+ fireEvent.change(screen.getByPlaceholderText("Ask LiteAdmin…"), { target: { value: "Second draft" } });++ fireEvent.click(screen.getByRole("tab", { name: "Chat 1" }));+ expect(screen.getByText("First answer.")).toBeInTheDocument();+ expect(screen.queryByText("Second answer.")).not.toBeInTheDocument();+ expect(screen.getByPlaceholderText("Ask LiteAdmin…")).toHaveValue("");+ expect(screen.getByRole("combobox", { name: "LiteAdmin model" })).toHaveValue("chat-model");+ fireEvent.change(screen.getByPlaceholderText("Ask LiteAdmin…"), { target: { value: "First draft" } });+ fireEvent.click(screen.getByRole("button", { name: "Close LiteAdmin" }));+ const home = screen.getByRole("region", { name: "Ask LiteAdmin" });+ expect(within(home).getByPlaceholderText("Ask LiteAdmin…")).toHaveValue("First draft");+ expect(screen.getAllByPlaceholderText("Ask LiteAdmin…")).toHaveLength(1);++ fireEvent.click(screen.getByRole("button", { name: "LiteAdmin" }));+ fireEvent.click(screen.getByRole("tab", { name: "Chat 2" }));+ expect(screen.getByPlaceholderText("Ask LiteAdmin…")).toHaveValue("Second draft");+ expect(screen.getByRole("combobox", { name: "LiteAdmin model" })).toHaveValue("other-chat-model");+ expect(screen.getAllByLabelText("LiteAdmin conversation")).toHaveLength(1);+ fireEvent.click(screen.getByRole("button", { name: "Close LiteAdmin" }));+ expect(within(home).getByPlaceholderText("Ask LiteAdmin…")).toHaveValue("Second draft");+ fireEvent.click(within(home).getByRole("button", { name: "Send message" }));+ await screen.findByText("Second follow-up.");+ expect(screen.getByRole("tab", { name: "Chat 2" })).toHaveAttribute("aria-selected", "true");+ fireEvent.click(screen.getByRole("tab", { name: "Chat 1" }));+ expect(screen.getByPlaceholderText("Ask LiteAdmin…")).toHaveValue("First draft");+ fireEvent.click(screen.getByRole("button", { name: "Send message" }));+ await screen.findByText("First follow-up.");++ const completions = requests.filter((request) => request.url.endsWith("/chat/completions"));+ expect(completions.map((request) => request.body.model)).toEqual([+ "chat-model",+ "other-chat-model",+ "other-chat-model",+ "chat-model",+ ]);+ expect(completions[1].body.messages).toEqual([+ { role: "system", content: expect.any(String) },+ { role: "user", content: "Second question" },+ ]);+ expect(completions[2].body.messages).toEqual([+ { role: "system", content: expect.any(String) },+ { role: "user", content: "Second question" },+ { role: "assistant", content: "Second answer." },+ { role: "user", content: "Second draft" },+ ]);+ expect(completions[3].body.messages).toEqual([+ { role: "system", content: expect.any(String) },+ { role: "user", content: "First question" },+ { role: "assistant", content: "First answer." },+ { role: "user", content: "First draft" },+ ]);+ });++ it("supports keyboard tab switching and keeps focus on a surviving tab after closing", async () => {+ gateway([]);+ renderWidget();+ await openWidget();+ const user = userEvent.setup();+ await user.click(screen.getByRole("button", { name: "New chat" }));+ await user.click(screen.getByRole("tab", { name: "Chat 1" }));+ await user.keyboard("{ArrowRight}{Enter}");+ expect(screen.getByRole("tab", { name: "Chat 2" })).toHaveAttribute("aria-selected", "true");+ expect(screen.getByRole("tab", { name: "Chat 2" })).toHaveFocus();+ await user.click(screen.getByRole("button", { name: "Close Chat 2" }));+ expect(screen.getByRole("tab", { name: "Chat 1" })).toHaveFocus();+ await user.click(screen.getByRole("button", { name: "Close Chat 1" }));+ expect(screen.getByRole("tab", { name: "Chat 3" })).toHaveFocus();+ expect(screen.getByRole("tab", { name: "Chat 3" })).toHaveAttribute("aria-selected", "true");+ });++ it("keeps tab focus when returning to a saved approval and focuses it when reopening the panel", async () => {+ const requests = gateway([toolReply("key_create", keyArguments)]);+ renderWidget();+ await openWidget();+ send("Prepare a key for approval");+ const review = await screen.findByRole("region", { name: "Create a virtual key" });+ expect(review).toHaveFocus();+ const user = userEvent.setup();+ await user.click(screen.getByRole("button", { name: "New chat" }));+ await user.click(screen.getByRole("tab", { name: "Chat 2" }));+ await user.keyboard("{ArrowLeft}{Enter}");+ expect(screen.getByRole("tab", { name: "Chat 1" })).toHaveFocus();+ expect(screen.getByRole("button", { name: "Confirm change" })).toBeInTheDocument();+ await user.click(screen.getByRole("tab", { name: "Chat 2" }));+ await user.click(screen.getByRole("button", { name: "Close Chat 2" }));+ expect(screen.getByRole("tab", { name: "Chat 1" })).toHaveFocus();+ await user.click(screen.getByRole("button", { name: "Close LiteAdmin" }));+ await user.click(screen.getByRole("button", { name: "LiteAdmin" }));+ expect(screen.getByRole("region", { name: "Create a virtual key" })).toHaveFocus();+ expect(requests.filter((request) => request.url.endsWith("/key/generate"))).toHaveLength(0);+ });++ it("lets simultaneous turns finish independently without a background review stealing focus", async () => {+ const first = deferred<ModelReply>();+ const second = deferred<ModelReply>();+ const requests = gateway([first.promise, second.promise]);+ renderWidget();+ await openWidget();+ send("First pending question");+ await waitFor(() =>+ expect(requests.filter((request) => request.url.endsWith("/chat/completions"))).toHaveLength(1),+ );+ fireEvent.click(screen.getByRole("button", { name: "New chat" }));+ await selectModel();+ send("Second pending question");+ await waitFor(() =>+ expect(requests.filter((request) => request.url.endsWith("/chat/completions"))).toHaveLength(2),+ );+ const completions = requests.filter((request) => request.url.endsWith("/chat/completions"));+ expect(completions.every((request) => !request.signal.aborted)).toBe(true);+ await act(async () => second.resolve(answer("Second completed first.")));+ await screen.findByText("Second completed first.");+ const composer = screen.getByPlaceholderText("Ask LiteAdmin…");+ fireEvent.change(composer, { target: { value: "Keep typing in the second chat" } });+ act(() => composer.focus());++ await act(async () => first.resolve(toolReply("key_create", keyArguments)));+ expect(composer).toHaveFocus();+ expect(composer).toHaveValue("Keep typing in the second chat");+ expect(composer).toBeEnabled();+ expect(screen.getByRole("tab", { name: "Chat 2" })).toHaveAttribute("aria-selected", "true");+ expect(screen.queryByRole("button", { name: "Confirm change" })).not.toBeInTheDocument();+ expect(screen.queryByText("First pending question")).not.toBeInTheDocument();+ fireEvent.click(screen.getByRole("tab", { name: "Chat 1" }));+ expect(await screen.findByRole("region", { name: "Create a virtual key" })).toHaveTextContent("Widget key");+ expect(screen.getByText("First pending question")).toBeInTheDocument();+ expect(screen.queryByText("Second completed first.")).not.toBeInTheDocument();+ fireEvent.click(screen.getByRole("tab", { name: "Chat 2" }));+ expect(screen.getByPlaceholderText("Ask LiteAdmin…")).toHaveValue("Keep typing in the second chat");+ expect(screen.getByText("Second completed first.")).toBeInTheDocument();+ expect(requests.filter((request) => request.url.endsWith("/key/generate"))).toHaveLength(0);+ });++ it("cancels only a closed tab's approval and prevents closing an applying write even from another tab", async () => {+ const response = deferred<Response>();+ const requests = gateway(+ [+ toolReply("key_create", keyArguments),+ answer("Second chat is usable."),+ toolReply("key_create", { ...keyArguments, key_alias: "Second chat key" }),+ answer("Third chat is usable."),+ answer("Second chat write completed."),+ ],+ { write: () => response.promise },+ );+ renderWidget();+ await openWidget();+ send("Propose a first key");+ await screen.findByRole("button", { name: "Confirm change" });+ fireEvent.click(screen.getByRole("button", { name: "New chat" }));+ await selectModel();+ expect(screen.queryByRole("button", { name: "Confirm change" })).not.toBeInTheDocument();+ send("Read in the second chat");+ await screen.findByText("Second chat is usable.");+ fireEvent.click(screen.getByRole("tab", { name: "Chat 1" }));+ expect(screen.getByRole("region", { name: "Create a virtual key" })).toHaveTextContent("Widget key");+ fireEvent.click(screen.getByRole("tab", { name: "Chat 2" }));+ fireEvent.click(screen.getByRole("button", { name: "Close Chat 1" }));+ expect(screen.queryByRole("tab", { name: "Chat 1" })).not.toBeInTheDocument();+ expect(screen.getByRole("tab", { name: "Chat 2" })).toHaveAttribute("aria-selected", "true");+ expect(requests.filter((request) => request.url.endsWith("/key/generate"))).toHaveLength(0);++ send("Create the second chat key");+ fireEvent.click(await screen.findByRole("button", { name: "Confirm change" }));+ await waitFor(() => expect(requests.filter((request) => request.url.endsWith("/key/generate"))).toHaveLength(1));+ expect(screen.getByRole("button", { name: "Close Chat 2" })).toBeDisabled();+ fireEvent.click(screen.getByRole("button", { name: "Close Chat 2" }));+ expect(screen.getByRole("tab", { name: "Chat 2" })).toHaveAttribute("aria-selected", "true");+ expect(screen.getByRole("button", { name: "New chat" })).toBeEnabled();+ fireEvent.click(screen.getByRole("button", { name: "New chat" }));+ expect(screen.getByRole("button", { name: "Close Chat 2" })).toBeDisabled();+ fireEvent.click(screen.getByRole("button", { name: "Close Chat 2" }));+ expect(screen.getByRole("tab", { name: "Chat 2" })).toBeInTheDocument();+ await selectModel();+ send("Read while the other tab writes");+ await screen.findByText("Third chat is usable.");+ await act(async () => response.resolve(json({ key: NEW_KEY })));+ await waitFor(() => expect(screen.getByRole("button", { name: "Close Chat 2" })).toBeEnabled());+ expect(screen.getByRole("tab", { name: "Chat 3" })).toHaveAttribute("aria-selected", "true");+ expect(screen.queryByText(NEW_KEY)).not.toBeInTheDocument();+ fireEvent.click(screen.getByRole("tab", { name: "Chat 2" }));+ expect(await screen.findByText("Second chat write completed.")).toBeInTheDocument();+ expect(screen.getByText(NEW_KEY)).toBeInTheDocument();+ expect(screen.getByRole("region", { name: "Create a virtual key" })).toHaveTextContent("Completed");+ expect(requests.filter((request) => request.url.endsWith("/key/generate")).map((request) => request.body)).toEqual([+ { key_alias: "Second chat key", team_id: "team-1", max_budget: 40 },+ ]);+ expect(screen.queryByText(/A submitted change may have completed/)).not.toBeInTheDocument();+ });++ it("closes inactive, active and last tabs without cancelling survivors or reusing closed histories", async () => {+ const first = deferred<ModelReply>();+ const second = deferred<ModelReply>();+ const requests = gateway([first.promise, second.promise, answer("Third answer."), answer("Fresh answer.")]);+ renderWidget();+ await openWidget();+ send("First pending question");+ await waitFor(() =>+ expect(requests.filter((request) => request.url.endsWith("/chat/completions"))).toHaveLength(1),+ );+ fireEvent.click(screen.getByRole("button", { name: "New chat" }));+ await selectModel();+ send("Second pending question");+ await waitFor(() =>+ expect(requests.filter((request) => request.url.endsWith("/chat/completions"))).toHaveLength(2),+ );+ const pending = requests.filter((request) => request.url.endsWith("/chat/completions"));+ fireEvent.click(screen.getByRole("button", { name: "Close Chat 1" }));+ await waitFor(() => expect(pending[0].signal.aborted).toBe(true));+ expect(pending[1].signal.aborted).toBe(false);+ expect(screen.getByRole("tab", { name: "Chat 2" })).toHaveAttribute("aria-selected", "true");+ await act(async () => first.resolve(toolReply("key_create", keyArguments)));+ expect(screen.queryByRole("button", { name: "Confirm change" })).not.toBeInTheDocument();+ expect(screen.getByRole("status", { name: "LiteAdmin is working" })).toBeInTheDocument();++ fireEvent.click(screen.getByRole("button", { name: "New chat" }));+ await selectModel();+ send("Third question");+ await screen.findByText("Third answer.");+ fireEvent.click(screen.getByRole("button", { name: "Close Chat 3" }));+ expect(screen.getByRole("tab", { name: "Chat 2" })).toHaveAttribute("aria-selected", "true");+ expect(screen.getByText("Second pending question")).toBeInTheDocument();+ expect(pending[1].signal.aborted).toBe(false);+ fireEvent.click(screen.getByRole("button", { name: "Close Chat 2" }));+ await waitFor(() => expect(pending[1].signal.aborted).toBe(true));+ expect(within(screen.getByRole("tablist", { name: "LiteAdmin chats" })).getAllByRole("tab")).toHaveLength(1);+ expect(screen.getByRole("tab", { name: "Chat 4" })).toHaveAttribute("aria-selected", "true");+ expect(screen.getByPlaceholderText("Ask LiteAdmin…")).toHaveValue("");+ expect(screen.queryByRole("button", { name: "Stop request" })).not.toBeInTheDocument();+ await act(async () => second.resolve(answer("Late closed answer.")));+ expect(screen.queryByText("Late closed answer.")).not.toBeInTheDocument();+ expect(screen.queryByText("Third answer.")).not.toBeInTheDocument();+ await selectModel();+ send("Fresh question");+ await screen.findByText("Fresh answer.");+ expect(requests.filter((request) => request.url.endsWith("/chat/completions")).at(-1)?.body.messages).toEqual([+ { role: "system", content: expect.any(String) },+ { role: "user", content: "Fresh question" },+ ]);+ expect(requests.filter((request) => request.url.endsWith("/key/generate"))).toHaveLength(0);+ });++ it("keeps Home drafts unsent without a model or with empty or oversized input", async () => {+ const options: GatewayOptions = { models: [] };+ const requests = gateway([], options);+ const { client } = renderWidget(undefined, true);+ const home = await screen.findByRole("region", { name: "Ask LiteAdmin" });+ expect(await within(home).findByText("Add a chat model to your gateway to use LiteAdmin.")).toBeInTheDocument();+ expect(within(home).getByPlaceholderText("Ask LiteAdmin…")).toBeDisabled();+ expect(within(home).getByRole("button", { name: "Send message" })).toBeDisabled();+ options.models = [{ model_group: "chat-model", mode: "chat" }];+ await act(async () => client.invalidateQueries({ queryKey: ["liteadmin-models"] }));+ await selectModel();+ for (const text of [" ", "x".repeat(MAX_INPUT_LENGTH + 1)]) {+ const input = within(home).getByPlaceholderText("Ask LiteAdmin…");+ fireEvent.change(input, { target: { value: text } });+ fireEvent.keyDown(input, { key: "Enter" });+ const submit = within(home).getByRole("button", { name: "Send message" });+ expect(submit).toBeDisabled();+ fireEvent.click(submit);+ expect(input).toHaveValue(text);+ }+ expect(home).toBeVisible();+ expect(within(home).getByRole("alert")).toHaveTextContent("8,000 characters");+ expect(screen.queryByRole("complementary", { name: "LiteAdmin" })).not.toBeInTheDocument();+ expect(requests.filter((request) => request.url.endsWith("/chat/completions"))).toHaveLength(0);+ });++ it("shows destination consent in Home and discards its draft when the destination changes", async () => {+ const settings = { target: EXTERNAL_INFERENCE, status: 200 };+ const settingsReady = deferred<void>();+ const requests = gateway([], {+ settings: async () => {+ await settingsReady.promise;+ return json({ PROXY_BASE_URL: MANAGEMENT, LITELLM_UI_API_DOC_BASE_URL: settings.target });+ },+ });+ const { client } = renderWidget(undefined, true);+ const home = await screen.findByRole("region", { name: "Ask LiteAdmin" });+ expect(await within(home).findByLabelText("Loading gateway settings")).toBeInTheDocument();+ await act(async () => settingsReady.resolve());+ const consent = await within(home).findByRole("button", { name: "Use configured gateway" });+ expect(within(home).getByText(EXTERNAL_INFERENCE)).toBeInTheDocument();+ expect(within(home).queryByPlaceholderText("Ask LiteAdmin…")).not.toBeInTheDocument();+ fireEvent.click(consent);+ await selectModel();+ fireEvent.change(within(home).getByPlaceholderText("Ask LiteAdmin…"), { target: { value: "Old gateway draft" } });+ settings.target = `${EXTERNAL_INFERENCE}/changed`;+ await act(async () => client.invalidateQueries({ queryKey: ["proxySettings"] }));+ fireEvent.click(await within(home).findByRole("button", { name: "Use configured gateway" }));+ await selectModel();+ expect(within(home).getByPlaceholderText("Ask LiteAdmin…")).toHaveValue("");+ expect(home).toBeVisible();+ expect(requests.some((request) => request.url.endsWith("/chat/completions"))).toBe(false);+ });+it.each([["sidebar", SidebarAccountMenu],["navbar", UserDropdown],] as const)("persists Hide LiteAdmin only for enterprise users in the %s account menu", async (_name, Menu) => {gateway([]);const user = userEvent.setup();- const view = renderWidget(Menu);+ const view = renderWidget(Menu, true);await screen.findByRole("button", { name: "LiteAdmin" });await user.click(screen.getByRole("button", { name: /account menu/i }));const toggle = await screen.findByRole("switch", { name: "Toggle hide LiteAdmin" });@@ -216,9 +593,10 @@ describe("LiteAdmin in the gateway", () => {await user.click(toggle);expect(toggle).toBeChecked();expect(screen.queryByRole("button", { name: "LiteAdmin" })).not.toBeInTheDocument();+ expect(screen.queryByRole("region", { name: "Ask LiteAdmin", hidden: true })).not.toBeInTheDocument();view.unmount();- const restored = renderWidget(Menu);+ const restored = renderWidget(Menu, true);await screen.findByText("Session ready");await waitFor(() => expect(restored.client.isFetching()).toBe(0));expect(screen.queryByRole("button", { name: "LiteAdmin" })).not.toBeInTheDocument();@@ -227,6 +605,7 @@ describe("LiteAdmin in the gateway", () => {expect(savedToggle).toBeChecked();await user.click(savedToggle);expect(await screen.findByRole("button", { name: "LiteAdmin" })).toBeInTheDocument();+ expect(await screen.findByRole("region", { name: "Ask LiteAdmin" })).toBeVisible();for (const premiumUser of [false, null, undefined, "true"]) {session("proxy_admin", "first-admin", { premium_user: premiumUser });@@ -241,10 +620,11 @@ describe("LiteAdmin in the gateway", () => {async (premiumUser) => {session("proxy_admin", "first-admin", { premium_user: premiumUser });const requests = gateway([]);- const { client } = renderWidget();+ const { client } = renderWidget(undefined, true);await screen.findByText("Session ready");await waitFor(() => expect(client.isFetching()).toBe(0));expect(screen.queryByRole("button", { name: "LiteAdmin" })).not.toBeInTheDocument();+ expect(screen.queryByRole("region", { name: "Ask LiteAdmin", hidden: true })).not.toBeInTheDocument();for (const modifiers of [{ metaKey: true }, { ctrlKey: true }]) {expect(fireEvent.keyDown(document, { key: "j", ...modifiers })).toBe(true);expect(screen.queryByRole("complementary", { name: "LiteAdmin" })).not.toBeInTheDocument();@@ -387,10 +767,11 @@ describe("LiteAdmin in the gateway", () => {async (role) => {session(role);const requests = gateway([]);- const { client } = renderWidget();+ const { client } = renderWidget(undefined, true);await screen.findByText("Session ready");await waitFor(() => expect(client.isFetching()).toBe(0));expect(screen.queryByRole("button", { name: "LiteAdmin" })).not.toBeInTheDocument();+ expect(screen.queryByRole("region", { name: "Ask LiteAdmin", hidden: true })).not.toBeInTheDocument();expect(requests.every((request) => request.url.endsWith("/litellm-ui-config"))).toBe(true);},);@@ -490,7 +871,8 @@ describe("LiteAdmin in the gateway", () => {const confirm = await screen.findByRole("button", { name: "Confirm change" });fireEvent.click(confirm);fireEvent.click(confirm);- expect(screen.getByRole("button", { name: "New chat" })).toBeDisabled();+ expect(screen.getByRole("button", { name: "Close Chat 1" })).toBeDisabled();+ expect(screen.getByRole("button", { name: "New chat" })).toBeEnabled();expect(screen.queryByRole("button", { name: "Stop request" })).not.toBeInTheDocument();fireEvent.click(screen.getByRole("button", { name: "Close LiteAdmin" }));await act(async () => response.resolve(json({ key: NEW_KEY })));@@ -573,25 +955,73 @@ describe("LiteAdmin in the gateway", () => {expect(screen.queryByText(/A submitted change may have completed/)).not.toBeInTheDocument();});- it.each(["account", "target"])("discards an unconfirmed review when the %s changes", async (transition) => {- const settings = { target: INFERENCE, status: 200 };- const requests = gateway([toolReply("key_create", keyArguments)], { settings });- const view = renderWidget();- await openWidget();- send("Old request");- await screen.findByRole("button", { name: "Confirm change" });- if (transition === "account") {- session("proxy_admin", "second-admin");- view.refresh();- } else {- settings.target = `${INFERENCE}/updated`;- await act(async () => view.client.invalidateQueries({ queryKey: ["proxySettings"] }));- }- await waitFor(() => expect(screen.queryByRole("button", { name: "Confirm change" })).not.toBeInTheDocument());- expect(screen.queryByText("Old request")).not.toBeInTheDocument();- expect(screen.queryByText(/A submitted change may have completed/)).not.toBeInTheDocument();- expect(requests.filter((request) => request.url.endsWith("/key/generate"))).toHaveLength(0);- });+ it.each(["account", "gateway", "destination", "permission"])(+ "resets every chat when the %s changes",+ async (transition) => {+ const pending = deferred<ModelReply>();+ const settings = { target: INFERENCE, status: 200 };+ const requests = gateway([pending.promise, toolReply("key_create", keyArguments), answer("Fresh session.")], {+ settings,+ });+ const view = renderWidget(undefined, true);+ await openWidget();+ send("Old request");+ await waitFor(() =>+ expect(requests.filter((request) => request.url.endsWith("/chat/completions"))).toHaveLength(1),+ );+ const original = requests.find((request) => request.url.endsWith("/chat/completions"));+ fireEvent.click(screen.getByRole("button", { name: "New chat" }));+ await selectModel();+ send("Old approval");+ await screen.findByRole("button", { name: "Confirm change" });+ fireEvent.click(screen.getByRole("button", { name: "New chat" }));+ await selectModel();+ fireEvent.change(screen.getByPlaceholderText("Ask LiteAdmin…"), { target: { value: "Old draft" } });+ if (transition === "account") {+ session("proxy_admin", "second-admin");+ view.refresh();+ } else if (transition === "gateway") {+ settings.target = "https://worker.test/inference";+ switchToWorkerUrl("https://worker.test/proxy");+ view.refresh();+ } else if (transition === "destination") {+ settings.target = `${INFERENCE}/updated`;+ await act(async () => view.client.invalidateQueries({ queryKey: ["proxySettings"] }));+ } else {+ session("proxy_admin_viewer");+ view.refresh();+ expect(screen.queryByRole("button", { name: "LiteAdmin" })).not.toBeInTheDocument();+ expect(screen.queryByRole("region", { name: "Ask LiteAdmin", hidden: true })).not.toBeInTheDocument();+ expect(screen.queryByRole("tablist", { name: "LiteAdmin chats", hidden: true })).not.toBeInTheDocument();+ fireEvent.keyDown(document, { key: "j", ctrlKey: true });+ expect(screen.queryByRole("complementary", { name: "LiteAdmin" })).not.toBeInTheDocument();+ session();+ view.refresh();+ }+ await waitFor(() => expect(original?.signal.aborted).toBe(true));+ const trigger = await screen.findByRole("button", { name: "LiteAdmin" });+ if (trigger.getAttribute("aria-expanded") === "false") fireEvent.click(trigger);+ const tabs = await screen.findByRole("tablist", { name: "LiteAdmin chats" });+ expect(within(tabs).getAllByRole("tab")).toHaveLength(1);+ expect(screen.getByRole("tab", { name: "Chat 1" })).toHaveAttribute("aria-selected", "true");+ await waitFor(() => expect(screen.queryByRole("button", { name: "Confirm change" })).not.toBeInTheDocument());+ expect(screen.queryByText("Old request")).not.toBeInTheDocument();+ expect(screen.queryByText("Old approval")).not.toBeInTheDocument();+ expect(screen.getByPlaceholderText("Ask LiteAdmin…")).toHaveValue("");+ expect(screen.getByRole("combobox", { name: "LiteAdmin model" })).toHaveValue("");+ await act(async () => pending.resolve(toolReply("key_create", keyArguments)));+ expect(screen.queryByRole("button", { name: "Confirm change" })).not.toBeInTheDocument();+ expect(screen.queryByText(/A submitted change may have completed/)).not.toBeInTheDocument();+ expect(requests.filter((request) => request.url.endsWith("/key/generate"))).toHaveLength(0);+ await selectModel();+ send("Fresh question");+ await screen.findByText("Fresh session.");+ expect(requests.filter((request) => request.url.endsWith("/chat/completions")).at(-1)?.body.messages).toEqual([+ { role: "system", content: expect.any(String) },+ { role: "user", content: "Fresh question" },+ ]);+ },+ );it.each(["account", "target"])("warns about an interrupted write when the %s changes and rejects its late key",@@ -641,9 +1071,9 @@ describe("LiteAdmin in the gateway", () => {it("blocks inference when settings cannot be loaded", async () => {const requests = gateway([], { settings: { target: INFERENCE, status: 503 } });- renderWidget();- fireEvent.click(await screen.findByRole("button", { name: "LiteAdmin" }));- expect(await screen.findByText("Could not load gateway settings.")).toBeInTheDocument();+ renderWidget(undefined, true);+ const home = await screen.findByRole("region", { name: "Ask LiteAdmin" });+ expect(await within(home).findByText("Could not load gateway settings.")).toBeInTheDocument();expect(requests.some((request) => request.url.endsWith("/chat/completions"))).toBe(false);});diff --git a/ui/litellm-dashboard/src/components/liteadmin/LiteAdmin.tsx b/ui/litellm-dashboard/src/components/liteadmin/LiteAdmin.tsxindex 38e4334763f..bf296d47746 100644--- a/ui/litellm-dashboard/src/components/liteadmin/LiteAdmin.tsx+++ b/ui/litellm-dashboard/src/components/liteadmin/LiteAdmin.tsx@@ -1,8 +1,19 @@"use client";-import { createContext, useContext, useEffect, useRef, useState, type ReactNode, type RefObject } from "react";-import { useQuery } from "@tanstack/react-query";-import { RotateCcw, Sparkles, X } from "lucide-react";+import {+ createContext,+ useCallback,+ useContext,+ useEffect,+ useLayoutEffect,+ useRef,+ useState,+ type ReactNode,+ type RefObject,+} from "react";+import { createPortal } from "react-dom";+import { useQuery, type UseQueryResult } from "@tanstack/react-query";+import { Plus, Sparkles, X } from "lucide-react";import useAuthorized from "@/app/(dashboard)/hooks/useAuthorized";import { useDisableLiteAdmin } from "@/app/(dashboard)/hooks/useDisableLiteAdmin";import { useProxySettingsQuery } from "@/app/(dashboard)/hooks/proxySettings/useProxySettings";@@ -16,14 +27,23 @@ import { Button } from "@/components/ui/button";import { Card, CardContent, CardFooter, CardHeader, CardTitle } from "@/components/ui/card";import { FieldError } from "@/components/ui/field";import { Skeleton } from "@/components/ui/skeleton";+import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";import { cn } from "@/lib/cva.config";import { isProxyAdminRole } from "@/utils/roles";import { getPreferredLiteAdminModel, MAX_INPUT_LENGTH, resolveInferenceTarget } from "./agent";import { LiteAdminConversation } from "./LiteAdminConversation";-import { useLiteAdmin, type LiteAdminSession } from "./useLiteAdmin";+import { useLiteAdmin, type ConversationEntry, type LiteAdminSession } from "./useLiteAdmin";type ManagementSession = Omit<LiteAdminSession, "inferenceBaseUrl">;-type LiteAdminState = { open: boolean; toggle: () => void };+type ChatPhase = ReturnType<typeof useLiteAdmin>["phase"];+type ChatTab = { id: number; phase: ChatPhase };+type LiteAdminState = {+ open: boolean;+ toggle: () => void;+ show: () => void;+ homeContainer: HTMLDivElement | null;+ setHomeContainer: (container: HTMLDivElement | null) => void;+};const LiteAdminContext = createContext<LiteAdminState | null>(null);@@ -43,12 +63,16 @@ export function LiteAdminFrame({ children }: { children: ReactNode }) {const configured = useLiteAdminSession();const sessionKey = configured?.key ?? null;const [open, setOpen] = useState(false);+ const [homeContainer, setHomeContainer] = useState<HTMLDivElement | null>(null);const [openedSession, setOpenedSession] = useState(sessionKey);if (openedSession !== sessionKey) {setOpenedSession(sessionKey);setOpen(false);}const toggle = () => setOpen((current) => !current);+ const show = () => {+ if (!open) setOpen(true);+ };useEffect(() => {if (sessionKey === null) return;const onKeyDown = (event: KeyboardEvent) => {@@ -62,7 +86,7 @@ export function LiteAdminFrame({ children }: { children: ReactNode }) {return () => document.removeEventListener("keydown", onKeyDown);}, [sessionKey]);return (- <LiteAdminContext.Provider value={configured ? { open, toggle } : null}>+ <LiteAdminContext.Provider value={configured ? { open, toggle, show, homeContainer, setHomeContainer } : null}>{children}{configured && (<DockedPanel key={configured.key} session={configured.session} open={open} close={() => setOpen(false)} />@@ -71,6 +95,29 @@ export function LiteAdminFrame({ children }: { children: ReactNode }) {);}+export function LiteAdminHome() {+ const state = useContext(LiteAdminContext);+ if (!state) return null;+ const { open, show, setHomeContainer } = state;+ return (+ <section aria-label="Ask LiteAdmin" hidden={open} className="rounded-2xl border bg-card">+ <div className="flex items-center justify-between gap-3 p-4">+ <div>+ <h2 className="flex items-center gap-2 text-sm font-medium">+ <Sparkles className="size-4 text-info" />+ LiteAdmin+ </h2>+ <p className="mt-1 text-sm text-muted-foreground">Ask about your gateway. Review changes in chat.</p>+ </div>+ <Button variant="ghost" size="sm" onClick={show}>+ Open chat+ </Button>+ </div>+ <div ref={setHomeContainer} />+ </section>+ );+}+export default function LiteAdminTrigger() {const state = useContext(LiteAdminContext);if (!state) return null;@@ -129,39 +176,43 @@ function Destination({}) {const [approved, setApproved] = useState(false);if (target?.baseUrl && (!target.requiresConsent || approved)) {- return <LiteAdminChat session={{ ...session, inferenceBaseUrl: target.baseUrl }} open={open} close={close} />;+ return <LiteAdminChats session={{ ...session, inferenceBaseUrl: target.baseUrl }} open={open} close={close} />;}return (- <Panel open={open}>+ <Panel+ open={open}+ composer={+ <div className="p-4">+ {loading && <Skeleton className="h-24" aria-label="Loading gateway settings" />}+ {!loading && !target?.baseUrl && (+ <Alert variant="destructive">+ <AlertDescription>{target?.error || "Could not load gateway settings."}</AlertDescription>+ <Button variant="link" onClick={retry}>+ Retry+ </Button>+ </Alert>+ )}+ {!loading && target?.baseUrl && (+ <Card size="sm">+ <CardHeader>+ <CardTitle>Connect to the configured gateway</CardTitle>+ </CardHeader>+ <CardContent className="space-y-3">+ <p className="break-all font-mono text-xs">{target.baseUrl}</p>+ <p className="text-muted-foreground">+ This gateway uses a different address. LiteAdmin will send your existing session credential to the+ address shown above.+ </p>+ </CardContent>+ <CardFooter>+ <Button onClick={() => setApproved(true)}>Use configured gateway</Button>+ </CardFooter>+ </Card>+ )}+ </div>+ }+ ><PanelHeader close={close} />- <div className="p-4">- {loading && <Skeleton className="h-24" aria-label="Loading gateway settings" />}- {!loading && !target?.baseUrl && (- <Alert variant="destructive">- <AlertDescription>{target?.error || "Could not load gateway settings."}</AlertDescription>- <Button variant="link" onClick={retry}>- Retry- </Button>- </Alert>- )}- {!loading && target?.baseUrl && (- <Card size="sm">- <CardHeader>- <CardTitle>Connect to the configured gateway</CardTitle>- </CardHeader>- <CardContent className="space-y-3">- <p className="break-all font-mono text-xs">{target.baseUrl}</p>- <p className="text-muted-foreground">- This gateway uses a different address. LiteAdmin will send your existing session credential to the- address shown above.- </p>- </CardContent>- <CardFooter>- <Button onClick={() => setApproved(true)}>Use configured gateway</Button>- </CardFooter>- </Card>- )}- </div></Panel>);}@@ -170,12 +221,16 @@ function Destination({function Panel({open,initialFocus,+ composer,children,}: {open: boolean;initialFocus?: RefObject<HTMLElement | null>;+ composer: ReactNode;children: ReactNode;}) {+ const state = useContext(LiteAdminContext);+ const homeContainer = !open ? state?.homeContainer : null;const ref = useRef<HTMLElement>(null);useEffect(() => {const panel = ref.current;@@ -196,19 +251,154 @@ function Panel({)}>{children}+ {homeContainer ? createPortal(composer, homeContainer) : composer}</aside>);}-function LiteAdminChat({ session, open, close }: { session: LiteAdminSession; open: boolean; close: () => void }) {+function LiteAdminChats({ session, open, close }: { session: LiteAdminSession; open: boolean; close: () => void }) {+ const [tabs, setTabs] = useState<{ chats: ChatTab[]; activeId: number; nextId: number }>({+ chats: [{ id: 1, phase: "idle" }],+ activeId: 1,+ nextId: 2,+ });+ const reviewRef = useRef<HTMLDivElement>(null);+ const activeTabRef = useRef<HTMLButtonElement>(null);+ const focusAfterClose = useRef(false);+ useLayoutEffect(() => {+ if (!focusAfterClose.current) return;+ focusAfterClose.current = false;+ activeTabRef.current?.focus();+ });+ const addChat = () => {+ setTabs((current) => ({+ chats: [...current.chats, { id: current.nextId, phase: "idle" }],+ activeId: current.nextId,+ nextId: current.nextId + 1,+ }));+ };+ const closeChat = (id: number) => {+ if (tabs.chats.some((chat) => chat.id === id && chat.phase === "applying")) return;+ focusAfterClose.current = true;+ setTabs((current) => {+ const closing = current.chats.find((chat) => chat.id === id);+ if (!closing || closing.phase === "applying") return current;+ const remaining = current.chats.filter((chat) => chat.id !== id);+ const next = remaining.find((chat) => chat.id > id) ?? remaining.at(-1);+ if (!next) {+ return {+ chats: [{ id: current.nextId, phase: "idle" }],+ activeId: current.nextId,+ nextId: current.nextId + 1,+ };+ }+ return { ...current, chats: remaining, activeId: current.activeId === id ? next.id : current.activeId };+ });+ };+ const updatePhase = useCallback((id: number, phase: ChatPhase) => {+ setTabs((current) => {+ if (!current.chats.some((chat) => chat.id === id && chat.phase !== phase)) return current;+ return { ...current, chats: current.chats.map((chat) => (chat.id === id ? { ...chat, phase } : chat)) };+ });+ }, []);+ return (+ <Tabs+ value={tabs.activeId}+ onValueChange={(id) => {+ if (typeof id === "number") setTabs((current) => ({ ...current, activeId: id }));+ }}+ className="contents"+ >+ <Panel open={open} initialFocus={reviewRef} composer={null}>+ <PanelHeader close={close}>+ <Button variant="ghost" size="icon-sm" aria-label="New chat" title="New chat" onClick={addChat}>+ <Plus className="size-4" />+ </Button>+ </PanelHeader>+ <TabsList+ aria-label="LiteAdmin chats"+ className="h-auto w-full shrink-0 justify-start overflow-x-auto rounded-none border-b bg-transparent p-2"+ >+ {tabs.chats.map((tab) => (+ <div key={tab.id} className="flex shrink-0 items-center">+ <TabsTrigger+ ref={tabs.activeId === tab.id ? activeTabRef : undefined}+ value={tab.id}+ aria-label={`Chat ${tab.id}`}+ title={tab.phase === "review" ? "Approval needed" : undefined}+ className="h-8 flex-none"+ >+ Chat {tab.id}+ {tab.phase !== "idle" && <span aria-hidden className="size-1.5 rounded-full bg-info" />}+ </TabsTrigger>+ <Button+ variant="ghost"+ size="icon-xs"+ aria-label={`Close Chat ${tab.id}`}+ title={tab.phase === "applying" ? "Wait for this change to finish" : `Close Chat ${tab.id}`}+ disabled={tab.phase === "applying"}+ onClick={() => closeChat(tab.id)}+ >+ <X className="size-3" />+ </Button>+ </div>+ ))}+ </TabsList>+ {tabs.chats.map((tab) => (+ <LiteAdminChat+ key={tab.id}+ id={tab.id}+ session={session}+ active={tabs.activeId === tab.id}+ open={open}+ reviewRef={reviewRef}+ onPhaseChange={updatePhase}+ />+ ))}+ </Panel>+ </Tabs>+ );+}++function useForegroundReviewFocus(+ entries: ConversationEntry[],+ foreground: boolean,+ reviewRef: RefObject<HTMLDivElement | null>,+) {+ const lastReviewId = useRef<string | null>(null);+ const pendingReviewId = entries.find((entry) => entry.kind === "action" && entry.status === "review")?.id ?? null;+ useEffect(() => {+ if (lastReviewId.current === pendingReviewId) return;+ lastReviewId.current = pendingReviewId;+ if (foreground && pendingReviewId) reviewRef.current?.focus({ preventScroll: true });+ }, [foreground, pendingReviewId, reviewRef]);+}++function LiteAdminChat({+ id,+ session,+ active,+ open,+ reviewRef,+ onPhaseChange,+}: {+ id: number;+ session: LiteAdminSession;+ active: boolean;+ open: boolean;+ reviewRef: RefObject<HTMLDivElement | null>;+ onPhaseChange: (id: number, phase: ChatPhase) => void;+}) {+ const state = useContext(LiteAdminContext);const chat = useLiteAdmin(session);const [input, setInput] = useState("");const [model, setModel] = useState<string | null>(null);- const reviewRef = useRef<HTMLDivElement>(null);+ useForegroundReviewFocus(chat.entries, active && open, reviewRef);+ useEffect(() => onPhaseChange(id, chat.phase), [id, chat.phase, onPhaseChange]);const modelQuery = {queryKey: ["liteadmin-models", session.accessToken, session.managementBaseUrl],queryFn: () => fetchAvailableModels(session.accessToken),- enabled: open,+ enabled: active && (open || Boolean(state?.homeContainer)),select: (available: ModelGroup[]) =>available.filter((item) => isModeCompatibleWithEndpoint(item.mode, EndpointType.CHAT)),};@@ -221,26 +411,31 @@ function LiteAdminChat({ session, open, close }: { session: LiteAdminSession; opconst submitDisabled = busy || models.isError || !hasValidInput;const send = () => {if (submitDisabled || !selectedModel) return;+ state?.show();void chat.send(input, selectedModel);setInput("");};+ if (!active) return null;+ const homeContainer = !open ? state?.homeContainer : null;+ const composer = (+ <div className="space-y-3 border-t p-3">+ <ModelPicker models={models} value={selectedModel} onChange={setModel} disabled={busy} />+ {tooLong && <FieldError>Keep your message within {MAX_INPUT_LENGTH.toLocaleString()} characters.</FieldError>}+ <ChatComposer+ value={input}+ onChange={setInput}+ onSubmit={send}+ onCancel={chat.phase === "applying" ? undefined : chat.stop}+ placeholder="Ask LiteAdmin…"+ disabled={busy || !selectedModel}+ isLoading={busy}+ submitDisabled={submitDisabled}+ />+ <p className="text-xs text-muted-foreground">Use a model you trust with your gateway data.</p>+ </div>+ );return (- <Panel open={open} initialFocus={chat.phase === "review" ? reviewRef : undefined}>- <PanelHeader close={close}>- <Button- variant="ghost"- size="icon-sm"- aria-label="New chat"- title="New chat"- disabled={chat.phase === "applying"}- onClick={() => {- chat.reset();- setInput("");- }}- >- <RotateCcw className="size-4" />- </Button>- </PanelHeader>+ <TabsContent value={id} className="flex min-h-0 flex-1 flex-col"><LiteAdminConversationentries={chat.entries}thinking={chat.phase === "thinking"}@@ -248,49 +443,53 @@ function LiteAdminChat({ session, open, close }: { session: LiteAdminSession; opreviewRef={reviewRef}onAnswer={chat.answer}/>- <div className="space-y-3 border-t p-3">- {models.isPending ? (- <Skeleton className="h-8" aria-label="Loading models" />- ) : (- <SearchSelect- aria-label="LiteAdmin model"- options={(models.data ?? []).map((item) => ({ value: item.model_group, label: item.model_group }))}- value={selectedModel}- onValueChange={setModel}- placeholder="Choose a chat model"- disabled={busy}- allowClear={false}- />- )}- {models.isError && (- <Alert variant="destructive">- <AlertDescription>- Could not load models.{" "}- <Button variant="link" onClick={() => void models.refetch()}>- Retry- </Button>- </AlertDescription>- </Alert>- )}- {models.isSuccess && models.data.length === 0 && (- <Alert role="status">- <AlertDescription>Add a chat model to your gateway to use LiteAdmin.</AlertDescription>- </Alert>- )}- {tooLong && <FieldError>Keep your message within {MAX_INPUT_LENGTH.toLocaleString()} characters.</FieldError>}- <ChatComposer- value={input}- onChange={setInput}- onSubmit={send}- onCancel={chat.phase === "applying" ? undefined : chat.stop}- placeholder="Ask LiteAdmin…"- disabled={busy || !selectedModel}- isLoading={busy}- submitDisabled={submitDisabled}+ {homeContainer ? createPortal(composer, homeContainer) : composer}+ </TabsContent>+ );+}++function ModelPicker({+ models,+ value,+ onChange,+ disabled,+}: {+ models: UseQueryResult<ModelGroup[]>;+ value: string | null;+ onChange: (value: string | null) => void;+ disabled: boolean;+}) {+ return (+ <>+ {models.isPending ? (+ <Skeleton className="h-8" aria-label="Loading models" />+ ) : (+ <SearchSelect+ aria-label="LiteAdmin model"+ options={(models.data ?? []).map((item) => ({ value: item.model_group, label: item.model_group }))}+ value={value}+ onValueChange={onChange}+ placeholder="Choose a chat model"+ disabled={disabled}+ allowClear={false}/>- <p className="text-xs text-muted-foreground">Use a model you trust with your gateway data.</p>- </div>- </Panel>+ )}+ {models.isError && (+ <Alert variant="destructive">+ <AlertDescription>+ Could not load models.{" "}+ <Button variant="link" onClick={() => void models.refetch()}>+ Retry+ </Button>+ </AlertDescription>+ </Alert>+ )}+ {models.isSuccess && models.data.length === 0 && (+ <Alert role="status">+ <AlertDescription>Add a chat model to your gateway to use LiteAdmin.</AlertDescription>+ </Alert>+ )}+ </>);}diff --git a/ui/litellm-dashboard/src/components/liteadmin/LiteAdminConversation.tsx b/ui/litellm-dashboard/src/components/liteadmin/LiteAdminConversation.tsxindex 826db57a736..014597dba39 100644--- a/ui/litellm-dashboard/src/components/liteadmin/LiteAdminConversation.tsx+++ b/ui/litellm-dashboard/src/components/liteadmin/LiteAdminConversation.tsx@@ -99,8 +99,7 @@ function ActionCard({useEffect(() => {if (!open || !review) return;scrollToEnd();- reviewRef.current?.focus({ preventScroll: true });- }, [entry.id, open, review, reviewRef, scrollToEnd]);+ }, [entry.id, open, review, scrollToEnd]);const answer = (approved: boolean) => {scrollToEnd();onAnswer(entry.id, approved);