diff --git a/litellm/responses/mcp/mcp_streaming_iterator.py b/litellm/responses/mcp/mcp_streaming_iterator.py
index 3c24a703b686..c705a04963ca 100644
--- a/litellm/responses/mcp/mcp_streaming_iterator.py
+++ b/litellm/responses/mcp/mcp_streaming_iterator.py
@@ -24,6 +24,8 @@
else:
MCPTool = Any
+MAX_MCP_TOOL_CALL_ROUNDS = 5
+
async def create_mcp_list_tools_events(
mcp_tools_with_litellm_proxy: List[ToolParam],
@@ -265,9 +267,7 @@ def __init__(
self.should_auto_execute = self._should_auto_execute_tools()
# Streaming state management
- self.phase = (
- "initial_response" # initial_response -> mcp_discovery -> tool_execution -> follow_up_response -> finished
- )
+ self.phase = "initial_response" # initial_response -> mcp_discovery -> (continue_initial_response <-> tool_execution) -> finished
self.finished = False
# Event queues and generation flags
@@ -281,11 +281,23 @@ def __init__(
# Iterator references
self.base_iterator: Optional[Union[Any, ResponsesAPIResponse]] = base_iterator # Will be created when needed
- self.follow_up_iterator: Optional[Any] = None
# Response collection for tool execution
self.collected_response: Optional[ResponsesAPIResponse] = None
+ # Counts completed rounds of tool execution, so a model that keeps
+ # calling tools (e.g. retrying after an error) can't loop forever.
+ # Capped in _create_follow_up_iterator, which drops "tools" from the
+ # request once the cap is hit so the model must answer in text.
+ self.tool_call_round = 0
+ # The collected_response that self.tool_results was computed from.
+ # _create_follow_up_iterator only builds a follow-up when this is
+ # still the current collected_response — otherwise a round whose
+ # response had no tool calls (e.g. the model finally answered in
+ # text) would incorrectly reuse tool_results left over from an
+ # earlier round and keep looping instead of finishing.
+ self._tool_results_for_response: Optional[ResponsesAPIResponse] = None
+
# Set up model metadata (will be updated when we get the real iterator)
self.model = self.original_request_params.get("model", "unknown")
self.litellm_metadata = {}
@@ -376,10 +388,11 @@ async def __anext__(self) -> ResponsesAPIStreamingResponse:
Phase-based streaming:
1. initial_response - Stream the first LLM response (includes response.created, response.in_progress, response.output_item.added)
2. mcp_discovery - Emit MCP discovery events (after response.output_item.added)
- 3. continue_initial_response - Continue streaming the initial response content
+ 3. continue_initial_response - Stream the current round's response (initial or follow-up).
+ On completion, if auto-execute is on and the response contains tool calls, loops back
+ through tool_execution/follow-up instead of ending, up to MAX_MCP_TOOL_CALL_ROUNDS.
4. tool_execution - Emit tool execution events
- 5. follow_up_response - Stream the follow-up response
- 6. finished - End iteration
+ 5. finished - End iteration
"""
# Phase 1: Initial Response Stream (emit standard OpenAI events first)
@@ -415,21 +428,17 @@ async def __anext__(self) -> ResponsesAPIStreamingResponse:
if self.tool_execution_events:
return self.tool_execution_events.pop(0)
- # Move to follow-up response phase
- self.phase = "follow_up_response"
+ # Route the follow-up call back through continue_initial_response so
+ # its completion is checked for further tool calls the same way the
+ # initial response is — otherwise a model that needs a second round
+ # of tool calls (e.g. retrying after an error) would have that round
+ # silently dropped and the stream would end with no final text.
await self._create_follow_up_iterator()
-
- # Phase 5: Follow-up Response Stream
- if self.phase == "follow_up_response":
- if self.follow_up_iterator:
- try:
- return await cast(Any, self.follow_up_iterator).__anext__() # type: ignore[attr-defined]
- except StopAsyncIteration:
- self.phase = "finished"
- raise
- else:
- self.phase = "finished"
- raise StopAsyncIteration
+ if self.base_iterator is not None:
+ self.phase = "continue_initial_response"
+ return await self.__anext__()
+ self.phase = "finished"
+ raise StopAsyncIteration
# Phase 6: Finished
if self.phase == "finished":
@@ -599,6 +608,7 @@ async def _generate_tool_execution_events(self) -> None:
tool_calls = []
if not tool_calls:
return
+ self.tool_call_round += 1
for tool_call in tool_calls:
(
@@ -686,6 +696,7 @@ async def _generate_tool_execution_events(self) -> None:
# Store tool results for follow-up call
self.tool_results = tool_results
+ self._tool_results_for_response = self.collected_response
except Exception as e:
verbose_logger.error(f"Error in tool execution: {e}")
@@ -693,10 +704,16 @@ async def _generate_tool_execution_events(self) -> None:
traceback.print_exc()
self.tool_results = []
+ self._tool_results_for_response = self.collected_response
async def _create_follow_up_iterator(self) -> None:
"""Create the follow-up response iterator with tool results"""
- if not self.collected_response or not hasattr(self, "tool_results"):
+ if self.collected_response is None or self.collected_response is not self._tool_results_for_response:
+ # Either no response to follow up on, or the current round's
+ # response had no tool calls (self.tool_results is stale from an
+ # earlier round) — there is nothing to follow up with, so end
+ # the stream instead of reusing stale tool results.
+ self.base_iterator = None
return
from litellm.responses.main import aresponses
@@ -726,18 +743,31 @@ async def _create_follow_up_iterator(self) -> None:
# Remove tool_choice to avoid forcing more tool calls
follow_up_params.pop("tool_choice", None)
+ if self.tool_call_round >= MAX_MCP_TOOL_CALL_ROUNDS:
+ # Hit the round cap: drop tools entirely so the model must
+ # answer in text instead of emitting another (unexecuted)
+ # tool call that would otherwise end the stream in silence.
+ follow_up_params.pop("tools", None)
+ verbose_logger.warning(
+ "MCP auto-execute hit MAX_MCP_TOOL_CALL_ROUNDS=%s; forcing a text-only follow-up.",
+ MAX_MCP_TOOL_CALL_ROUNDS,
+ )
+
follow_up_response = await aresponses(**follow_up_params)
- # Set up the follow-up iterator
+ # Route the follow-up through the same base_iterator machinery as
+ # the initial call so its completion is checked for further tool
+ # calls (see phase 4 in __anext__).
if hasattr(follow_up_response, "__aiter__"):
- self.follow_up_iterator = follow_up_response
+ self.base_iterator = follow_up_response
+ self.collected_response = None
except Exception as e:
verbose_logger.error(f"Error creating follow-up iterator: {e}")
import traceback
traceback.print_exc()
- self.follow_up_iterator = None
+ self.base_iterator = None
def __iter__(self):
return self
diff --git a/tests/test_litellm/responses/mcp/test_mcp_streaming_iterator.py b/tests/test_litellm/responses/mcp/test_mcp_streaming_iterator.py
new file mode 100644
index 000000000000..ecf89ce18d4d
--- /dev/null
+++ b/tests/test_litellm/responses/mcp/test_mcp_streaming_iterator.py
@@ -0,0 +1,171 @@
+import sys
+import types
+from types import SimpleNamespace
+from unittest.mock import AsyncMock, MagicMock
+
+import pytest
+from mcp.types import CallToolResult, TextContent
+
+import litellm # noqa: F401 - ensures litellm.responses.main is registered in sys.modules
+from litellm.responses.mcp.mcp_streaming_iterator import (
+ MAX_MCP_TOOL_CALL_ROUNDS,
+ MCPEnhancedStreamingIterator,
+)
+from litellm.types.llms.openai import ResponsesAPIResponse, ResponsesAPIStreamEvents
+
+# `litellm.__init__` re-exports a function named `responses`, which shadows the
+# `litellm.responses` subpackage as an attribute — `import litellm.responses.main`
+# can resolve to the unrelated third-party `responses` package instead. Look the
+# real submodule up in sys.modules directly to sidestep the shadowing.
+responses_main_module = sys.modules["litellm.responses.main"]
+
+
+class _FakeAsyncStream:
+ """Minimal async iterator yielding pre-built chunks, one per __anext__ call."""
+
+ def __init__(self, chunks):
+ self._chunks = list(chunks)
+
+ def __aiter__(self):
+ return self
+
+ async def __anext__(self):
+ if not self._chunks:
+ raise StopAsyncIteration
+ return self._chunks.pop(0)
+
+
+def _output_item_added_chunk():
+ return SimpleNamespace(type=ResponsesAPIStreamEvents.OUTPUT_ITEM_ADDED)
+
+
+def _completed_chunk(output):
+ response = ResponsesAPIResponse(id="resp-1", created_at=0, output=output)
+ return SimpleNamespace(type=ResponsesAPIStreamEvents.RESPONSE_COMPLETED, response=response)
+
+
+def _function_call(call_id: str, name: str, arguments: str = "{}"):
+ return {"type": "function_call", "call_id": call_id, "name": name, "arguments": arguments}
+
+
+def _text_message(text: str):
+ return {"type": "message", "role": "assistant", "content": [{"type": "output_text", "text": text}]}
+
+
+def _tool_call_stream(call_id: str, tool_name: str) -> _FakeAsyncStream:
+ return _FakeAsyncStream([_completed_chunk([_function_call(call_id, tool_name)])])
+
+
+def _text_only_stream(text: str) -> _FakeAsyncStream:
+ return _FakeAsyncStream([_completed_chunk([_text_message(text)])])
+
+
+def _mock_mcp_environment(monkeypatch: pytest.MonkeyPatch) -> AsyncMock:
+ """Patch the MCP tool-call plumbing so _execute_tool_calls can run in tests."""
+ call_tool = AsyncMock(return_value=CallToolResult(content=[TextContent(type="text", text="ok")], isError=False))
+ fake_manager = types.SimpleNamespace(
+ call_tool=call_tool,
+ _get_mcp_server_from_tool_name=MagicMock(return_value=None),
+ )
+ monkeypatch.setattr(
+ "litellm.proxy._experimental.mcp_server.mcp_server_manager.global_mcp_server_manager",
+ fake_manager,
+ )
+ monkeypatch.setitem(
+ sys.modules,
+ "litellm.proxy.proxy_server",
+ types.SimpleNamespace(proxy_logging_obj=MagicMock()),
+ )
+ return call_tool
+
+
+def _make_iterator(initial_chunks) -> MCPEnhancedStreamingIterator:
+ return MCPEnhancedStreamingIterator(
+ base_iterator=_FakeAsyncStream(initial_chunks),
+ mcp_events=[],
+ tool_server_map={"read_wiki_contents": "deepwiki"},
+ mcp_tools_with_litellm_proxy=[{"require_approval": "never"}],
+ user_api_key_auth=None,
+ original_request_params={
+ "model": "gpt-4",
+ "input": "what is berriai/litellm?",
+ "tools": [{"type": "mcp"}],
+ },
+ )
+
+
+@pytest.mark.asyncio
+async def test_second_round_tool_call_is_executed_and_reaches_final_text(monkeypatch):
+ """
+ Regression test: a tool call that errors, followed by the model retrying
+ the tool in its follow-up turn, must have that second tool call executed
+ too — the stream should not silently end after round 1 with no final
+ text (see PR discussion: deepwiki tool call errors, model retries once,
+ reply used to just stop with no explanation).
+ """
+ call_tool = _mock_mcp_environment(monkeypatch)
+
+ aresponses_mock = AsyncMock(
+ side_effect=[
+ _tool_call_stream("call_2", "read_wiki_contents"), # round 2: model retries
+ _text_only_stream("Here's what I found after retrying."), # round 3: final answer
+ ]
+ )
+ monkeypatch.setattr(responses_main_module, "aresponses", aresponses_mock)
+
+ iterator = _make_iterator(
+ [
+ _output_item_added_chunk(),
+ _completed_chunk([_function_call("call_1", "read_wiki_contents")]), # round 1: errors
+ ]
+ )
+
+ chunks = [chunk async for chunk in iterator]
+
+ # Both rounds' tool calls were actually executed, not just streamed unexecuted.
+ assert call_tool.call_count == 2
+ assert iterator.tool_call_round == 2
+
+ # The stream reached round 3 and produced the final text response instead
+ # of stopping after round 1 or round 2.
+ completed_chunks = [c for c in chunks if getattr(c, "type", None) == ResponsesAPIStreamEvents.RESPONSE_COMPLETED]
+ assert len(completed_chunks) == 3
+ final_output = completed_chunks[-1].response.output
+ assert final_output[0]["content"][0]["text"] == "Here's what I found after retrying."
+
+
+@pytest.mark.asyncio
+async def test_tool_call_rounds_are_capped(monkeypatch):
+ """
+ A model that keeps calling tools every round must not loop forever —
+ auto-execution stops at MAX_MCP_TOOL_CALL_ROUNDS, and the follow-up made
+ at the cap drops "tools" from the request so the model is forced to
+ answer in text instead of the stream just hanging.
+ """
+ call_tool = _mock_mcp_environment(monkeypatch)
+
+ # Rounds 2..MAX_MCP_TOOL_CALL_ROUNDS keep calling the tool; the call made
+ # once the cap is hit returns a text-only response.
+ tool_call_streams = [
+ _tool_call_stream(f"call_{i}", "read_wiki_contents") for i in range(2, MAX_MCP_TOOL_CALL_ROUNDS + 1)
+ ]
+ aresponses_mock = AsyncMock(side_effect=[*tool_call_streams, _text_only_stream("giving up on tools")])
+ monkeypatch.setattr(responses_main_module, "aresponses", aresponses_mock)
+
+ iterator = _make_iterator(
+ [
+ _output_item_added_chunk(),
+ _completed_chunk([_function_call("call_1", "read_wiki_contents")]),
+ ]
+ )
+
+ _ = [chunk async for chunk in iterator]
+
+ assert iterator.tool_call_round == MAX_MCP_TOOL_CALL_ROUNDS
+ assert call_tool.call_count == MAX_MCP_TOOL_CALL_ROUNDS
+ assert aresponses_mock.call_count == MAX_MCP_TOOL_CALL_ROUNDS
+
+ # Every follow-up before the cap still offered tools; only the capped one drops them.
+ for call in aresponses_mock.call_args_list[:-1]:
+ assert "tools" in call.kwargs
+ assert "tools" not in aresponses_mock.call_args_list[-1].kwargs
diff --git a/ui/litellm-dashboard/src/app/chat/api-keys/page.tsx b/ui/litellm-dashboard/src/app/chat/api-keys/page.tsx
new file mode 100644
index 000000000000..ffba47479a11
--- /dev/null
+++ b/ui/litellm-dashboard/src/app/chat/api-keys/page.tsx
@@ -0,0 +1,14 @@
+"use client";
+
+import { useChatShell } from "@/contexts/ChatShellContext";
+import KeysPanel from "@/components/chat/KeysPanel";
+
+export default function ApiKeysPage() {
+ const { accessToken, userId, premiumUser } = useChatShell();
+
+ return (
+
+
+
+ );
+}
diff --git a/ui/litellm-dashboard/src/app/chat/credentials/page.tsx b/ui/litellm-dashboard/src/app/chat/credentials/page.tsx
new file mode 100644
index 000000000000..d82ed603e044
--- /dev/null
+++ b/ui/litellm-dashboard/src/app/chat/credentials/page.tsx
@@ -0,0 +1,14 @@
+"use client";
+
+import { useChatShell } from "@/contexts/ChatShellContext";
+import MCPCredentialsTab from "@/components/chat/MCPCredentialsTab";
+
+export default function CredentialsPage() {
+ const { accessToken } = useChatShell();
+
+ return (
+
+
+
+ );
+}
diff --git a/ui/litellm-dashboard/src/app/chat/integrations/page.tsx b/ui/litellm-dashboard/src/app/chat/integrations/page.tsx
new file mode 100644
index 000000000000..f85dd591199c
--- /dev/null
+++ b/ui/litellm-dashboard/src/app/chat/integrations/page.tsx
@@ -0,0 +1,38 @@
+"use client";
+
+import { Suspense, useEffect } from "react";
+import { useRouter, useSearchParams } from "next/navigation";
+import { useChatShell } from "@/contexts/ChatShellContext";
+import MCPAppsPanel from "@/components/chat/MCPAppsPanel";
+
+// useSearchParams() requires a Suspense boundary for static export.
+function IntegrationsPageContent() {
+ const { accessToken, selectedMCPServers, setSelectedMCPServers } = useChatShell();
+ const router = useRouter();
+ const searchParams = useSearchParams();
+ const oauthReturn = searchParams.get("mcpOauthReturn");
+
+ // Clean up the OAuth return param after it's been consumed — real routing means
+ // we no longer need it to pick a tab, but it should not linger in the address bar.
+ useEffect(() => {
+ if (oauthReturn) {
+ const url = new URL(window.location.href);
+ url.searchParams.delete("mcpOauthReturn");
+ router.replace(url.pathname + url.search);
+ }
+ }, [oauthReturn, router]);
+
+ return (
+
+
+
+ );
+}
+
+export default function IntegrationsPage() {
+ return (
+
+
+
+ );
+}
diff --git a/ui/litellm-dashboard/src/app/chat/layout.test.tsx b/ui/litellm-dashboard/src/app/chat/layout.test.tsx
new file mode 100644
index 000000000000..642fb6880573
--- /dev/null
+++ b/ui/litellm-dashboard/src/app/chat/layout.test.tsx
@@ -0,0 +1,86 @@
+import { afterEach, describe, expect, it, vi } from "vitest";
+import { render, screen } from "@testing-library/react";
+import ChatLayout from "./layout";
+
+const { mockUseAuthorized, mockUseUISettings, mockReplace, mockMigratedHref, state } = vi.hoisted(() => {
+ const state = {
+ enableChatUI: false,
+ isUISettingsLoading: false,
+ };
+ return {
+ state,
+ mockReplace: vi.fn(),
+ mockMigratedHref: vi.fn((segment: string) => `/mocked-ui/${segment}`),
+ mockUseAuthorized: vi.fn(() => ({
+ accessToken: "token-123",
+ userRole: "Internal User",
+ userId: "user-1",
+ userEmail: "user@example.com",
+ premiumUser: false,
+ })),
+ mockUseUISettings: vi.fn(() => ({
+ data: { values: { enable_chat_ui: state.enableChatUI } },
+ isLoading: state.isUISettingsLoading,
+ })),
+ };
+});
+
+vi.mock("next/navigation", () => ({
+ useRouter: () => ({ replace: mockReplace }),
+}));
+vi.mock("@/app/(dashboard)/hooks/useAuthorized", () => ({ default: mockUseAuthorized }));
+vi.mock("@/app/(dashboard)/hooks/uiSettings/useUISettings", () => ({ useUISettings: mockUseUISettings }));
+vi.mock("@/utils/migratedPages", () => ({ migratedHref: mockMigratedHref }));
+vi.mock("@/components/navbar", () => ({ default: () =>
}));
+vi.mock("@/contexts/ThemeContext", () => ({
+ ThemeProvider: ({ children }: { children: React.ReactNode }) => <>{children}>,
+}));
+vi.mock("@/contexts/ChatShellContext", () => ({
+ ChatShellProvider: ({ children }: { children: React.ReactNode }) => <>{children}>,
+}));
+vi.mock("@/components/chat/ChatShell", () => ({
+ default: ({ children }: { children: React.ReactNode }) => {children}
,
+}));
+
+describe("ChatLayout", () => {
+ afterEach(() => {
+ state.enableChatUI = false;
+ state.isUISettingsLoading = false;
+ mockReplace.mockClear();
+ mockMigratedHref.mockClear();
+ });
+
+ it("renders the chat shell when enable_chat_ui is on", () => {
+ state.enableChatUI = true;
+ render(
+
+
+ ,
+ );
+ expect(screen.getByTestId("chat-shell")).toBeInTheDocument();
+ expect(screen.getByTestId("page-content")).toBeInTheDocument();
+ expect(mockReplace).not.toHaveBeenCalled();
+ });
+
+ it("redirects to the dashboard when enable_chat_ui is off", () => {
+ state.enableChatUI = false;
+ render(
+
+
+ ,
+ );
+ expect(screen.queryByTestId("chat-shell")).not.toBeInTheDocument();
+ expect(mockReplace).toHaveBeenCalledWith("/mocked-ui/");
+ });
+
+ it("renders nothing while UI settings are still loading", () => {
+ state.isUISettingsLoading = true;
+ render(
+
+
+ ,
+ );
+ expect(screen.queryByTestId("chat-shell")).not.toBeInTheDocument();
+ expect(mockReplace).not.toHaveBeenCalled();
+ });
+});
diff --git a/ui/litellm-dashboard/src/app/chat/layout.tsx b/ui/litellm-dashboard/src/app/chat/layout.tsx
new file mode 100644
index 000000000000..fe7c327d25b9
--- /dev/null
+++ b/ui/litellm-dashboard/src/app/chat/layout.tsx
@@ -0,0 +1,54 @@
+"use client";
+
+import { Suspense, useEffect } from "react";
+import { useRouter } from "next/navigation";
+import useAuthorized from "@/app/(dashboard)/hooks/useAuthorized";
+import { useUISettings } from "@/app/(dashboard)/hooks/uiSettings/useUISettings";
+import Navbar from "@/components/navbar";
+import { ThemeProvider } from "@/contexts/ThemeContext";
+import { ChatShellProvider } from "@/contexts/ChatShellContext";
+import ChatShell from "@/components/chat/ChatShell";
+import { migratedHref } from "@/utils/migratedPages";
+
+// ChatShellProvider uses useSearchParams(), which requires a Suspense boundary for static export.
+function ChatLayoutContent({ children }: { children: React.ReactNode }) {
+ const { accessToken, userRole, userId, userEmail, premiumUser } = useAuthorized();
+ const { data: uiSettings, isLoading: isUISettingsLoading } = useUISettings();
+ const router = useRouter();
+
+ const chatEnabled = Boolean(uiSettings?.values?.enable_chat_ui);
+ const blocked = !isUISettingsLoading && !chatEnabled;
+
+ useEffect(() => {
+ if (blocked) router.replace(migratedHref(""));
+ }, [blocked, router]);
+
+ if (isUISettingsLoading || blocked) return null;
+
+ return (
+
+
+
+ );
+}
+
+export default function ChatLayout({ children }: { children: React.ReactNode }) {
+ return (
+
+ {children}
+
+ );
+}
diff --git a/ui/litellm-dashboard/src/app/chat/page.test.tsx b/ui/litellm-dashboard/src/app/chat/page.test.tsx
deleted file mode 100644
index 658142d47a6d..000000000000
--- a/ui/litellm-dashboard/src/app/chat/page.test.tsx
+++ /dev/null
@@ -1,83 +0,0 @@
-import { afterEach, describe, expect, it, vi } from "vitest";
-import { render, screen } from "@testing-library/react";
-import ChatPageRoute from "./page";
-
-const { mockUseAuthorized, mockUseUISettings, mockUseUIConfig, mockReplace, state } = vi.hoisted(() => {
- const state = {
- userRole: "Internal User" as string,
- enableChatUI: false,
- isUISettingsLoading: false,
- serverRootPath: undefined as string | undefined,
- };
- return {
- state,
- mockReplace: vi.fn(),
- mockUseAuthorized: vi.fn(() => ({
- accessToken: "token-123",
- userRole: state.userRole,
- userId: "user-1",
- userEmail: "user@example.com",
- })),
- mockUseUISettings: vi.fn(() => ({
- data: { values: { enable_chat_ui: state.enableChatUI } },
- isLoading: state.isUISettingsLoading,
- })),
- mockUseUIConfig: vi.fn(() => ({ data: { server_root_path: state.serverRootPath } })),
- };
-});
-
-vi.mock("next/navigation", () => ({
- useRouter: () => ({ replace: mockReplace }),
-}));
-vi.mock("@/app/(dashboard)/hooks/useAuthorized", () => ({ default: mockUseAuthorized }));
-vi.mock("@/app/(dashboard)/hooks/uiSettings/useUISettings", () => ({ useUISettings: mockUseUISettings }));
-vi.mock("@/app/(dashboard)/hooks/uiConfig/useUIConfig", () => ({ useUIConfig: mockUseUIConfig }));
-vi.mock("@/components/chat/ChatPage", () => ({ default: () =>
}));
-
-describe("ChatPageRoute", () => {
- afterEach(() => {
- state.userRole = "Internal User";
- state.enableChatUI = false;
- state.isUISettingsLoading = false;
- state.serverRootPath = undefined;
- mockReplace.mockClear();
- });
-
- it("renders the chat page when enable_chat_ui is on", () => {
- state.enableChatUI = true;
- render( );
- expect(screen.getByTestId("chat-page")).toBeInTheDocument();
- expect(mockReplace).not.toHaveBeenCalled();
- });
-
- it("redirects non-admins to the dashboard when enable_chat_ui is off", () => {
- state.enableChatUI = false;
- state.userRole = "Internal User";
- render( );
- expect(screen.queryByTestId("chat-page")).not.toBeInTheDocument();
- expect(mockReplace).toHaveBeenCalledWith("/ui/");
- });
-
- it("redirects admins to the dashboard when enable_chat_ui is off", () => {
- state.enableChatUI = false;
- state.userRole = "Admin";
- render( );
- expect(screen.queryByTestId("chat-page")).not.toBeInTheDocument();
- expect(mockReplace).toHaveBeenCalledWith("/ui/");
- });
-
- it("renders nothing while UI settings are still loading", () => {
- state.isUISettingsLoading = true;
- render( );
- expect(screen.queryByTestId("chat-page")).not.toBeInTheDocument();
- expect(mockReplace).not.toHaveBeenCalled();
- });
-
- it("respects a custom server_root_path when redirecting", () => {
- state.enableChatUI = false;
- state.userRole = "Internal User";
- state.serverRootPath = "/api/v1";
- render( );
- expect(mockReplace).toHaveBeenCalledWith("/api/v1/ui/");
- });
-});
diff --git a/ui/litellm-dashboard/src/app/chat/page.tsx b/ui/litellm-dashboard/src/app/chat/page.tsx
index f1053bec78da..57bb740fbde1 100644
--- a/ui/litellm-dashboard/src/app/chat/page.tsx
+++ b/ui/litellm-dashboard/src/app/chat/page.tsx
@@ -1,46 +1,590 @@
"use client";
-import { Suspense, useEffect } from "react";
+import React, { useCallback, useEffect, useRef, useState, useLayoutEffect } from "react";
+import { Plus, ChevronDown, Check, X } from "lucide-react";
+import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover";
+import { Skeleton } from "@/components/ui/skeleton";
+import { ScrollArea } from "@/components/ui/scroll-area";
+import { Input } from "@/components/ui/input";
+import { Button } from "@/components/ui/button";
+import MessageManager from "@/components/molecules/message_manager";
import { useRouter } from "next/navigation";
-import useAuthorized from "@/app/(dashboard)/hooks/useAuthorized";
-import { useUIConfig } from "@/app/(dashboard)/hooks/uiConfig/useUIConfig";
-import { useUISettings } from "@/app/(dashboard)/hooks/uiSettings/useUISettings";
-import ChatPage from "@/components/chat/ChatPage";
-
-// ChatPage uses useSearchParams() which requires a Suspense boundary for static export.
-const ChatPageContent = () => {
- const { accessToken, userRole, userId, userEmail } = useAuthorized();
- const { data: uiSettings, isLoading: isUISettingsLoading } = useUISettings();
- const { data: uiConfig } = useUIConfig();
+import { useChatShell } from "@/contexts/ChatShellContext";
+import { CHAT_ROUTES } from "@/components/chat/ChatShell";
+import ChatMessages from "@/components/chat/ChatMessages";
+import MCPConnectPicker from "@/components/chat/MCPConnectPicker";
+import { fetchAvailableModels } from "@/components/llm_calls/fetch_models";
+import { makeOpenAIResponsesRequest } from "@/components/llm_calls/responses_api";
+import type { MCPEvent } from "@/components/chat/types";
+import { getProviderLogoAndName } from "@/components/provider_info_helpers";
+
+const SUGGESTIONS = ["Write", "Learn", "Code", "Brainstorm"];
+const LOCALSTORAGE_MODEL_KEY = "litellm_chat_selected_model";
+
+function getGreeting(): string {
+ const h = new Date().getHours();
+ if (h >= 5 && h < 12) return "Good morning";
+ if (h >= 12 && h < 17) return "Good afternoon";
+ return "Good evening";
+}
+
+// Extract provider from model name for logo lookup.
+// Handles prefixed models ("groq/llama-3"), and detects well-known providers by keyword.
+function getProviderFromModelName(modelName: string): string {
+ if (!modelName) return "";
+ const lower = modelName.toLowerCase();
+ const slash = lower.indexOf("/");
+ if (slash > 0) return lower.slice(0, slash);
+ // Keyword matching — order matters (more specific first)
+ if (lower.includes("claude")) return "anthropic";
+ if (lower.includes("gemini")) return "gemini";
+ if (lower.includes("gpt") || lower.includes("chatgpt") || /^o[0-9]/.test(lower)) return "openai";
+ if (lower.includes("mistral") || lower.includes("codestral")) return "mistral";
+ if (lower.includes("llama")) return "meta_llama";
+ if (lower.includes("deepseek")) return "deepseek";
+ if (lower.includes("grok")) return "xai";
+ if (lower.includes("command")) return "cohere";
+ if (lower.includes("nova") || lower.includes("titan")) return "bedrock";
+ return "";
+}
+
+export default function ChatConversationPage() {
const router = useRouter();
+ const {
+ accessToken,
+ userId,
+ userEmail,
+ selectedMCPServers,
+ setSelectedMCPServers,
+ activeConversationId,
+ activeConversation,
+ storageUnavailable,
+ staleId,
+ createConversation,
+ appendMessage,
+ updateLastAssistantMessage,
+ truncateFromMessage,
+ } = useChatShell();
+ const hadActiveConversationOnMountRef = useRef(activeConversationId !== null);
+
+ const [selectedModel, setSelectedModel] = useState(null);
+ const [models, setModels] = useState([]);
+ const [isLoadingModels, setIsLoadingModels] = useState(true);
+ const [modelSelectorOpen, setModelSelectorOpen] = useState(false);
+ const [modelSearchText, setModelSearchText] = useState("");
+
+ const [responsesSessionId, setResponsesSessionId] = useState(null);
+ const [prevConversationIdForSessionReset, setPrevConversationIdForSessionReset] = useState(activeConversationId);
+ const [isStreaming, setIsStreaming] = useState(false);
+ const [inputText, setInputText] = useState("");
+ const [mcpPopoverOpen, setMcpPopoverOpen] = useState(false);
+ const [storageBannerDismissed, setStorageBannerDismissed] = useState(false);
- const uiRoot =
- uiConfig?.server_root_path && uiConfig.server_root_path !== "/"
- ? uiConfig.server_root_path.replace(/\/+$/, "")
- : "";
- const chatEnabled = Boolean(uiSettings?.values?.enable_chat_ui);
- const blocked = !isUISettingsLoading && !chatEnabled;
+ const abortControllerRef = useRef(null);
+ const textareaRef = useRef(null);
+ const messagesScrollRef = useRef(null);
+ const [showScrollButton, setShowScrollButton] = useState(false);
+ const streamScrollLock = useRef(null);
useEffect(() => {
- if (blocked) router.replace(`${uiRoot}/ui/`);
- }, [blocked, uiRoot, router]);
+ if (staleId) router.replace(CHAT_ROUTES.chats);
+ }, [staleId, router]);
- if (isUISettingsLoading || blocked) return null;
+ // Load models
+ useEffect(() => {
+ if (!accessToken) return;
+ fetchAvailableModels(accessToken)
+ .then((data) => {
+ const names = (data || []).map((m: { model_group?: string }) => m.model_group ?? "").filter(Boolean);
+ setModels(names);
+ try {
+ const saved = localStorage.getItem(LOCALSTORAGE_MODEL_KEY);
+ if (saved && names.includes(saved)) {
+ setSelectedModel(saved);
+ return;
+ }
+ } catch {
+ // ignore parse errors
+ }
+ if (names.length > 0) {
+ setSelectedModel(names[0]);
+ localStorage.setItem(LOCALSTORAGE_MODEL_KEY, names[0]);
+ }
+ })
+ .catch(() => MessageManager.error("Could not load models"))
+ .finally(() => setIsLoadingModels(false));
+ }, [accessToken]);
- return (
-
+ // Reset the responses session when switching between conversations so that
+ // previous_response_id from conversation A is never sent for conversation B.
+ if (activeConversationId !== prevConversationIdForSessionReset) {
+ setPrevConversationIdForSessionReset(activeConversationId);
+ setResponsesSessionId(null);
+ }
+
+ const selectModel = useCallback((model: string) => {
+ setSelectedModel(model);
+ localStorage.setItem(LOCALSTORAGE_MODEL_KEY, model);
+ setModelSelectorOpen(false);
+ setModelSearchText("");
+ }, []);
+
+ const handleSend = useCallback(
+ async (text: string, historyOverride?: Array<{ role: "user" | "assistant"; content: string }>) => {
+ const trimmed = text.trim();
+ if (!trimmed || !selectedModel || isStreaming) return;
+ const model = selectedModel;
+ setInputText("");
+
+ let convId = activeConversationId;
+ if (!convId) {
+ convId = createConversation(model);
+ setResponsesSessionId(null); // new conversation starts a fresh session
+ router.push(`${CHAT_ROUTES.chats}?id=${convId}`);
+ }
+
+ appendMessage(convId, { role: "user", content: trimmed });
+ appendMessage(convId, { role: "assistant", content: "" });
+
+ setIsStreaming(true);
+ abortControllerRef.current = new AbortController();
+
+ // When historyOverride is set (edit / retry), the existing server-side
+ // session chain covers messages that were just truncated and is no longer
+ // valid for the rewritten history. Eagerly clear the session so that a
+ // failed/aborted edit does not leave a stale session ID that contaminates
+ // the next regular send.
+ if (historyOverride) {
+ setResponsesSessionId(null);
+ }
+
+ // On a normal continuation turn with an active session, the Responses API
+ // already holds the prior context server-side, so we only pass the new
+ // user message (sending the full history would double-count it).
+ //
+ // On the very first turn (no session yet), we send the full history.
+ const previousResponseId = historyOverride ? null : responsesSessionId;
+
+ const history: Array<{ role: "user" | "assistant"; content: string }> = historyOverride
+ ? [...historyOverride, { role: "user" as const, content: trimmed }]
+ : previousResponseId
+ ? [{ role: "user" as const, content: trimmed }]
+ : [
+ // Explicitly filter to only user/assistant roles — tool messages
+ // lack a required tool_call_id and would cause API errors.
+ ...(activeConversation?.messages ?? [])
+ .filter(
+ (m): m is typeof m & { role: "user" | "assistant" } => m.role === "user" || m.role === "assistant",
+ )
+ .map((m) => ({ role: m.role, content: m.content })),
+ { role: "user" as const, content: trimmed },
+ ];
+
+ let accumulatedContent = "";
+ let accumulatedReasoning = "";
+ // MCP events accumulated locally so we can persist them to the message
+ // without relying on component state (which would cause stale closures).
+ const accumulatedMCPEvents: MCPEvent[] = [];
+ // Track clean completion so partial events are not shown on error/abort.
+ let streamCompletedCleanly = false;
+
+ try {
+ await makeOpenAIResponsesRequest(
+ history,
+ (_role: string, chunk: string) => {
+ accumulatedContent += chunk;
+ updateLastAssistantMessage(convId!, { content: accumulatedContent });
+ },
+ model,
+ accessToken,
+ undefined, // tags
+ abortControllerRef.current.signal,
+ (rc: string) => {
+ accumulatedReasoning += rc;
+ updateLastAssistantMessage(convId!, { reasoningContent: accumulatedReasoning });
+ },
+ undefined,
+ undefined,
+ undefined,
+ undefined,
+ undefined,
+ undefined,
+ selectedMCPServers.length > 0 ? selectedMCPServers : undefined,
+ previousResponseId,
+ (id: string) => setResponsesSessionId(id),
+ (event: MCPEvent) => {
+ // Accumulate locally only — persisted once in finally to avoid
+ // one full localStorage write per MCP event during streaming.
+ accumulatedMCPEvents.push(event);
+ },
+ );
+ streamCompletedCleanly = true;
+ } catch (err: unknown) {
+ if (err instanceof Error && err.name === "AbortError") {
+ updateLastAssistantMessage(convId!, {
+ content: accumulatedContent + " [stopped]",
+ });
+ } else {
+ updateLastAssistantMessage(convId!, {
+ content: "[Something went wrong. The partial response has been saved.]",
+ });
+ }
+ } finally {
+ // Only persist MCP events on clean completion — partial events from an
+ // aborted or errored turn would show incomplete tool calls to the user.
+ if (accumulatedMCPEvents.length > 0 && streamCompletedCleanly) {
+ updateLastAssistantMessage(convId!, { mcpEvents: accumulatedMCPEvents });
+ }
+ setIsStreaming(false);
+ abortControllerRef.current = null;
+ }
+ },
+ [
+ activeConversationId,
+ activeConversation,
+ selectedModel,
+ selectedMCPServers,
+ accessToken,
+ createConversation,
+ appendMessage,
+ updateLastAssistantMessage,
+ router,
+ isStreaming,
+ responsesSessionId,
+ ],
);
-};
-const ChatPageRoute = () => (
-
-
-
-);
+ const handleStop = useCallback(() => {
+ abortControllerRef.current?.abort();
+ }, []);
+
+ const handleEditAndResend = useCallback(
+ (messageId: string, newContent: string) => {
+ if (!activeConversationId || isStreaming) return;
+ // Compute the truncated history synchronously before the async state update lands,
+ // so handleSend receives the correct pre-edit context rather than the stale closure value.
+ const msgs = activeConversation?.messages ?? [];
+ const idx = msgs.findIndex((m) => m.id === messageId);
+ const priorMessages = (idx === -1 ? msgs : msgs.slice(0, idx))
+ .filter((m) => m.role === "user" || m.role === "assistant")
+ .map((m) => ({ role: m.role as "user" | "assistant", content: m.content }));
+ truncateFromMessage(activeConversationId, messageId);
+ handleSend(newContent, priorMessages);
+ },
+ [activeConversationId, isStreaming, activeConversation, truncateFromMessage, handleSend],
+ );
+
+ const handleKeyDown = (e: React.KeyboardEvent) => {
+ if (e.key === "Enter" && !e.shiftKey) {
+ e.preventDefault();
+ handleSend(inputText);
+ }
+ };
+
+ // Auto-resize textarea
+ useEffect(() => {
+ const ta = textareaRef.current;
+ if (!ta) return;
+ ta.style.height = "auto";
+ ta.style.height = `${Math.min(ta.scrollHeight, 180)}px`;
+ }, [inputText]);
-export default ChatPageRoute;
+ // Track scroll position to show/hide scroll-to-bottom button
+ useEffect(() => {
+ const el = messagesScrollRef.current;
+ if (!el) return;
+ const onScroll = () => {
+ const distFromBottom = el.scrollHeight - el.scrollTop - el.clientHeight;
+ setShowScrollButton(distFromBottom > 120);
+ if (streamScrollLock.current !== null) {
+ streamScrollLock.current = el.scrollTop; // track user-initiated scroll
+ }
+ };
+ el.addEventListener("scroll", onScroll, { passive: true });
+ return () => el.removeEventListener("scroll", onScroll);
+ }, [activeConversation]);
+
+ // Start/stop the scroll lock when streaming begins/ends
+ useEffect(() => {
+ const el = messagesScrollRef.current;
+ if (isStreaming) {
+ streamScrollLock.current = el?.scrollTop ?? 0;
+ } else {
+ streamScrollLock.current = null;
+ }
+ }, [isStreaming]);
+
+ // After every render during streaming, restore the locked scroll position
+ useLayoutEffect(() => {
+ if (streamScrollLock.current === null) return;
+ const el = messagesScrollRef.current;
+ if (!el) return;
+ el.scrollTop = streamScrollLock.current;
+ });
+
+ // Scroll to bottom only when message COUNT increases (new message added)
+ const prevMsgCountRef = useRef(0);
+ useLayoutEffect(() => {
+ const count = activeConversation?.messages?.length ?? 0;
+ const prev = prevMsgCountRef.current;
+ prevMsgCountRef.current = count;
+ if (count > prev) {
+ const el = messagesScrollRef.current;
+ if (el) el.scrollTop = el.scrollHeight;
+ }
+ }, [activeConversation?.messages]);
+
+ const showBlankState = !activeConversation || activeConversation.messages.length === 0;
+ const displayName = userEmail?.split("@")[0] ?? userId ?? "";
+ const greeting = displayName ? `${getGreeting()}, ${displayName}` : getGreeting();
+
+ // Filtered models: selected one floats to the top, then alphabetical
+ const filteredModels = (
+ modelSearchText ? models.filter((m) => m.toLowerCase().includes(modelSearchText.toLowerCase())) : models
+ ).sort((a, b) => {
+ if (a === selectedModel) return -1;
+ if (b === selectedModel) return 1;
+ return 0;
+ });
+
+ const modelSelectorContent = (
+
+
+ setModelSearchText(e.target.value)}
+ placeholder="Search models..."
+ className="h-8 text-[13px]"
+ />
+
+
+ {filteredModels.map((m) => {
+ const checked = m === selectedModel;
+ const provider = getProviderFromModelName(m);
+ const { logo } = provider ? getProviderLogoAndName(provider) : { logo: "" };
+ return (
+ selectModel(m)}
+ className={`h-auto w-full justify-start gap-2 rounded px-3 py-[7px] font-normal ${checked ? "bg-accent" : ""}`}
+ >
+ {logo ? (
+ {
+ (e.currentTarget as HTMLImageElement).style.display = "none";
+ }}
+ />
+ ) : (
+
+ )}
+
+ {m}
+
+ {checked && }
+
+ );
+ })}
+
+
+ );
+
+ const modelSelectorTrigger = isLoadingModels ? (
+
+ ) : (
+ {
+ setModelSelectorOpen(open);
+ if (!open) setModelSearchText("");
+ }}
+ >
+
+
+ {selectedModel ? (
+ <>
+ {(() => {
+ const provider = getProviderFromModelName(selectedModel);
+ const { logo } = provider ? getProviderLogoAndName(provider) : { logo: "" };
+ return logo ? (
+ {
+ (e.currentTarget as HTMLImageElement).style.display = "none";
+ }}
+ />
+ ) : null;
+ })()}
+ {selectedModel}
+ >
+ ) : (
+ Select model
+ )}
+
+
+
+
+ {modelSelectorContent}
+
+
+ );
+
+ const inputBar = (inConversation: boolean) => (
+
+ );
+
+ return (
+ <>
+ {storageUnavailable && !storageBannerDismissed && (
+
+ Chat history won't be saved in this browser session
+ setStorageBannerDismissed(true)}
+ className="text-amber-800 hover:bg-amber-100 hover:text-amber-800"
+ >
+
+
+
+ )}
+
+
+ {showBlankState ? (
+
+
+ {greeting}
+
+
+
+ Chat with 100+ LLMs + MCP tools; authenticate once, use them here.{" "}
+ router.push(CHAT_ROUTES.integrations)}
+ className="h-auto p-0 text-sm font-medium"
+ >
+ Open Integrations ->
+
+
+
+
{inputBar(false)}
+
+
+ {SUGGESTIONS.map((s) => (
+ setInputText(s + ": ")}
+ className="rounded-full px-4 text-muted-foreground"
+ >
+ {s}
+
+ ))}
+
+
+ ) : (
+
+
+
+
+ {showScrollButton && (
+
{
+ const el = messagesScrollRef.current;
+ if (el) {
+ el.scrollTo({ top: el.scrollHeight, behavior: "smooth" });
+ if (streamScrollLock.current !== null) {
+ streamScrollLock.current = el.scrollHeight;
+ }
+ }
+ }}
+ className="absolute bottom-[100px] left-1/2 -translate-x-1/2 z-10 rounded-full border bg-background/75 text-muted-foreground shadow-sm backdrop-blur-md hover:bg-background/95 hover:text-muted-foreground"
+ aria-label="Scroll to bottom"
+ >
+
+
+ )}
+
+
{inputBar(true)}
+
+ )}
+
+ >
+ );
+}
diff --git a/ui/litellm-dashboard/src/app/chat/usage/page.tsx b/ui/litellm-dashboard/src/app/chat/usage/page.tsx
new file mode 100644
index 000000000000..113a094ef401
--- /dev/null
+++ b/ui/litellm-dashboard/src/app/chat/usage/page.tsx
@@ -0,0 +1,14 @@
+"use client";
+
+import { useChatShell } from "@/contexts/ChatShellContext";
+import UsagePanel from "@/components/chat/UsagePanel";
+
+export default function UsagePage() {
+ const { accessToken, userId } = useChatShell();
+
+ return (
+
+
+
+ );
+}
diff --git a/ui/litellm-dashboard/src/components/Navbar/ViewSwitcher.test.tsx b/ui/litellm-dashboard/src/components/Navbar/ViewSwitcher.test.tsx
index a13af8b2bef4..bdbf74cdf7d3 100644
--- a/ui/litellm-dashboard/src/components/Navbar/ViewSwitcher.test.tsx
+++ b/ui/litellm-dashboard/src/components/Navbar/ViewSwitcher.test.tsx
@@ -2,13 +2,14 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { act, fireEvent, render, screen, waitFor } from "@testing-library/react";
import ViewSwitcher from "./ViewSwitcher";
-const { mockUsePluginMode, mockUseUISettings, state } = vi.hoisted(() => {
+const { mockUsePluginMode, mockUseUISettings, mockUsePathname, state } = vi.hoisted(() => {
const state = {
mode: "ai-gateway" as string,
setMode: vi.fn(),
plugins: [] as { name: string; display_name: string; url: string }[],
activePlugin: null as { name: string; display_name: string; url: string } | null,
enableChatUI: false,
+ pathname: "/ui/",
};
return {
state,
@@ -19,11 +20,13 @@ const { mockUsePluginMode, mockUseUISettings, state } = vi.hoisted(() => {
activePlugin: state.activePlugin,
})),
mockUseUISettings: vi.fn(() => ({ data: { values: { enable_chat_ui: state.enableChatUI } } })),
+ mockUsePathname: vi.fn(() => state.pathname),
};
});
vi.mock("@/contexts/PluginModeContext", () => ({ usePluginMode: mockUsePluginMode }));
vi.mock("@/app/(dashboard)/hooks/uiSettings/useUISettings", () => ({ useUISettings: mockUseUISettings }));
+vi.mock("next/navigation", () => ({ usePathname: mockUsePathname }));
// Deterministic hrefs so navigation assertions don't depend on server_root_path.
vi.mock("@/utils/migratedPages", () => ({ migratedHref: (seg: string) => `/ui/${seg}` }));
@@ -42,6 +45,7 @@ describe("ViewSwitcher", () => {
state.mode = "ai-gateway";
state.plugins = [];
state.enableChatUI = false;
+ state.pathname = "/ui/";
state.setMode.mockClear();
});
@@ -100,6 +104,23 @@ describe("ViewSwitcher", () => {
expect(state.setMode).not.toHaveBeenCalled();
});
+ it("navigates back to the dashboard when a mode entry is picked from the chat route", async () => {
+ state.enableChatUI = true;
+ state.pathname = "/ui/chat";
+ state.plugins = [{ name: "litellm-platform-plugin", display_name: "Chat UI", url: "http://localhost:3300" }];
+ render( );
+
+ act(() => {
+ fireEvent.click(screen.getByRole("button"));
+ });
+ await waitFor(() => expect(screen.getByText("AI Gateway")).toBeInTheDocument());
+ act(() => {
+ fireEvent.click(screen.getByText("AI Gateway"));
+ });
+ expect(state.setMode).toHaveBeenCalledWith("ai-gateway");
+ expect(assignSpy).toHaveBeenCalledWith("/ui/");
+ });
+
it("hides the Chat entry from everyone when disabled", async () => {
state.enableChatUI = false;
state.plugins = [{ name: "obs", display_name: "Observability", url: "http://localhost:9000" }];
diff --git a/ui/litellm-dashboard/src/components/Navbar/ViewSwitcher.tsx b/ui/litellm-dashboard/src/components/Navbar/ViewSwitcher.tsx
index a64b00f885c3..834966aca351 100644
--- a/ui/litellm-dashboard/src/components/Navbar/ViewSwitcher.tsx
+++ b/ui/litellm-dashboard/src/components/Navbar/ViewSwitcher.tsx
@@ -1,4 +1,5 @@
import React from "react";
+import { usePathname } from "next/navigation";
import { Dropdown } from "antd";
import { AppstoreOutlined, CheckOutlined, DownOutlined } from "@ant-design/icons";
import type { MenuProps } from "antd";
@@ -12,12 +13,17 @@ const CHAT = "chat";
export default function ViewSwitcher() {
const { mode, setMode, plugins } = usePluginMode();
const { data: uiSettings } = useUISettings();
+ const pathname = usePathname();
const chatEnabled = Boolean(uiSettings?.values?.enable_chat_ui);
if (plugins.length === 0 && !chatEnabled) return null;
- const activeLabel = plugins.find((p) => p.name === mode)?.display_name ?? "AI Gateway";
+ const chatHref = migratedHref(CHAT);
+ const normalizedPathname = (pathname ?? "").replace(/\/+$/, "");
+ const isChatRoute = chatEnabled && (normalizedPathname === chatHref || normalizedPathname.startsWith(`${chatHref}/`));
+
+ const activeLabel = isChatRoute ? "Chat" : plugins.find((p) => p.name === mode)?.display_name ?? "AI Gateway";
const modeEntries = [
{ key: GATEWAY, label: "AI Gateway" },
@@ -30,7 +36,7 @@ export default function ViewSwitcher() {
label: (
{e.label}
- {e.key === mode && }
+ {!isChatRoute && e.key === mode && }
),
})),
@@ -41,6 +47,7 @@ export default function ViewSwitcher() {
label: (
Chat
+ {isChatRoute && }
),
},
@@ -54,10 +61,15 @@ export default function ViewSwitcher() {
return;
}
setMode(key);
+ // The chat route lives outside the dashboard SPA shell that reacts to `mode`,
+ // so switching modes from there needs a real navigation, not just state.
+ if (isChatRoute) {
+ window.location.assign(migratedHref(""));
+ }
};
return (
-
+
` sidebar nav item went through five different ad-hoc color attempts in one session (invisible `bg-accent`, a barely-visible shadow, invisible `bg-primary/10`, a `border-l-2` that clipped at the border-radius corner) before landing on the actual fix: use `bg-sidebar-accent`, a token that already existed and was never checked. Every rule below exists to stop that specific failure mode: **reaching for a plausible-looking Tailwind class instead of checking what the design system already provides.**
+
+---
+
+## Decision tree: "I need a new UI element"
+
+1. **Does `design.md` already show this exact pattern?** Copy it verbatim. Don't restyle it "to match" something else you're looking at — if it needs to look different, that's a `design.md` update, not a one-off deviation.
+2. **Is it a clickable thing?** It's a `Button` (some variant/size), full stop. Never a raw ``. If no variant looks right, that's a sign to re-read the Button section in `design.md`, not to hand-roll classes on a ``.
+3. **Does it need a color for "selected" / "active" / "hover"?** Before picking a class:
+ - Read the actual values in `src/app/globals.css` for the classes you're about to use. Don't assume `accent` ≠ `secondary` ≠ `muted` — in this theme they're identical. Confirm contrast against the _actual container_ background, not the general Tailwind palette in your head.
+ - If the element lives inside the sidebar, use the `sidebar-*` token family (`bg-sidebar`, `bg-sidebar-accent`, `text-sidebar-accent-foreground`), not the generic tokens.
+4. **Is the shadcn primitive you want to use not in `src/components/ui/`?** Check the "Known gaps" list in `design.md` first — if it's `Card`, `Textarea`, `sonner`, or a `Sidebar` block, use the documented substitute. If it's something else entirely missing, stop and flag it; don't hand-write a parallel implementation inside a chat component.
+5. **Still unsure?** Grep this directory and `src/app/(dashboard)/` for an existing instance of the same UI idea (e.g. "how does the rest of the dashboard render a data table") before inventing a new pattern for chat specifically. The chat UI should look like the rest of the app, not like its own product.
+
+## Decision tree: "I'm fixing a bug in an existing component"
+
+1. Reproduce it first — actually load the page, don't infer from reading code.
+2. If the bug is visual (wrong color, wrong spacing, misaligned element), check whether the _component_ is even the right primitive before touching classes. A hand-rolled `` with a color bug is often better fixed by replacing it with `Button` than by fixing the color, because the color bug is usually a symptom of not having the component's built-in state handling.
+3. Fix the root cause, not the symptom you can see. "The active tab has an invisible highlight" was fixed correctly only on the _second_ attempt — the first fix (a subtle shadow) treated the symptom (not distinct enough) without asking why `bg-accent` had no contrast in the first place.
+4. After the fix, look for the same bug pattern elsewhere in the same file and sibling files. If one nav item had a contrast bug, check whether the pattern is reused elsewhere before considering it done.
+
+## When it's OK to deviate from `design.md`
+
+- The pattern truly doesn't exist yet in this codebase and adding the missing shadcn piece (e.g. a real `Sidebar` block, `Textarea`, `sonner`) is out of scope for the current change. Use the documented substitute in "Known gaps," and don't block your task on it — but don't invent a _different_ substitute than the one written down either.
+- You're the one updating `design.md` itself because the pattern was wrong (like the `bg-secondary`-sidebar-with-`bg-accent`-active-item combination that shipped with zero contrast). In that case, update `design.md` in the same change, with a note on what was wrong and why the new pattern is correct — don't leave the stale guidance in place for the next agent to copy.
+
+Never deviate silently. If you improvise, the next agent (or you, in six months) will copy the improvisation as if it were the standard.
+
+## Pre-commit checklist
+
+Run through this before considering a chat UI change done:
+
+- [ ] Every clickable element is a `Button` variant, not a raw `` — search your diff for `` run on anything you hand-edited (don't let formatting drift force a second review pass).
+- [ ] Actually opened the page in a browser and looked at the change — a design-system violation that "should" render correctly per the code is still a bug if it doesn't.
+- [ ] If you changed or discovered a gap in `design.md`, `design.md` was updated in the same commit, not left for later.
diff --git a/ui/litellm-dashboard/src/components/chat/ChatMessages.tsx b/ui/litellm-dashboard/src/components/chat/ChatMessages.tsx
index f29adcfb6a51..b9f4fb7c3bc1 100644
--- a/ui/litellm-dashboard/src/components/chat/ChatMessages.tsx
+++ b/ui/litellm-dashboard/src/components/chat/ChatMessages.tsx
@@ -1,7 +1,9 @@
"use client";
-import { ToolOutlined, CopyOutlined, CheckOutlined, EditOutlined } from "@ant-design/icons";
-import { Collapse, Tooltip } from "antd";
+import { Wrench, Copy, Check, Pencil } from "lucide-react";
+import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from "@/components/ui/tooltip";
+import { Collapsible, CollapsibleContent, CollapsibleTrigger } from "@/components/ui/collapsible";
+import { Button } from "@/components/ui/button";
import React, { useEffect, useRef, useState } from "react";
import ReactMarkdown from "react-markdown";
import remarkGfm from "remark-gfm";
@@ -11,9 +13,6 @@ import ReasoningContent from "@/components/chat_ui/ReasoningContent";
import MCPEventsDisplay from "@/components/chat_ui/MCPEventsDisplay";
import { ChatMessage } from "./types";
-const { Panel } = Collapse;
-
-// Keys whose values must be redacted in tool args display
const REDACTED_KEY_PATTERNS = /token|key|secret|password|auth/i;
function redactSensitiveValues(obj: Record): Record {
@@ -43,8 +42,6 @@ function formatTimestamp(ts: number): string {
return `${hh}:${mm}`;
}
-// Shared markdown code renderer matching ReasoningContent style.
-// react-markdown v9 removed the `inline` prop; detect fenced blocks via language className.
function MarkdownCodeRenderer({
node,
className,
@@ -63,14 +60,12 @@ function MarkdownCodeRenderer({
{String(children).replace(/\n$/, "")}
) : (
-
+
{children}
);
}
-// ------- Sub-components -------
-
interface UserBubbleProps {
message: ChatMessage;
onEdit?: (messageId: string, newContent: string) => void;
@@ -90,7 +85,6 @@ function UserBubble({ message, onEdit, isStreaming }: UserBubbleProps) {
}
}, [editing]);
- // Auto-resize textarea
useEffect(() => {
const ta = textareaRef.current;
if (!ta) return;
@@ -119,79 +113,29 @@ function UserBubble({ message, onEdit, isStreaming }: UserBubbleProps) {
if (editing) {
return (
-
-
+
@@ -200,59 +144,38 @@ function UserBubble({ message, onEdit, isStreaming }: UserBubbleProps) {
return (
setHovered(true)}
onMouseLeave={() => setHovered(false)}
>
-
- {/* Edit button — appears on hover, to the left of the bubble */}
+
{hovered && !isStreaming && onEdit && (
-
- {
- setEditValue(message.content);
- setEditing(true);
- }}
- style={{
- background: "none",
- border: "none",
- cursor: "pointer",
- padding: "4px 6px",
- borderRadius: 5,
- color: "#9ca3af",
- fontSize: 13,
- flexShrink: 0,
- display: "flex",
- alignItems: "center",
- transition: "color 0.15s",
- }}
- onMouseEnter={(e) => {
- (e.currentTarget as HTMLButtonElement).style.color = "#6b7280";
- }}
- onMouseLeave={(e) => {
- (e.currentTarget as HTMLButtonElement).style.color = "#9ca3af";
- }}
- >
-
-
-
+
+
+
+ {
+ setEditValue(message.content);
+ setEditing(true);
+ }}
+ className="text-muted-foreground hover:text-foreground shrink-0"
+ >
+
+
+
+
+ Edit message
+
+
+
)}
-
-
{formatTimestamp(message.timestamp)}
+
{formatTimestamp(message.timestamp)}
);
}
@@ -262,13 +185,10 @@ interface AssistantBubbleProps {
isLastMessage: boolean;
isStreaming: boolean;
isTypingIndicator: boolean;
- /** MCP events stored on the message — rendered inline below the response. */
mcpEvents?: ChatMessage["mcpEvents"];
}
function AssistantBubble({ message, isLastMessage, isStreaming, isTypingIndicator, mcpEvents }: AssistantBubbleProps) {
- // ReasoningContent manages its own expanded state; we bump this key to
- // remount it (collapsed by default) when streaming finishes.
const [reasoningKey, setReasoningKey] = useState(0);
const prevStreamingRef = useRef
(isStreaming);
@@ -280,20 +200,18 @@ function AssistantBubble({ message, isLastMessage, isStreaming, isTypingIndicato
}, [isStreaming]);
const showReasoningPlaceholder = isLastMessage && isStreaming && !message.reasoningContent;
-
const showReasoning = !!message.reasoningContent || showReasoningPlaceholder;
if (isTypingIndicator) {
return (
-
-
+
);
}
- // Split content at trailing "[stopped]"
let mainContent = message.content;
let stoppedSuffix = false;
if (mainContent.endsWith("[stopped]")) {
@@ -302,7 +220,7 @@ function AssistantBubble({ message, isLastMessage, isStreaming, isTypingIndicato
}
return (
-
+
{showReasoning &&
(showReasoningPlaceholder ? (
@@ -310,14 +228,7 @@ function AssistantBubble({ message, isLastMessage, isStreaming, isTypingIndicato
))}
-
+
{mainContent}
- {stoppedSuffix && [stopped] }
+ {stoppedSuffix && [stopped] }
{mcpEvents && mcpEvents.length > 0 && (
-
+
)}
@@ -349,39 +260,28 @@ function CopyButton({ text }: { text: string }) {
setCopied(true);
setTimeout(() => setCopied(false), 2000);
})
- .catch(() => {
- // clipboard not available (non-HTTPS or permission denied) — silently no-op
- });
+ .catch(() => {});
};
return (
-
-
- {
- if (!copied) (e.currentTarget as HTMLButtonElement).style.color = "#6b7280";
- }}
- onMouseLeave={(e) => {
- if (!copied) (e.currentTarget as HTMLButtonElement).style.color = "#9ca3af";
- }}
- >
- {copied ? : }
-
-
+
+
+
+
+
+ {copied ? : }
+
+
+
+ {copied ? "Copied!" : "Copy"}
+
+
+
);
}
@@ -398,21 +298,8 @@ function ThinkingPlaceholder() {
animation: thinking-pulse 1.4s ease-in-out infinite;
}
`}
-
-
Thinking...
+
+ Thinking...
>
);
@@ -430,7 +317,7 @@ function TypingDots() {
width: 7px;
height: 7px;
border-radius: 50%;
- background-color: #9ca3af;
+ background-color: var(--color-muted-foreground);
animation: chat-typing-bounce 1.2s ease-in-out infinite;
}
.chat-dot:nth-child(2) { animation-delay: 0.2s; }
@@ -449,96 +336,43 @@ interface ToolCardProps {
function ToolCard({ message }: ToolCardProps) {
const redactedArgs = message.toolArgs ? redactSensitiveValues(message.toolArgs) : undefined;
+ const [open, setOpen] = useState(false);
return (
-
-
-
-
- {message.toolName ?? "Tool call"}
-
- }
- key="tool"
- >
+
+
+
+
+ {message.toolName ?? "Tool call"}
+
+
{redactedArgs !== undefined && (
-
-
+
+
Arguments
-
+
{JSON.stringify(redactedArgs, null, 2)}
)}
-
{message.toolResult && (
-
+
Result
-
)}
-
-
-
{formatTimestamp(message.timestamp)}
+
+
+
{formatTimestamp(message.timestamp)}
);
}
-// ------- Main component -------
-
interface Props {
messages: ChatMessage[];
isStreaming: boolean;
@@ -546,15 +380,12 @@ interface Props {
}
const ChatMessages: React.FC
= ({ messages, isStreaming, onEditMessage }) => {
- // Scrolling is managed by ChatPage.tsx (scroll lock during streaming,
- // scroll-to-bottom on new message). No auto-scroll here.
-
const lastIndex = messages.length - 1;
const lastMsg = messages[lastIndex] ?? null;
const isTypingIndicator = isStreaming && lastMsg !== null && lastMsg.role === "assistant" && lastMsg.content === "";
return (
-
+
{messages.map((msg, idx) => {
const isLastMessage = idx === lastIndex;
@@ -566,7 +397,6 @@ const ChatMessages: React.FC
= ({ messages, isStreaming, onEditMessage })
return ;
}
- // assistant
return (
= 5 && h < 12) return "Good morning";
- if (h >= 12 && h < 17) return "Good afternoon";
- return "Good evening";
-}
-
-// Build the chat UI URL respecting server root path (e.g. /api/v1/ui/chat)
-function getChatUrl(root: string, id?: string): string {
- return id ? `${root}/ui/chat?id=${id}` : `${root}/ui/chat`;
-}
-
-// Build the dashboard root URL (e.g. /api/v1/ui/)
-function getDashboardUrl(root: string): string {
- return `${root}/ui/`;
-}
-
-// Extract provider from model name for logo lookup.
-// Handles prefixed models ("groq/llama-3"), and detects well-known providers by keyword.
-function getProviderFromModelName(modelName: string): string {
- if (!modelName) return "";
- const lower = modelName.toLowerCase();
- const slash = lower.indexOf("/");
- if (slash > 0) return lower.slice(0, slash);
- // Keyword matching — order matters (more specific first)
- if (lower.includes("claude")) return "anthropic";
- if (lower.includes("gemini")) return "gemini";
- if (lower.includes("gpt") || lower.includes("chatgpt") || /^o[0-9]/.test(lower)) return "openai";
- if (lower.includes("mistral") || lower.includes("codestral")) return "mistral";
- if (lower.includes("llama")) return "meta_llama";
- if (lower.includes("deepseek")) return "deepseek";
- if (lower.includes("grok")) return "xai";
- if (lower.includes("command")) return "cohere";
- if (lower.includes("nova") || lower.includes("titan")) return "bedrock";
- return "";
-}
-
-interface ComparisonExchange {
- userMessage: string;
- responses: Record; // model → accumulated response text
-}
-
-interface StreamToModelArgs {
- model: string;
- messages: Array<{ role: "user" | "assistant"; content: string }>;
- accessToken: string;
- mcpServers: string[];
- signal: AbortSignal;
- onChunk: (model: string, chunk: string) => void;
- onDone: (model: string) => void;
-}
-
-// Module-level async helper — each model gets its own independent Promise so they all run in parallel.
-async function streamToModel({
- model,
- messages,
- accessToken,
- mcpServers,
- signal,
- onChunk,
- onDone,
-}: StreamToModelArgs): Promise {
- try {
- await makeOpenAIChatCompletionRequest(
- messages,
- (chunk: string) => onChunk(model, chunk),
- model,
- accessToken,
- undefined, // tags
- signal,
- undefined, // onReasoningContent
- undefined,
- undefined,
- undefined,
- undefined,
- undefined,
- undefined, // positions 8-13
- mcpServers.length > 0 ? mcpServers : undefined, // position 14: selectedMCPServers
- );
- } catch (err: unknown) {
- // Surface real errors in the response card; ignore user-triggered aborts
- if (!(err instanceof Error && err.name === "AbortError")) {
- const msg = err instanceof Error ? err.message : String(err);
- onChunk(model, `\n\n_Error: ${msg}_`);
- }
- } finally {
- onDone(model);
- }
-}
-
-const ChatPage: React.FC = ({ accessToken, userRole, userId, userEmail }) => {
- const router = useRouter();
- const searchParams = useSearchParams();
- const activeConversationId = searchParams.get("id");
- const hadActiveConversationOnMountRef = useRef(activeConversationId !== null);
- const { data: uiConfig } = useUIConfig();
- const uiRoot =
- uiConfig?.server_root_path && uiConfig.server_root_path !== "/"
- ? uiConfig.server_root_path.replace(/\/+$/, "")
- : "";
- const logoSrc = `${getProxyBaseUrl()}/get_image`;
-
- const [selectedModels, setSelectedModels] = useState([]);
- const [models, setModels] = useState([]);
- const [isLoadingModels, setIsLoadingModels] = useState(true);
- const [modelSelectorOpen, setModelSelectorOpen] = useState(false);
- const [modelSearchText, setModelSearchText] = useState("");
-
- const [selectedMCPServers, setSelectedMCPServers] = useState([]);
- const [responsesSessionId, setResponsesSessionId] = useState(null);
- const [prevConversationIdForSessionReset, setPrevConversationIdForSessionReset] = useState(activeConversationId);
- const [isStreaming, setIsStreaming] = useState(false);
- const [inputText, setInputText] = useState("");
- const [mcpPopoverOpen, setMcpPopoverOpen] = useState(false);
- const [sidebarCollapsed, setSidebarCollapsed] = useState(false);
- const _oauthReturn = searchParams?.get("mcpOauthReturn");
- const [sidebarView, setSidebarView] = useState<"chats" | "apps" | "credentials">(
- _oauthReturn === "apps" ? "apps" : "chats",
- );
- const [storageBannerDismissed, setStorageBannerDismissed] = useState(false);
-
- // Comparison mode state (active when selectedModels.length > 1)
- // Each exchange holds the user message + per-model responses so we can do multi-turn comparison.
- const [comparisonExchanges, setComparisonExchanges] = useState([]);
- const [comparisonStreamingSet, setComparisonStreamingSet] = useState>(new Set());
- const comparisonAbortControllersRef = useRef>({});
-
- const abortControllerRef = useRef(null);
- const textareaRef = useRef(null);
- const messagesScrollRef = useRef(null);
- const [showScrollButton, setShowScrollButton] = useState(false);
- const streamScrollLock = useRef(null);
-
- const {
- conversations,
- activeConversation,
- storageUnavailable,
- staleId,
- createConversation,
- appendMessage,
- updateLastAssistantMessage,
- truncateFromMessage,
- deleteConversation,
- renameConversation,
- } = useChatHistory(activeConversationId, userId);
-
- // Clean up the OAuth return param after it's been consumed
- useEffect(() => {
- if (_oauthReturn && typeof window !== "undefined") {
- const url = new URL(window.location.href);
- url.searchParams.delete("mcpOauthReturn");
- window.history.replaceState({}, "", url.toString());
- }
- }, []); // eslint-disable-line react-hooks/exhaustive-deps
-
- // Load models
- useEffect(() => {
- if (!accessToken) return;
- fetchAvailableModels(accessToken)
- .then((data) => {
- const names = (data || []).map((m: { model_group?: string }) => m.model_group ?? "").filter(Boolean);
- setModels(names);
- try {
- const saved = localStorage.getItem(LOCALSTORAGE_MODEL_KEY);
- if (saved) {
- const parsed: unknown = JSON.parse(saved);
- if (Array.isArray(parsed)) {
- const valid = (parsed as string[]).filter((m) => names.includes(m));
- if (valid.length > 0) {
- setSelectedModels(hadActiveConversationOnMountRef.current ? [valid[0]] : valid);
- return;
- }
- }
- }
- } catch {
- // ignore parse errors
- }
- if (names.length > 0) {
- setSelectedModels([names[0]]);
- localStorage.setItem(LOCALSTORAGE_MODEL_KEY, JSON.stringify([names[0]]));
- }
- })
- .catch(() => MessageManager.error("Could not load models"))
- .finally(() => setIsLoadingModels(false));
- }, [accessToken]);
-
- useEffect(() => {
- if (staleId) router.replace(getChatUrl(uiRoot));
- }, [staleId, router, uiRoot]);
-
- // Reset the responses session when switching between conversations so that
- // previous_response_id from conversation A is never sent for conversation B.
- if (activeConversationId !== prevConversationIdForSessionReset) {
- setPrevConversationIdForSessionReset(activeConversationId);
- setResponsesSessionId(null);
- }
-
- const toggleModel = useCallback((model: string) => {
- setSelectedModels((prev) => {
- let next: string[];
- if (prev.includes(model)) {
- next = prev.filter((m) => m !== model);
- } else if (prev.length >= MAX_COMPARISON_MODELS) {
- return prev;
- } else {
- next = [...prev, model];
- }
- localStorage.setItem(LOCALSTORAGE_MODEL_KEY, JSON.stringify(next));
- return next;
- });
- }, []);
-
- const isComparisonMode = selectedModels.length > 1;
- const isAnyStreaming = isStreaming || comparisonStreamingSet.size > 0;
-
- const handleSend = useCallback(
- async (text: string, historyOverride?: Array<{ role: "user" | "assistant"; content: string }>) => {
- const trimmed = text.trim();
- if (!trimmed || selectedModels.length === 0 || isStreaming) return;
- const model = selectedModels[0];
- setInputText("");
-
- let convId = activeConversationId;
- if (!convId) {
- convId = createConversation(model);
- setResponsesSessionId(null); // new conversation starts a fresh session
- router.push(getChatUrl(uiRoot, convId));
- }
-
- appendMessage(convId, { role: "user", content: trimmed });
- appendMessage(convId, { role: "assistant", content: "" });
-
- setIsStreaming(true);
- abortControllerRef.current = new AbortController();
-
- // When historyOverride is set (edit / retry), the existing server-side
- // session chain covers messages that were just truncated and is no longer
- // valid for the rewritten history. Eagerly clear the session so that a
- // failed/aborted edit does not leave a stale session ID that contaminates
- // the next regular send.
- if (historyOverride) {
- setResponsesSessionId(null);
- }
-
- // On a normal continuation turn with an active session, the Responses API
- // already holds the prior context server-side, so we only pass the new
- // user message (sending the full history would double-count it).
- //
- // On the very first turn (no session yet), we send the full history.
- const previousResponseId = historyOverride ? null : responsesSessionId;
-
- const history: Array<{ role: "user" | "assistant"; content: string }> = historyOverride
- ? [...historyOverride, { role: "user" as const, content: trimmed }]
- : previousResponseId
- ? [{ role: "user" as const, content: trimmed }]
- : [
- // Explicitly filter to only user/assistant roles — tool messages
- // lack a required tool_call_id and would cause API errors.
- ...(activeConversation?.messages ?? [])
- .filter(
- (m): m is typeof m & { role: "user" | "assistant" } => m.role === "user" || m.role === "assistant",
- )
- .map((m) => ({ role: m.role, content: m.content })),
- { role: "user" as const, content: trimmed },
- ];
-
- let accumulatedContent = "";
- let accumulatedReasoning = "";
- // MCP events accumulated locally so we can persist them to the message
- // without relying on component state (which would cause stale closures).
- const accumulatedMCPEvents: MCPEvent[] = [];
- // Track clean completion so partial events are not shown on error/abort.
- let streamCompletedCleanly = false;
-
- try {
- await makeOpenAIResponsesRequest(
- history,
- (_role: string, chunk: string) => {
- accumulatedContent += chunk;
- updateLastAssistantMessage(convId!, { content: accumulatedContent });
- },
- model,
- accessToken,
- undefined, // tags
- abortControllerRef.current.signal,
- (rc: string) => {
- accumulatedReasoning += rc;
- updateLastAssistantMessage(convId!, { reasoningContent: accumulatedReasoning });
- },
- undefined,
- undefined,
- undefined,
- undefined,
- undefined,
- undefined,
- selectedMCPServers.length > 0 ? selectedMCPServers : undefined,
- previousResponseId,
- (id: string) => setResponsesSessionId(id),
- (event: MCPEvent) => {
- // Accumulate locally only — persisted once in finally to avoid
- // one full localStorage write per MCP event during streaming.
- accumulatedMCPEvents.push(event);
- },
- );
- streamCompletedCleanly = true;
- } catch (err: unknown) {
- if (err instanceof Error && err.name === "AbortError") {
- updateLastAssistantMessage(convId!, {
- content: accumulatedContent + " [stopped]",
- });
- } else {
- updateLastAssistantMessage(convId!, {
- content: "[Something went wrong. The partial response has been saved.]",
- });
- }
- } finally {
- // Only persist MCP events on clean completion — partial events from an
- // aborted or errored turn would show incomplete tool calls to the user.
- if (accumulatedMCPEvents.length > 0 && streamCompletedCleanly) {
- updateLastAssistantMessage(convId!, { mcpEvents: accumulatedMCPEvents });
- }
- setIsStreaming(false);
- abortControllerRef.current = null;
- }
- },
- [
- activeConversationId,
- activeConversation,
- selectedModels,
- selectedMCPServers,
- accessToken,
- createConversation,
- appendMessage,
- updateLastAssistantMessage,
- router,
- isStreaming,
- responsesSessionId,
- uiRoot,
- ],
- );
-
- const handleSendComparison = useCallback(
- (text: string, currentExchanges: ComparisonExchange[]) => {
- const trimmed = text.trim();
- if (!trimmed || selectedModels.length === 0 || isAnyStreaming) return;
- setInputText("");
-
- // Append a new exchange with empty responses
- const newExchange: ComparisonExchange = { userMessage: trimmed, responses: {} };
- const newExchangeIdx = currentExchanges.length;
- setComparisonExchanges((prev) => [...prev, newExchange]);
- setComparisonStreamingSet(new Set(selectedModels));
-
- const controllers: Record = {};
- selectedModels.forEach((m) => {
- controllers[m] = new AbortController();
- });
- comparisonAbortControllersRef.current = controllers;
-
- // Launch all model streams simultaneously — Promise.allSettled ensures they run in parallel
- // (streamToModel handles its own errors internally so these promises won't reject)
- void Promise.allSettled(
- selectedModels.map((model) => {
- // Build per-model history: each model's past responses become its own context
- const history: Array<{ role: "user" | "assistant"; content: string }> = [];
- for (const ex of currentExchanges) {
- history.push({ role: "user", content: ex.userMessage });
- history.push({ role: "assistant", content: ex.responses[model] ?? "" });
- }
- history.push({ role: "user", content: trimmed });
-
- return streamToModel({
- model,
- messages: history,
- accessToken,
- mcpServers: selectedMCPServers,
- signal: controllers[model].signal,
- onChunk: (m, chunk) =>
- setComparisonExchanges((prev) => {
- const updated = [...prev];
- const ex = { ...updated[newExchangeIdx] };
- ex.responses = { ...ex.responses, [m]: (ex.responses[m] ?? "") + chunk };
- updated[newExchangeIdx] = ex;
- return updated;
- }),
- onDone: (m) =>
- setComparisonStreamingSet((prev) => {
- const next = new Set(prev);
- next.delete(m);
- return next;
- }),
- });
- }),
- );
- },
- [selectedModels, accessToken, selectedMCPServers, isAnyStreaming],
- );
-
- const handleStop = useCallback(() => {
- abortControllerRef.current?.abort();
- Object.values(comparisonAbortControllersRef.current).forEach((c) => c.abort());
- comparisonAbortControllersRef.current = {};
- }, []);
-
- const handleEditAndResend = useCallback(
- (messageId: string, newContent: string) => {
- if (!activeConversationId || isStreaming) return;
- // Compute the truncated history synchronously before the async state update lands,
- // so handleSend receives the correct pre-edit context rather than the stale closure value.
- const msgs = activeConversation?.messages ?? [];
- const idx = msgs.findIndex((m) => m.id === messageId);
- const priorMessages = (idx === -1 ? msgs : msgs.slice(0, idx))
- .filter((m) => m.role === "user" || m.role === "assistant")
- .map((m) => ({ role: m.role as "user" | "assistant", content: m.content }));
- truncateFromMessage(activeConversationId, messageId);
- handleSend(newContent, priorMessages);
- },
- [activeConversationId, isStreaming, activeConversation, truncateFromMessage, handleSend],
- );
-
- const handleSubmit = useCallback(
- (text: string) => {
- if (isComparisonMode) {
- handleSendComparison(text, comparisonExchanges);
- } else {
- handleSend(text);
- }
- },
- [isComparisonMode, handleSend, handleSendComparison, comparisonExchanges],
- );
-
- const handleKeyDown = (e: React.KeyboardEvent) => {
- if (e.key === "Enter" && !e.shiftKey) {
- e.preventDefault();
- handleSubmit(inputText);
- }
- };
-
- // Auto-resize textarea
- useEffect(() => {
- const ta = textareaRef.current;
- if (!ta) return;
- ta.style.height = "auto";
- ta.style.height = `${Math.min(ta.scrollHeight, 180)}px`;
- }, [inputText]);
-
- // Track scroll position to show/hide scroll-to-bottom button
- useEffect(() => {
- const el = messagesScrollRef.current;
- if (!el) return;
- const onScroll = () => {
- const distFromBottom = el.scrollHeight - el.scrollTop - el.clientHeight;
- setShowScrollButton(distFromBottom > 120);
- if (streamScrollLock.current !== null) {
- streamScrollLock.current = el.scrollTop; // track user-initiated scroll
- }
- };
- el.addEventListener("scroll", onScroll, { passive: true });
- return () => el.removeEventListener("scroll", onScroll);
- }, [activeConversation]);
-
- // Start/stop the scroll lock when streaming begins/ends
- useEffect(() => {
- const el = messagesScrollRef.current;
- if (isStreaming) {
- streamScrollLock.current = el?.scrollTop ?? 0;
- } else {
- streamScrollLock.current = null;
- }
- }, [isStreaming]);
-
- // After every render during streaming, restore the locked scroll position
- useLayoutEffect(() => {
- if (streamScrollLock.current === null) return;
- const el = messagesScrollRef.current;
- if (!el) return;
- el.scrollTop = streamScrollLock.current;
- });
-
- // Scroll to bottom only when message COUNT increases (new message added)
- const prevMsgCountRef = useRef(0);
- useLayoutEffect(() => {
- const count = activeConversation?.messages?.length ?? 0;
- const prev = prevMsgCountRef.current;
- prevMsgCountRef.current = count;
- if (count > prev) {
- const el = messagesScrollRef.current;
- if (el) el.scrollTop = el.scrollHeight;
- }
- }, [activeConversation?.messages]);
-
- const showBlankState = !isComparisonMode
- ? !activeConversation || activeConversation.messages.length === 0
- : comparisonExchanges.length === 0;
- const displayName = userEmail?.split("@")[0] ?? userId ?? "";
- const greeting = displayName ? `${getGreeting()}, ${displayName}` : getGreeting();
- const dashboardUrl = getDashboardUrl(uiRoot);
-
- // Filtered models: selected ones float to the top, then alphabetical
- const filteredModels = (
- modelSearchText ? models.filter((m) => m.toLowerCase().includes(modelSearchText.toLowerCase())) : models
- ).sort((a, b) => {
- const aSelected = selectedModels.includes(a);
- const bSelected = selectedModels.includes(b);
- if (aSelected && !bSelected) return -1;
- if (!aSelected && bSelected) return 1;
- return 0;
- });
-
- // ---- Model selector popover content ----
- const modelSelectorContent = (
-
-
- setModelSearchText(e.target.value)}
- placeholder="Search models..."
- style={{
- width: "100%",
- padding: "6px 10px",
- border: "1px solid #d1d5db",
- borderRadius: 6,
- fontSize: 13,
- outline: "none",
- boxSizing: "border-box",
- }}
- />
-
- {selectedModels.length >= MAX_COMPARISON_MODELS && (
-
- Max {MAX_COMPARISON_MODELS} models selected — deselect one to change.
-
- )}
-
- {filteredModels.map((m) => {
- const checked = selectedModels.includes(m);
- const disabled = !checked && selectedModels.length >= MAX_COMPARISON_MODELS;
- const provider = getProviderFromModelName(m);
- const { logo } = provider ? getProviderLogoAndName(provider) : { logo: "" };
- return (
-
toggleModel(m)}
- style={{
- display: "flex",
- alignItems: "center",
- gap: 8,
- width: "100%",
- padding: "7px 12px",
- background: checked ? "#eff6ff" : "transparent",
- border: "none",
- cursor: disabled ? "not-allowed" : "pointer",
- textAlign: "left",
- opacity: disabled ? 0.45 : 1,
- borderRadius: 4,
- }}
- >
-
- {checked && }
-
- {logo ? (
- {
- (e.currentTarget as HTMLImageElement).style.display = "none";
- }}
- />
- ) : (
-
- )}
-
- {m}
-
-
- );
- })}
-
-
- );
-
- // ---- Sidebar nav item renderer ----
- const sidebarNavItem = ({
- icon,
- label,
- onClick,
- active = false,
- kbd,
- }: {
- icon: React.ReactNode;
- label: string;
- onClick: () => void;
- active?: boolean;
- kbd?: string;
- }) => (
-
- {
- if (!active) (e.currentTarget as HTMLButtonElement).style.background = "#f5f5f5";
- }}
- onMouseLeave={(e) => {
- (e.currentTarget as HTMLButtonElement).style.background = active ? "#e8f4ff" : "transparent";
- }}
- >
- {icon}
- {!sidebarCollapsed && (
- <>
- {label}
- {kbd && {kbd} }
- >
- )}
-
-
- );
-
- // ---- Model selector trigger button ----
- const modelSelectorTrigger = isLoadingModels ? (
-
- ) : (
- {
- setModelSelectorOpen(open);
- if (!open) setModelSearchText("");
- }}
- content={modelSelectorContent}
- trigger="click"
- placement="bottomLeft"
- >
- {
- (e.currentTarget as HTMLButtonElement).style.background = "#f5f5f5";
- }}
- onMouseLeave={(e) => {
- (e.currentTarget as HTMLButtonElement).style.background = "transparent";
- }}
- >
- {selectedModels.length === 0 ? (
- Select model
- ) : selectedModels.length === 1 ? (
- <>
- {(() => {
- const provider = getProviderFromModelName(selectedModels[0]);
- const { logo } = provider ? getProviderLogoAndName(provider) : { logo: "" };
- return logo ? (
- {
- (e.currentTarget as HTMLImageElement).style.display = "none";
- }}
- />
- ) : null;
- })()}
-
- {selectedModels[0]}
-
- >
- ) : (
-
- {selectedModels.map((m) => {
- const provider = getProviderFromModelName(m);
- const { logo } = provider ? getProviderLogoAndName(provider) : { logo: "" };
- return (
-
- {logo && (
- {
- (e.currentTarget as HTMLImageElement).style.display = "none";
- }}
- />
- )}
-
- {m}
-
-
- );
- })}
-
- )}
-
-
-
- );
-
- // ---- Shared input bar ----
- const inputBar = (inConversation: boolean) => (
-
- );
-
- return (
-
- {/* ===== LEFT SIDEBAR ===== */}
-
- {/* Sidebar header: logo + collapse button */}
-
- {!sidebarCollapsed && (
-
-
-
- )}
-
- setSidebarCollapsed((v) => !v)}
- style={{
- background: "none",
- border: "none",
- cursor: "pointer",
- padding: 6,
- borderRadius: 7,
- color: "#6b7280",
- fontSize: 16,
- display: "flex",
- alignItems: "center",
- }}
- >
- {sidebarCollapsed ? : }
-
-
-
-
- {/* Sidebar nav buttons */}
-
- {sidebarNavItem({
- icon: ,
- label: "New chat",
- onClick: () => router.push(getChatUrl(uiRoot)),
- })}
- {sidebarNavItem({
- icon: ,
- label: "Search chats",
- onClick: () => setSidebarView("chats"),
- })}
-
-
-
-
- {/* Chats / Apps tabs + Back to console */}
-
- {sidebarNavItem({
- icon:
,
- label: "Chats",
- onClick: () => setSidebarView("chats"),
- active: sidebarView === "chats",
- })}
- {sidebarNavItem({
- icon:
,
- label: "Apps",
- onClick: () => setSidebarView("apps"),
- active: sidebarView === "apps",
- })}
- {sidebarNavItem({
- icon:
,
- label: "Credentials",
- onClick: () => setSidebarView("credentials"),
- active: sidebarView === "credentials",
- })}
-
- {
- (e.currentTarget as HTMLAnchorElement).style.background = "#f5f5f5";
- }}
- onMouseLeave={(e) => {
- (e.currentTarget as HTMLAnchorElement).style.background = "transparent";
- }}
- >
-
- {!sidebarCollapsed && Back to Developer Console UI }
-
-
-
-
-
-
- {/* Sidebar content — only conversation list, only when in chats view and expanded */}
- {!sidebarCollapsed && sidebarView === "chats" && (
-
- router.push(getChatUrl(uiRoot, id))}
- onDelete={(id) => {
- deleteConversation(id);
- if (id === activeConversationId) router.push(getChatUrl(uiRoot));
- }}
- onNewChat={() => router.push(getChatUrl(uiRoot))}
- onRename={renameConversation}
- />
-
- )}
-
-
- {/* ===== MAIN AREA ===== */}
-
- {/* Top bar */}
-
- {/* Left: model selector */}
-
- {modelSelectorTrigger}
-
-
- {/* Right: settings */}
-
-
-
-
-
-
-
-
-
- {/* Storage warning banner */}
- {storageUnavailable && !storageBannerDismissed && (
-
- Chat history won't be saved in this browser session.
- setStorageBannerDismissed(true)}
- style={{ background: "none", border: "none", cursor: "pointer", fontSize: 16, color: "#874d00" }}
- >
- ×
-
-
- )}
-
- {/* Content area */}
-
- {/* ---- Apps page view ---- */}
- {sidebarView === "apps" ? (
-
-
-
- ) : sidebarView === "credentials" ? (
- /* ---- Credentials view ---- */
-
-
-
- ) : showBlankState ? (
- /* ---- Blank state ---- */
-
- {/* Greeting */}
-
- {isComparisonMode ? `Compare ${selectedModels.length} models` : greeting}
-
-
- {isComparisonMode ? (
-
- Send a message to see responses side-by-side
-
- ) : (
-
- Chat with 100+ LLMs + MCP tools — authenticate once, use them here.{" "}
- setSidebarView("apps")}
- style={{
- background: "none",
- border: "none",
- cursor: "pointer",
- color: "#1677ff",
- fontSize: 14,
- padding: 0,
- fontWeight: 500,
- }}
- >
- Open Apps →
-
-
- )}
-
- {/* Input card */}
-
{inputBar(false)}
-
- {/* Suggestion chips — only in single-model mode */}
- {!isComparisonMode && (
-
- {SUGGESTIONS.map((s) => (
- setInputText(s + ": ")}
- style={{
- background: "#f9fafb",
- border: "1px solid #e5e7eb",
- borderRadius: 20,
- padding: "7px 16px",
- fontSize: 14,
- color: "#374151",
- cursor: "pointer",
- }}
- onMouseEnter={(e) => {
- (e.currentTarget as HTMLButtonElement).style.background = "#f3f4f6";
- }}
- onMouseLeave={(e) => {
- (e.currentTarget as HTMLButtonElement).style.background = "#f9fafb";
- }}
- >
- {s}
-
- ))}
-
- )}
-
- ) : (
- /* ---- Active conversation (single-model or comparison) ---- */
-
= 3 ? 1200 : 960) : 760,
- margin: "0 auto",
- width: "100%",
- padding: "0 24px",
- position: "relative",
- }}
- >
-
- {isComparisonMode ? (
- /* Comparison: multi-turn exchanges, each with user bubble + side-by-side response cards */
-
- {comparisonExchanges.map((exchange, exchangeIdx) => {
- const isLastExchange = exchangeIdx === comparisonExchanges.length - 1;
- return (
-
- {/* User message bubble */}
-
-
- {exchange.userMessage}
-
-
-
- {/* Response cards side-by-side */}
-
- {selectedModels.map((model, idx) => {
- const provider = getProviderFromModelName(model);
- const { logo } = provider ? getProviderLogoAndName(provider) : { logo: "" };
- const responseText = exchange.responses[model] ?? "";
- const isModelStreaming = isLastExchange && comparisonStreamingSet.has(model);
- return (
-
- {/* Card header — only show on first exchange */}
- {exchangeIdx === 0 && (
-
- {logo ? (
-
{
- (e.currentTarget as HTMLImageElement).style.display = "none";
- }}
- />
- ) : (
-
- )}
-
- Response {idx + 1}
-
-
- {model}
-
-
- )}
- {/* Card body */}
-
- {isModelStreaming && (
-
- ●
-
- )}
- {responseText ? (
-
(
-
- {children}
-
- ),
- code: ({ className, children }) => {
- const isBlock = /language-(\w+)/.exec(className || "");
- if (isBlock) {
- return (
-
- {children}
-
- );
- }
- return (
-
- {children}
-
- );
- },
- }}
- >
- {responseText}
-
- ) : isModelStreaming ? (
-
Generating…
- ) : (
-
—
- )}
-
-
- );
- })}
-
-
- );
- })}
-
- ) : (
-
- )}
-
- {showScrollButton && (
-
{
- const el = messagesScrollRef.current;
- if (el) {
- el.scrollTo({ top: el.scrollHeight, behavior: "smooth" });
- if (streamScrollLock.current !== null) {
- streamScrollLock.current = el.scrollHeight;
- }
- }
- }}
- style={{
- position: "absolute",
- bottom: 100,
- left: "50%",
- transform: "translateX(-50%)",
- width: 34,
- height: 34,
- borderRadius: "50%",
- background: "rgba(255,255,255,0.75)",
- backdropFilter: "blur(6px)",
- WebkitBackdropFilter: "blur(6px)",
- border: "1px solid rgba(0,0,0,0.1)",
- boxShadow: "0 1px 4px rgba(0,0,0,0.08)",
- cursor: "pointer",
- display: "flex",
- alignItems: "center",
- justifyContent: "center",
- color: "#6b7280",
- zIndex: 10,
- transition: "background 0.15s",
- }}
- onMouseEnter={(e) => {
- (e.currentTarget as HTMLButtonElement).style.background = "rgba(255,255,255,0.95)";
- }}
- onMouseLeave={(e) => {
- (e.currentTarget as HTMLButtonElement).style.background = "rgba(255,255,255,0.75)";
- }}
- aria-label="Scroll to bottom"
- >
-
-
- )}
-
- {/* Input bar (in conversation) */}
-
{inputBar(true)}
-
- )}
-
-
-
- );
-};
-
-export default ChatPage;
diff --git a/ui/litellm-dashboard/src/components/chat/ChatShell.test.tsx b/ui/litellm-dashboard/src/components/chat/ChatShell.test.tsx
new file mode 100644
index 000000000000..01dca80acd59
--- /dev/null
+++ b/ui/litellm-dashboard/src/components/chat/ChatShell.test.tsx
@@ -0,0 +1,76 @@
+import { afterEach, describe, expect, it, vi } from "vitest";
+import { fireEvent, render, screen } from "@testing-library/react";
+import ChatShell from "./ChatShell";
+
+const { mockPush, mockUsePathname, mockUseChatShell } = vi.hoisted(() => ({
+ mockPush: vi.fn(),
+ mockUsePathname: vi.fn(() => "/ui/chat"),
+ mockUseChatShell: vi.fn(() => ({
+ conversations: [],
+ activeConversationId: null,
+ deleteConversation: vi.fn(),
+ renameConversation: vi.fn(),
+ })),
+}));
+
+vi.mock("next/navigation", () => ({
+ useRouter: () => ({ push: mockPush }),
+ usePathname: mockUsePathname,
+}));
+// Deterministic hrefs so navigation/active-state assertions don't depend on server_root_path.
+vi.mock("@/utils/migratedPages", () => ({ migratedHref: (seg: string) => `/ui/${seg}`.replace(/\/$/, "") || "/ui" }));
+vi.mock("@/contexts/ChatShellContext", () => ({ useChatShell: mockUseChatShell }));
+vi.mock("./ConversationList", () => ({ default: () =>
}));
+
+describe("ChatShell", () => {
+ afterEach(() => {
+ mockPush.mockClear();
+ mockUsePathname.mockReturnValue("/ui/chat");
+ });
+
+ it("marks Chats active and shows the conversation list on the base chat route", () => {
+ render(
+
+
+ ,
+ );
+ expect(screen.getByRole("button", { name: "Chats" })).toHaveAttribute("aria-current", "page");
+ expect(screen.getByRole("button", { name: "API Keys" })).not.toHaveAttribute("aria-current");
+ expect(screen.getByTestId("conversation-list")).toBeInTheDocument();
+ });
+
+ it("marks API Keys active while still showing the conversation list", () => {
+ mockUsePathname.mockReturnValue("/ui/chat/api-keys");
+ render(
+
+
+ ,
+ );
+ expect(screen.getByRole("button", { name: "API Keys" })).toHaveAttribute("aria-current", "page");
+ expect(screen.getByRole("button", { name: "Chats" })).not.toHaveAttribute("aria-current");
+ expect(screen.getByTestId("conversation-list")).toBeInTheDocument();
+ });
+
+ it("navigates to the dedicated route for each nav item", () => {
+ render(
+
+
+ ,
+ );
+ fireEvent.click(screen.getByRole("button", { name: "Integrations" }));
+ expect(mockPush).toHaveBeenCalledWith("/ui/chat/integrations");
+
+ fireEvent.click(screen.getByRole("button", { name: "Usage" }));
+ expect(mockPush).toHaveBeenCalledWith("/ui/chat/usage");
+ });
+
+ it("tolerates a trailing slash on the current pathname when matching the active route", () => {
+ mockUsePathname.mockReturnValue("/ui/chat/usage/");
+ render(
+
+
+ ,
+ );
+ expect(screen.getByRole("button", { name: "Usage" })).toHaveAttribute("aria-current", "page");
+ });
+});
diff --git a/ui/litellm-dashboard/src/components/chat/ChatShell.tsx b/ui/litellm-dashboard/src/components/chat/ChatShell.tsx
new file mode 100644
index 000000000000..f4e0703d62b9
--- /dev/null
+++ b/ui/litellm-dashboard/src/components/chat/ChatShell.tsx
@@ -0,0 +1,139 @@
+"use client";
+
+import React from "react";
+import { usePathname, useRouter } from "next/navigation";
+import { Plus, MessageSquare, LayoutGrid, KeyRound, Lock, BarChart3 } from "lucide-react";
+import { Button } from "@/components/ui/button";
+import { Separator } from "@/components/ui/separator";
+import { migratedHref } from "@/utils/migratedPages";
+import { useChatShell } from "@/contexts/ChatShellContext";
+import ConversationList from "./ConversationList";
+
+const CHAT_BASE = migratedHref("chat");
+export const CHAT_ROUTES = {
+ chats: CHAT_BASE,
+ integrations: `${CHAT_BASE}/integrations`,
+ credentials: `${CHAT_BASE}/credentials`,
+ apiKeys: `${CHAT_BASE}/api-keys`,
+ usage: `${CHAT_BASE}/usage`,
+};
+
+function stripTrailingSlash(path: string): string {
+ return path.length > 1 ? path.replace(/\/+$/, "") : path;
+}
+
+interface NavItemProps {
+ icon: React.ReactNode;
+ label: string;
+ onClick: () => void;
+ active?: boolean;
+}
+
+function NavItem({ icon, label, onClick, active = false }: NavItemProps) {
+ return (
+
+ {icon}
+ {label}
+
+ );
+}
+
+interface ChatShellProps {
+ children: React.ReactNode;
+}
+
+const ChatShell: React.FC = ({ children }) => {
+ const router = useRouter();
+ const pathname = stripTrailingSlash(usePathname() ?? "");
+ const { conversations, activeConversationId, deleteConversation, renameConversation } = useChatShell();
+
+ const isChatsRoute = pathname === CHAT_ROUTES.chats;
+
+ return (
+
+
+ This is a pre-v0 feature. Do not use in production, it may change unexpectedly. Please share feedback{" "}
+
+ here
+
+ .
+
+
+
+
+
router.push(CHAT_ROUTES.chats)} className="w-full justify-start gap-2.5">
+
+ New Chat
+
+
+
+
+
+
+ }
+ label="Chats"
+ onClick={() => router.push(CHAT_ROUTES.chats)}
+ active={isChatsRoute}
+ />
+ }
+ label="Integrations"
+ onClick={() => router.push(CHAT_ROUTES.integrations)}
+ active={pathname === CHAT_ROUTES.integrations}
+ />
+ }
+ label="Credentials"
+ onClick={() => router.push(CHAT_ROUTES.credentials)}
+ active={pathname === CHAT_ROUTES.credentials}
+ />
+ }
+ label="API Keys"
+ onClick={() => router.push(CHAT_ROUTES.apiKeys)}
+ active={pathname === CHAT_ROUTES.apiKeys}
+ />
+ }
+ label="Usage"
+ onClick={() => router.push(CHAT_ROUTES.usage)}
+ active={pathname === CHAT_ROUTES.usage}
+ />
+
+
+
+
+
+ router.push(`${CHAT_ROUTES.chats}?id=${id}`)}
+ onDelete={(id) => {
+ deleteConversation(id);
+ if (id === activeConversationId) router.push(CHAT_ROUTES.chats);
+ }}
+ onRename={renameConversation}
+ />
+
+
+
+
{children}
+
+
+ );
+};
+
+export default ChatShell;
diff --git a/ui/litellm-dashboard/src/components/chat/ConversationList.tsx b/ui/litellm-dashboard/src/components/chat/ConversationList.tsx
index 7501c19002d2..91c18c099359 100644
--- a/ui/litellm-dashboard/src/components/chat/ConversationList.tsx
+++ b/ui/litellm-dashboard/src/components/chat/ConversationList.tsx
@@ -1,44 +1,46 @@
"use client";
import React, { useState, useEffect, useRef, useCallback } from "react";
-import { Button, Input, Modal, Popconfirm, Tooltip, Avatar, Typography } from "antd";
+import { Pencil, Trash2, Search, MessageSquare } from "lucide-react";
+import { Button } from "@/components/ui/button";
+import { Input } from "@/components/ui/input";
+import { Dialog, DialogContent } from "@/components/ui/dialog";
import {
- EditOutlined,
- DeleteOutlined,
- PlusOutlined,
- SearchOutlined,
- UserOutlined,
- MessageOutlined,
-} from "@ant-design/icons";
+ AlertDialog,
+ AlertDialogAction,
+ AlertDialogCancel,
+ AlertDialogContent,
+ AlertDialogDescription,
+ AlertDialogFooter,
+ AlertDialogHeader,
+ AlertDialogTitle,
+ AlertDialogTrigger,
+} from "@/components/ui/alert-dialog";
+import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from "@/components/ui/tooltip";
+import { ScrollArea } from "@/components/ui/scroll-area";
import dayjs from "dayjs";
import { Conversation } from "./types";
-const { Text } = Typography;
-
interface Props {
conversations: Conversation[];
activeConversationId: string | null;
onSelect: (id: string) => void;
onDelete: (id: string) => void;
- onNewChat: () => void;
onRename: (id: string, newTitle: string) => void;
}
-// ---- Date grouping helpers ----
-
-type DateGroup = "Today" | "Yesterday" | "Last 7 Days" | "Older";
+type DateGroup = "Recents" | "Yesterday" | "Last 7 Days" | "Older";
const getDateGroup = (timestamp: number): DateGroup => {
const now = dayjs();
const date = dayjs(timestamp);
-
- if (date.isSame(now, "day")) return "Today";
+ if (date.isSame(now, "day")) return "Recents";
if (date.isSame(now.subtract(1, "day"), "day")) return "Yesterday";
if (date.isAfter(now.subtract(7, "day"))) return "Last 7 Days";
return "Older";
};
-const DATE_GROUP_ORDER: DateGroup[] = ["Today", "Yesterday", "Last 7 Days", "Older"];
+const DATE_GROUP_ORDER: DateGroup[] = ["Recents", "Yesterday", "Last 7 Days", "Older"];
interface GroupedConversations {
group: DateGroup;
@@ -47,21 +49,17 @@ interface GroupedConversations {
const groupConversations = (conversations: Conversation[]): GroupedConversations[] => {
const map = new Map();
-
for (const conv of conversations) {
const group = getDateGroup(conv.updatedAt);
if (!map.has(group)) map.set(group, []);
map.get(group)!.push(conv);
}
-
return DATE_GROUP_ORDER.filter((g) => map.has(g)).map((g) => ({
group: g,
items: map.get(g)!,
}));
};
-// ---- Single conversation row ----
-
interface ConversationRowProps {
conv: Conversation;
isActive: boolean;
@@ -111,102 +109,84 @@ const ConversationRow: React.FC = ({ conv, isActive, onSel
}
};
- const truncatedTitle = conv.title.length > 40 ? conv.title.slice(0, 40) + "…" : conv.title;
+ const truncatedTitle = conv.title.length > 40 ? conv.title.slice(0, 40) + "\u2026" : conv.title;
return (
!editing && onSelect(conv.id)}
- className="conversation-row group"
- style={{
- display: "flex",
- alignItems: "center",
- padding: "6px 8px",
- borderRadius: 6,
- cursor: editing ? "default" : "pointer",
- backgroundColor: isActive ? "#e6f4ff" : "transparent",
- transition: "background-color 0.15s",
- minHeight: 34,
- position: "relative",
- }}
- onMouseEnter={(e) => {
- if (!isActive) {
- (e.currentTarget as HTMLDivElement).style.backgroundColor = "#f5f5f5";
- }
- }}
- onMouseLeave={(e) => {
- if (!isActive) {
- (e.currentTarget as HTMLDivElement).style.backgroundColor = "transparent";
- }
- }}
+ className={`group flex items-center px-2 py-1.5 rounded-md cursor-pointer transition-colors min-h-[34px] relative ${
+ isActive ? "bg-accent text-accent-foreground" : "hover:bg-accent/50"
+ }`}
>
{editing ? (
{
- inputRef.current = node?.input ?? null;
- }}
- size="small"
+ ref={inputRef}
value={editValue}
onChange={(e) => setEditValue(e.target.value)}
onKeyDown={handleKeyDown}
onBlur={commitRename}
onClick={(e) => e.stopPropagation()}
- style={{ flex: 1, fontSize: 13 }}
+ className="h-7 text-[13px] flex-1"
/>
) : (
<>
-
{truncatedTitle}
-
+
- {/* Action icons — visible only on hover via CSS opacity */}
e.stopPropagation()}
>
-
- }
- onClick={startEditing}
- style={{ width: 22, height: 22, padding: 0, minWidth: 22 }}
- />
-
-
onDelete(conv.id)}
- okText="Delete"
- cancelText="Cancel"
- okButtonProps={{ danger: true }}
- >
-
- }
- style={{ width: 22, height: 22, padding: 0, minWidth: 22 }}
- />
+
+
+
+
+
+
+
+
+ Rename
+
-
+
+
+
+
+
+
+
+
+
+
+
+
+
+ Delete
+
+
+
+
+
+ Delete this conversation?
+ This action cannot be undone
+
+
+ Cancel
+ onDelete(conv.id)}
+ className="bg-destructive text-white hover:bg-destructive/90"
+ >
+ Delete
+
+
+
+
>
)}
@@ -214,8 +194,6 @@ const ConversationRow: React.FC
= ({ conv, isActive, onSel
);
};
-// ---- Cmd+K search modal ----
-
interface SearchModalProps {
open: boolean;
conversations: Conversation[];
@@ -242,77 +220,49 @@ const SearchModal: React.FC = ({ open, conversations, onSelect
};
return (
-
- }
- placeholder="Search conversations…"
- value={query}
- onChange={(e) => setQuery(e.target.value)}
- style={{ marginBottom: 12 }}
- allowClear
- />
+ !v && onClose()}>
+
+
+
+ setQuery(e.target.value)}
+ className="pl-9"
+ />
+
-
- {filtered.length === 0 ? (
-
No conversations found
- ) : (
- filtered.map((conv) => {
- const truncated = conv.title.length > 55 ? conv.title.slice(0, 55) + "…" : conv.title;
- return (
-
handleSelect(conv.id)}
- style={{
- display: "flex",
- alignItems: "center",
- gap: 8,
- padding: "8px 10px",
- borderRadius: 6,
- cursor: "pointer",
- transition: "background-color 0.1s",
- }}
- onMouseEnter={(e) => {
- (e.currentTarget as HTMLDivElement).style.backgroundColor = "#f0f5ff";
- }}
- onMouseLeave={(e) => {
- (e.currentTarget as HTMLDivElement).style.backgroundColor = "transparent";
- }}
- >
-
- {truncated}
-
- {dayjs(conv.updatedAt).format("MMM D")}
-
-
- );
- })
- )}
-
-
+
+ {filtered.length === 0 ? (
+ No conversations found
+ ) : (
+ filtered.map((conv) => {
+ const truncated = conv.title.length > 55 ? conv.title.slice(0, 55) + "\u2026" : conv.title;
+ return (
+ handleSelect(conv.id)}
+ className="flex items-center gap-2 px-2.5 py-2 rounded-md cursor-pointer transition-colors hover:bg-accent/50"
+ >
+
+ {truncated}
+
+ {dayjs(conv.updatedAt).format("MMM D")}
+
+
+ );
+ })
+ )}
+
+
+
);
};
-// ---- Main ConversationList component ----
-
-const ConversationList: React.FC = ({
- conversations,
- activeConversationId,
- onSelect,
- onDelete,
- onNewChat,
- onRename,
-}) => {
+const ConversationList: React.FC = ({ conversations, activeConversationId, onSelect, onDelete, onRename }) => {
const [searchModalOpen, setSearchModalOpen] = useState(false);
- // Cmd+K / Ctrl+K listener
const handleGlobalKeyDown = useCallback((e: KeyboardEvent) => {
if (e.key === "k" && (e.metaKey || e.ctrlKey)) {
e.preventDefault();
@@ -329,69 +279,18 @@ const ConversationList: React.FC = ({
return (
<>
- {/* Hover-reveal CSS for action icons */}
-
-
-
- {/* Top: New Chat button */}
-
-
- } onClick={onNewChat} style={{ width: "100%" }}>
- New Chat
-
-
-
-
- {/* Conversation list (scrollable) */}
-
+
+
{grouped.length === 0 ? (
-
- No conversations yet.
+
+ No conversations yet
- Start a new chat above.
+ Start a new chat above
) : (
grouped.map(({ group, items }) => (
-
-
+
+
{group}
{items.map((conv) => (
@@ -407,38 +306,9 @@ const ConversationList: React.FC
= ({
))
)}
-
-
- {/* Bottom: user avatar placeholder */}
-
-
}
- style={{ backgroundColor: "#e0e7ff", color: "#4f46e5", flexShrink: 0 }}
- />
-
- My Account
-
-
+
- {/* Cmd+K search modal */}
= ({ accessToken, userId, premiumUser }) => {
+ const queryClient = useQueryClient();
+ const [rotateTarget, setRotateTarget] = useState(null);
+ const [regeneratedKey, setRegeneratedKey] = useState(null);
+ const [isRegenerating, setIsRegenerating] = useState(false);
+ const [copied, setCopied] = useState(false);
+ const [formState, setFormState] = useState({
+ key_alias: "",
+ max_budget: "",
+ tpm_limit: "",
+ rpm_limit: "",
+ duration: "",
+ grace_period: "",
+ });
+ const [formErrors, setFormErrors] = useState>>({});
+
+ const { data, isLoading } = useQuery({
+ queryKey: [KEYS_QUERY_KEY, accessToken, userId],
+ queryFn: async () => {
+ const resp = await keyListCall(accessToken, null, null, null, userId, null, 1, 100, null, null, null, null);
+ return (resp?.keys ?? []) as KeyResponse[];
+ },
+ enabled: !!accessToken,
+ });
+
+ const keys = data ?? [];
+
+ const openRotateModal = (key: KeyResponse) => {
+ setRotateTarget(key);
+ setRegeneratedKey(null);
+ setCopied(false);
+ setFormErrors({});
+ setFormState({
+ key_alias: key.key_alias ?? "",
+ max_budget: key.max_budget != null ? String(key.max_budget) : "",
+ tpm_limit: key.tpm_limit != null ? String(key.tpm_limit) : "",
+ rpm_limit: key.rpm_limit != null ? String(key.rpm_limit) : "",
+ duration: key.duration ?? "",
+ grace_period: "",
+ });
+ };
+
+ const validate = (): boolean => {
+ const errors: Partial> = {};
+ const keyExpired = rotateTarget ? isKeyExpired(rotateTarget.expires) : false;
+
+ if (formState.duration && !DURATION_RE.test(formState.duration)) {
+ errors.duration = "Must be a duration like 30s, 30m, 24h, 2d, 1w, or 1mo";
+ }
+ if (keyExpired && !formState.duration) {
+ errors.duration = "Expiration is required for expired keys";
+ }
+ if (formState.grace_period && !DURATION_RE.test(formState.grace_period)) {
+ errors.grace_period = "Must be a duration like 24h, 2d";
+ }
+
+ setFormErrors(errors);
+ return Object.keys(errors).length === 0;
+ };
+
+ const handleRegenerate = async () => {
+ if (!rotateTarget || !validate()) return;
+ setIsRegenerating(true);
+ try {
+ const payload: Record = {};
+ if (formState.key_alias) payload.key_alias = formState.key_alias;
+ if (formState.max_budget) payload.max_budget = parseFloat(formState.max_budget);
+ if (formState.tpm_limit) payload.tpm_limit = parseInt(formState.tpm_limit, 10);
+ if (formState.rpm_limit) payload.rpm_limit = parseInt(formState.rpm_limit, 10);
+ if (formState.duration) payload.duration = formState.duration;
+ if (formState.grace_period) payload.grace_period = formState.grace_period;
+
+ const response = await regenerateKeyCall(accessToken, rotateTarget.token || rotateTarget.token_id, payload);
+ setRegeneratedKey(response.key);
+ MessageManager.success("Key rotated successfully");
+ queryClient.invalidateQueries({ queryKey: [KEYS_QUERY_KEY] });
+ } catch {
+ MessageManager.error("Failed to rotate key");
+ } finally {
+ setIsRegenerating(false);
+ }
+ };
+
+ const closeModal = () => {
+ setRotateTarget(null);
+ setRegeneratedKey(null);
+ setCopied(false);
+ setFormErrors({});
+ };
+
+ const keyIsExpired = rotateTarget ? isKeyExpired(rotateTarget.expires) : false;
+ const newExpiryTime =
+ formState.duration && DURATION_RE.test(formState.duration)
+ ? calculateExpiryPreviewFromDuration(formState.duration)
+ : null;
+
+ const updateField = (field: keyof FormState, value: string) => {
+ setFormState((prev) => ({ ...prev, [field]: value }));
+ if (formErrors[field]) setFormErrors((prev) => ({ ...prev, [field]: undefined }));
+ };
+
+ return (
+
+
+
Your API Keys
+
+ View your virtual keys and spend
+ {premiumUser &&
+ ". Rotate keys to generate new credentials while optionally keeping the old key valid during a grace period"}
+
+
+
+ {isLoading ? (
+
+
+
+
+ Key
+ Spend
+ Expires
+ Created
+ {premiumUser && (
+
+ )}
+
+
+
+ {[...Array(5)].map((_, i) => (
+
+
+
+
+
+
+
+
+
+
+
+
+
+ {premiumUser && (
+
+
+
+ )}
+
+ ))}
+
+
+
+ ) : keys.length === 0 ? (
+
+
+ No keys found
+
+ ) : (
+
+
+
+
+ Key
+ Spend
+ Expires
+ Created
+ {premiumUser && (
+
+ )}
+
+
+
+ {keys.map((record) => {
+ const expired = isKeyExpired(record.expires);
+ return (
+
+
+ {maskKey(record.key_name)}
+ {record.key_alias && {record.key_alias}
}
+
+
+ ${record.spend?.toFixed(2) ?? "0.00"}
+ {record.max_budget != null && record.max_budget > 0 && (
+ / ${record.max_budget.toFixed(2)}
+ )}
+
+
+ {!record.expires ? (
+ Never
+ ) : (
+
+ {expired ? "Expired" : formatExpiresUtc(record.expires)}
+
+ )}
+
+
+ {relativeTime(record.created_at)}
+
+ {premiumUser && (
+
+ openRotateModal(record)} title="Rotate key">
+
+ Rotate
+
+
+ )}
+
+ );
+ })}
+
+
+
+ )}
+
+
!v && closeModal()}>
+
+
+ Rotate Key
+
+
+ {regeneratedKey ? (
+
+
+ Save this key now; you will not see it again
+
+
New Key
+
+ {regeneratedKey}
+
+
+ ) : (
+
+
+ Key Alias
+
+
+
+
+
+
Expire Key
+
updateField("duration", e.target.value)}
+ />
+ {formErrors.duration &&
{formErrors.duration}
}
+
+ Current: {rotateTarget?.expires ? formatExpiresUtc(rotateTarget.expires) : "Never"}
+ {keyIsExpired && " (expired)"}
+
+ {newExpiryTime && (
+
New: {newExpiryTime}
+ )}
+
+
+
Grace Period
+
updateField("grace_period", e.target.value)}
+ />
+ {formErrors.grace_period &&
{formErrors.grace_period}
}
+
+
+
+ )}
+
+
+ {regeneratedKey ? (
+ <>
+
+ Close
+
+ setCopied(true)}>
+
+ {copied ? : }
+ {copied ? "Copied" : "Copy Key"}
+
+
+ >
+ ) : (
+ <>
+
+ Cancel
+
+
+ {isRegenerating ? (
+
+ ) : (
+
+ )}
+ Rotate
+
+ >
+ )}
+
+
+
+
+ );
+};
+
+export default KeysPanel;
diff --git a/ui/litellm-dashboard/src/components/chat/MCPAppsPanel.tsx b/ui/litellm-dashboard/src/components/chat/MCPAppsPanel.tsx
index 2e2baee01eb3..867522090d2d 100644
--- a/ui/litellm-dashboard/src/components/chat/MCPAppsPanel.tsx
+++ b/ui/litellm-dashboard/src/components/chat/MCPAppsPanel.tsx
@@ -2,8 +2,11 @@
import React, { useCallback, useEffect, useRef, useState } from "react";
import { useQuery } from "@tanstack/react-query";
-import { Spin, Input, Button, Skeleton } from "antd";
-import { SearchOutlined, ArrowLeftOutlined, RightOutlined, ToolOutlined, CheckCircleOutlined } from "@ant-design/icons";
+import { Search, ArrowLeft, ChevronRight, Wrench, CheckCircle, Loader2 } from "lucide-react";
+import { Button } from "@/components/ui/button";
+import { Input } from "@/components/ui/input";
+import { Skeleton } from "@/components/ui/skeleton";
+import { Tabs, TabsList, TabsTrigger } from "@/components/ui/tabs";
import {
deleteMCPOAuthUserCredential,
fetchMCPServers,
@@ -14,13 +17,10 @@ import { AUTH_TYPE, MCPServer, MCPTool, handleTransport } from "../mcp_tools/typ
import MessageManager from "@/components/molecules/message_manager";
import { useUserMcpOAuthFlow } from "@/hooks/useUserMcpOAuthFlow";
-// ── OAuth2 connect button ─────────────────────────────────────────────────────
-// Wraps useUserMcpOAuthFlow so each server card can hold its own hook instance.
interface OAuth2ConnectButtonProps {
server: MCPServer;
accessToken: string;
onConnect: (serverId: string) => void;
- /** "badge" = small inline chip (grid card), "button" = full Ant Button (detail view) */
variant?: "badge" | "button";
}
@@ -42,13 +42,9 @@ const OAuth2ConnectButton: React.FC = ({
if (variant === "button") {
return (
-
- {loading ? "Connecting…" : "Connect"}
+
+ {loading && }
+ {loading ? "Connecting\u2026" : "Connect"}
);
}
@@ -59,23 +55,16 @@ const OAuth2ConnectButton: React.FC = ({
e.stopPropagation();
if (!loading) startOAuthFlow();
}}
- style={{
- fontSize: 11,
- fontWeight: 600,
- color: loading ? "#9ca3af" : "#fff",
- background: loading ? "#e5e7eb" : "#1677ff",
- borderRadius: 6,
- padding: "2px 8px",
- cursor: loading ? "default" : "pointer",
- flexShrink: 0,
- whiteSpace: "nowrap",
- }}
+ className={`text-[11px] font-semibold rounded-md px-2 py-0.5 shrink-0 whitespace-nowrap ${
+ loading
+ ? "text-muted-foreground bg-muted cursor-default"
+ : "text-primary-foreground bg-primary cursor-pointer hover:bg-primary/90"
+ }`}
>
- {loading ? "Connecting…" : "Connect"}
+ {loading ? "Connecting\u2026" : "Connect"}
);
};
-// ─────────────────────────────────────────────────────────────────────────────
interface Props {
accessToken: string;
@@ -113,15 +102,10 @@ const MCPAppsPanel: React.FC = ({ accessToken, selectedServers, onChange
const [activeTab, setActiveTab] = useState("all");
const [togglingOn, setTogglingOn] = useState>(new Set());
const [detailServer, setDetailServer] = useState(null);
- // tool counts per server name, preloaded in background
const [toolCounts, setToolCounts] = useState>({});
const [loadingCounts, setLoadingCounts] = useState(false);
- // OAuth2 connect state — tracks which server_ids have a stored user credential
const [oauthConnected, setOauthConnected] = useState>(new Set());
- // Refs keep the latest values for the auto-enable effect so it always reads
- // the current servers/selectedServers/onChange without needing them as
- // dependencies (which would cause the effect to fire on every render).
const serversRef = useRef([]);
useEffect(() => {
serversRef.current = servers;
@@ -147,7 +131,7 @@ const MCPAppsPanel: React.FC = ({ accessToken, selectedServers, onChange
const tools: MCPTool[] = Array.isArray(toolsData?.tools) ? toolsData.tools : [];
setToolCounts((prev) => ({ ...prev, [nameOf(server)]: tools.length }));
} catch {
- // ignore — this server's tool count just stays unset
+ // ignore
}
},
[accessToken],
@@ -162,7 +146,7 @@ const MCPAppsPanel: React.FC = ({ accessToken, selectedServers, onChange
setOauthConnected((prev) => new Set(prev).add(server.server_id));
}
} catch {
- // ignore — server just shows as not connected
+ // ignore
}
},
[accessToken],
@@ -171,7 +155,6 @@ const MCPAppsPanel: React.FC = ({ accessToken, selectedServers, onChange
useEffect(() => {
fetchLoadCancelledRef.current = false;
- // 1. Load servers first — show the list immediately
fetchMCPServers(accessToken)
.then(async (serverData) => {
if (fetchLoadCancelledRef.current) return;
@@ -179,7 +162,6 @@ const MCPAppsPanel: React.FC = ({ accessToken, selectedServers, onChange
setServers(list);
setLoading(false);
- // 2. Fetch tools per server, at most TOOLS_FETCH_CONCURRENCY at a time
setLoadingCounts(true);
const chunks = Array.from({ length: Math.ceil(list.length / TOOLS_FETCH_CONCURRENCY) }, (_, i) =>
list.slice(i * TOOLS_FETCH_CONCURRENCY, (i + 1) * TOOLS_FETCH_CONCURRENCY),
@@ -190,7 +172,6 @@ const MCPAppsPanel: React.FC = ({ accessToken, selectedServers, onChange
}
if (!fetchLoadCancelledRef.current) setLoadingCounts(false);
- // 3. Check OAuth credential status for OAuth2 servers in parallel
const oauthServers = list.filter((s) => s.auth_type === AUTH_TYPE.OAUTH2);
oauthServers.forEach((s) => checkOauthCredential(s));
})
@@ -205,10 +186,6 @@ const MCPAppsPanel: React.FC = ({ accessToken, selectedServers, onChange
};
}, [accessToken, fetchToolCount, checkOauthCredential]);
- // Auto-enable oauth2 servers for the current chat session when a valid
- // credential is detected (either on mount or after a fresh OAuth sign-in).
- // Uses refs for servers/selectedServers/onChange to avoid stale closures
- // without adding them as dependencies (which would re-fire on every render).
useEffect(() => {
if (oauthConnected.size === 0) return;
const namesToAdd = serversRef.current
@@ -222,7 +199,6 @@ const MCPAppsPanel: React.FC = ({ accessToken, selectedServers, onChange
const handleToggle = async (serverName: string, checked: boolean, serverId?: string) => {
if (!checked) {
onChange(selectedServers.filter((s) => s !== serverName));
- // Also clear from oauthConnected so the auto-enable effect doesn't re-add it.
if (serverId) {
setOauthConnected((prev) => {
const next = new Set(prev);
@@ -234,15 +210,12 @@ const MCPAppsPanel: React.FC = ({ accessToken, selectedServers, onChange
}
setTogglingOn((prev) => new Set(prev).add(serverName));
try {
- // Use UUID if available, fall back to name (for connectivity check only)
const idToFetch = serverId ?? serverName;
const result = await listMCPTools(accessToken, idToFetch);
if (result?.error) {
MessageManager.warning(`Could not load tools for ${serverName}`);
return;
}
- // Use the ref so we read the most up-to-date list; guard against duplicates
- // that the oauthConnected effect may have already added while we awaited.
if (!selectedServersRef.current.includes(serverName)) {
onChange([...selectedServersRef.current, serverName]);
}
@@ -257,7 +230,6 @@ const MCPAppsPanel: React.FC = ({ accessToken, selectedServers, onChange
}
};
- // Fetch tools for the detail view — server_id must be the UUID
const { data: detailToolsResult, isLoading: loadingTools } = useQuery({
queryKey: ["mcp-apps-panel-detail-tools", detailServer?.server_id],
queryFn: () => listMCPTools(accessToken, detailServer!.server_id),
@@ -276,11 +248,8 @@ const MCPAppsPanel: React.FC = ({ accessToken, selectedServers, onChange
});
const connectedCount = servers.filter((s) => selectedServers.includes(nameOf(s))).length;
-
- // Total tools available across all servers (based on preloaded counts)
const totalTools = Object.values(toolCounts).reduce((sum, n) => sum + n, 0);
- // ── Detail view ──
if (detailServer) {
const name = nameOf(detailServer);
const isConnected = selectedServers.includes(name);
@@ -288,40 +257,23 @@ const MCPAppsPanel: React.FC = ({ accessToken, selectedServers, onChange
const color = getAvatarColor(name);
return (
-
- {/* Back */}
-
+ setDetailServer(null)}
- style={{
- display: "flex",
- alignItems: "center",
- gap: 6,
- background: "none",
- border: "none",
- cursor: "pointer",
- color: "#6b7280",
- fontSize: 13,
- padding: "0 0 20px 0",
- }}
+ className="-ml-3 mb-5 gap-1.5 text-muted-foreground hover:text-foreground"
>
-
+
Back
-
+
- {/* Avatar + name + connect */}
-
+
{detailServer.mcp_info?.logo_url ? (
{
const el = e.target as HTMLImageElement;
el.style.display = "none";
@@ -330,36 +282,27 @@ const MCPAppsPanel: React.FC
= ({ accessToken, selectedServers, onChange
/>
) : null}
{name.charAt(0).toUpperCase()}
-
-
{name}
-
{detailServer.description ?? "MCP server"}
+
+
{name}
+
{detailServer.description ?? "MCP server"}
{detailServer.auth_type === AUTH_TYPE.OAUTH2 ? (
oauthConnected.has(detailServer.server_id) ? (
{
try {
await deleteMCPOAuthUserCredential(accessToken, detailServer.server_id);
} catch (_) {
- // Ignore — credential may already be gone; update UI regardless.
+ // Ignore
}
setOauthConnected((prev) => {
const n = new Set(prev);
@@ -368,7 +311,7 @@ const MCPAppsPanel: React.FC = ({ accessToken, selectedServers, onChange
});
onChangeRef.current(selectedServersRef.current.filter((s) => s !== name));
}}
- style={{ borderRadius: 8, fontWeight: 600, height: 38, minWidth: 110 }}
+ className="font-semibold h-[38px] min-w-[110px]"
>
Disconnect
@@ -384,19 +327,19 @@ const MCPAppsPanel: React.FC
= ({ accessToken, selectedServers, onChange
)
) : (
handleToggle(name, !isConnected, detailServer.server_id)}
- style={{ borderRadius: 8, fontWeight: 600, height: 38, minWidth: 110 }}
+ className="font-semibold h-[38px] min-w-[110px]"
>
+ {isTogglingOn && }
{isConnected ? "Disconnect" : "Connect"}
)}
- {/* Info table */}
- Information
-
+
Information
+
{[
["Server ID", detailServer.server_id],
["Transport", handleTransport(detailServer.transport, detailServer.spec_path)],
@@ -404,66 +347,41 @@ const MCPAppsPanel: React.FC
= ({ accessToken, selectedServers, onChange
]
.filter(([, v]) => v)
.map(([label, value], i, arr) => (
-
-
{label}
-
{value}
+
+ {label}
+ {value}
))}
- {/* Tools section */}
-
-
Available Tools
+
+
Available Tools
{!loadingTools && (
-
+
{detailTools.length}
)}
{loadingTools ? (
-
-
+
+ {Array.from({ length: 3 }, (_, i) => (
+
+
+
+
+ ))}
) : detailTools.length === 0 ? (
-
No tools available
+
No tools available
) : (
-
+
{detailTools.map((tool) => (
-
-
-
-
- {tool.name}
-
+
+
+
+ {tool.name}
- {tool.description && (
-
{tool.description}
- )}
+ {tool.description &&
{tool.description}
}
))}
@@ -472,113 +390,78 @@ const MCPAppsPanel: React.FC
= ({ accessToken, selectedServers, onChange
);
}
- // ── List view ──
return (
-
- {/* Header row */}
-
+
+
-
-
MCP Servers
-
+
+
MCP Servers
+
Beta
-
-
- Browse tools, authenticate once, use in chat — no setup needed.
-
+
+
Browse tools, authenticate once, use in chat
{loadingCounts ? (
-
-
+
+
Loading tools...
) : totalTools > 0 ? (
-
-
+
+
{totalTools} tool{totalTools !== 1 ? "s" : ""} available
) : null}
- }
- placeholder="Search servers..."
- value={query}
- onChange={(e) => setQuery(e.target.value)}
- allowClear
- style={{ width: 220, borderRadius: 8, fontSize: 13 }}
- size="middle"
- />
+
+
+ setQuery(e.target.value)}
+ className="pl-9 text-[13px] h-9"
+ />
+
- {/* Tabs */}
-
- {(["all", "connected"] as TabKey[]).map((tab) => (
- setActiveTab(tab)}
- style={{
- padding: "8px 16px",
- border: "none",
- borderBottom: activeTab === tab ? "2px solid #1677ff" : "2px solid transparent",
- cursor: "pointer",
- fontSize: 13,
- fontWeight: activeTab === tab ? 600 : 400,
- background: "transparent",
- color: activeTab === tab ? "#1677ff" : "#6b7280",
- marginBottom: -1,
- }}
- >
- {tab === "all" ? "All" : `Connected${connectedCount > 0 ? ` (${connectedCount})` : ""}`}
-
- ))}
-
+
setActiveTab(v as TabKey)} className="mb-4">
+
+
+ All
+
+
+ Connected{connectedCount > 0 ? ` (${connectedCount})` : ""}
+
+
+
- {/* Grid */}
{loading ? (
-
-
+
+ {Array.from({ length: 6 }, (_, idx) => (
+
+ ))}
) : filtered.length === 0 ? (
-
+
{servers.length === 0
- ? "No MCP servers configured. Add servers in Tools → MCP Servers."
+ ? "No MCP servers configured. Add servers in Tools -> MCP Servers."
: activeTab === "connected"
? "No servers connected yet."
: "No servers match your search."}
) : (
-
+
{filtered.map((server, idx) => {
const name = nameOf(server);
const isConnected = selectedServers.includes(name);
@@ -590,38 +473,15 @@ const MCPAppsPanel: React.FC
= ({ accessToken, selectedServers, onChange
setDetailServer(server)}
- style={{
- display: "flex",
- alignItems: "center",
- gap: 12,
- padding: "14px 16px",
- background: "#fff",
- borderRight: isLeftCol ? "1px solid #f3f4f6" : "none",
- borderBottom:
- Math.floor(idx / 2) < Math.floor((filtered.length - 1) / 2) ? "1px solid #f3f4f6" : "none",
- cursor: "pointer",
- minWidth: 0,
- transition: "background 0.1s",
- }}
- onMouseEnter={(e) => {
- (e.currentTarget as HTMLDivElement).style.background = "#fafafa";
- }}
- onMouseLeave={(e) => {
- (e.currentTarget as HTMLDivElement).style.background = "#fff";
- }}
+ className={`flex items-center gap-3 p-4 bg-card cursor-pointer transition-colors hover:bg-accent/30 min-w-0 ${
+ isLeftCol ? "border-r" : ""
+ } ${Math.floor(idx / 2) < Math.floor((filtered.length - 1) / 2) ? "border-b" : ""}`}
>
{server.mcp_info?.logo_url ? (
{
const el = e.target as HTMLImageElement;
el.style.display = "none";
@@ -630,68 +490,32 @@ const MCPAppsPanel: React.FC
= ({ accessToken, selectedServers, onChange
/>
) : null}
{name.charAt(0).toUpperCase()}
-
-
- {name}
-
-
-
- {server.description ?? "MCP server"}
-
+
+
{name}
+
+ {server.description ?? "MCP server"}
{count !== undefined ? (
count > 0 ? (
-
- · {count}
+
+ · {count}
) : null
) : loadingCounts ? (
-
+
) : null}
{server.auth_type === AUTH_TYPE.OAUTH2 ? (
oauthConnected.has(server.server_id) ? (
-
+
) : (
= ({ accessToken, selectedServers, onChange
/>
)
) : isConnected ? (
-
+
) : null}
-
+
);
})}
diff --git a/ui/litellm-dashboard/src/components/chat/MCPConnectPicker.tsx b/ui/litellm-dashboard/src/components/chat/MCPConnectPicker.tsx
index 3e13ec9dc87c..abeccb0f0416 100644
--- a/ui/litellm-dashboard/src/components/chat/MCPConnectPicker.tsx
+++ b/ui/litellm-dashboard/src/components/chat/MCPConnectPicker.tsx
@@ -1,5 +1,7 @@
import React, { useEffect, useState } from "react";
-import { Switch, Spin } from "antd";
+import { Loader2 } from "lucide-react";
+import { Switch } from "@/components/ui/switch";
+import { Skeleton } from "@/components/ui/skeleton";
import MessageManager from "@/components/molecules/message_manager";
import { fetchMCPServers, listMCPTools } from "../networking";
import { MCPServer } from "../mcp_tools/types";
@@ -13,7 +15,6 @@ interface Props {
const MCPConnectPicker: React.FC
= ({ accessToken, selectedServers, onChange }) => {
const [servers, setServers] = useState([]);
const [loadingServers, setLoadingServers] = useState(true);
- // Track which individual servers are being toggled on (verifying tools)
const [togglingOn, setTogglingOn] = useState>(new Set());
useEffect(() => {
@@ -24,7 +25,6 @@ const MCPConnectPicker: React.FC = ({ accessToken, selectedServers, onCha
try {
const data = await fetchMCPServers(accessToken);
if (cancelled) return;
- // API returns { data: MCPServer[] } or MCPServer[]
const list: MCPServer[] = Array.isArray(data) ? data : data?.data ?? [];
setServers(list);
} catch {
@@ -47,25 +47,20 @@ const MCPConnectPicker: React.FC = ({ accessToken, selectedServers, onCha
const handleToggle = async (serverName: string, checked: boolean) => {
if (!checked) {
- // Toggle OFF — remove immediately, no tool fetch needed
onChange(selectedServers.filter((s) => s !== serverName));
return;
}
- // Toggle ON — verify tools are reachable first
setTogglingOn((prev) => new Set(prev).add(serverName));
try {
const result = await listMCPTools(accessToken, serverName);
- // listMCPTools never throws; it returns { tools, error, message } on failure
if (result?.error) {
- MessageManager.warning(`Could not load tools for ${serverName} — it will be excluded from this message.`);
- // Do not add to selectedServers
+ MessageManager.warning(`Could not load tools for ${serverName} \u2014 it will be excluded from this message.`);
return;
}
onChange([...selectedServers, serverName]);
} catch {
- MessageManager.warning(`Could not load tools for ${serverName} — it will be excluded from this message.`);
- // Do not add to selectedServers
+ MessageManager.warning(`Could not load tools for ${serverName} \u2014 it will be excluded from this message.`);
} finally {
setTogglingOn((prev) => {
const next = new Set(prev);
@@ -76,22 +71,24 @@ const MCPConnectPicker: React.FC = ({ accessToken, selectedServers, onCha
};
return (
-
+
{loadingServers ? (
-
-
+
+ {Array.from({ length: 3 }).map((_, i) => (
+
+ ))}
) : servers.length === 0 ? (
-
- No MCP servers configured
-
+
No MCP servers configured
) : (
servers.map((server) => {
const name = server.server_name ?? server.alias ?? server.server_id;
@@ -99,67 +96,34 @@ const MCPConnectPicker: React.FC
= ({ accessToken, selectedServers, onCha
const isTogglingOn = togglingOn.has(name);
return (
-
+
{server.mcp_info?.logo_url && (
{
(e.target as HTMLImageElement).style.display = "none";
}}
/>
)}
-
-
- {name}
-
+
+
{name}
{server.description && (
-
- {server.description}
-
+
{server.description}
+ )}
+
+
+ {isTogglingOn ? (
+
+ ) : (
+ handleToggle(name, checked)}
+ className="scale-75"
+ />
)}
-
handleToggle(name, checked)}
- />
);
})
diff --git a/ui/litellm-dashboard/src/components/chat/MCPCredentialsTab.tsx b/ui/litellm-dashboard/src/components/chat/MCPCredentialsTab.tsx
index 3f5d4714d103..f73d18081d82 100644
--- a/ui/litellm-dashboard/src/components/chat/MCPCredentialsTab.tsx
+++ b/ui/litellm-dashboard/src/components/chat/MCPCredentialsTab.tsx
@@ -1,18 +1,24 @@
"use client";
-/**
- * MCPCredentialsTab
- *
- * Shows all OAuth2 MCP connections the calling user has stored.
- * Lives in the Chat sidebar's "Credentials" tab.
- */
-
import React, { useState } from "react";
-import { Spin, Table, Tag } from "antd";
-import type { ColumnsType } from "antd/es/table";
import { useQuery, useQueryClient } from "@tanstack/react-query";
+import { Loader2, Trash2, Link } from "lucide-react";
+import { Badge } from "@/components/ui/badge";
+import { Button } from "@/components/ui/button";
+import { Skeleton } from "@/components/ui/skeleton";
+import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
+import {
+ AlertDialog,
+ AlertDialogAction,
+ AlertDialogCancel,
+ AlertDialogContent,
+ AlertDialogDescription,
+ AlertDialogFooter,
+ AlertDialogHeader,
+ AlertDialogTitle,
+ AlertDialogTrigger,
+} from "@/components/ui/alert-dialog";
import MessageManager from "@/components/molecules/message_manager";
-import { DeleteOutlined, LinkOutlined } from "@ant-design/icons";
import { deleteMCPOAuthUserCredential, listMCPUserCredentials, MCPUserCredentialListItem } from "../networking";
const MCP_CREDENTIALS_QUERY_KEY = "mcp-user-credentials";
@@ -38,21 +44,24 @@ function relativeTime(isoString: string | null | undefined): string {
}
}
-function expiryLabel(isoString: string | null | undefined): string {
- if (!isoString) return "Does not expire";
+function expiryLabel(isoString: string | null | undefined): {
+ text: string;
+ variant: "secondary" | "destructive" | "outline";
+} {
+ if (!isoString) return { text: "Does not expire", variant: "secondary" };
try {
const exp = new Date(isoString);
const diffMs = exp.getTime() - Date.now();
- if (diffMs <= 0) return "Expired";
+ if (diffMs <= 0) return { text: "Expired", variant: "destructive" };
const diffSec = Math.floor(diffMs / 1000);
const diffMin = Math.floor(diffSec / 60);
const diffHr = Math.floor(diffMin / 60);
const diffDay = Math.floor(diffHr / 24);
- if (diffDay > 0) return `Expires in ${diffDay}d`;
- if (diffHr > 0) return `Expires in ${diffHr}h`;
- return `Expires in ${diffMin}m`;
+ if (diffDay > 0) return { text: `Expires in ${diffDay}d`, variant: "outline" };
+ if (diffHr > 0) return { text: `Expires in ${diffHr}h`, variant: "outline" };
+ return { text: `Expires in ${diffMin}m`, variant: "outline" };
} catch {
- return "";
+ return { text: "", variant: "outline" };
}
}
@@ -86,68 +95,132 @@ const MCPCredentialsTab: React.FC
= ({ accessToken }) => {
const displayName = (c: MCPUserCredentialListItem) => c.alias || c.server_name || c.server_id;
- const columns: ColumnsType = [
- {
- title: "App",
- key: "app",
- render: (_, cred) => {displayName(cred)} ,
- },
- {
- title: "Connected",
- key: "connected",
- render: (_, cred) => {relativeTime(cred.connected_at) || "—"} ,
- },
- {
- title: "Status",
- key: "status",
- render: (_, cred) => {
- const exp = expiryLabel(cred.expires_at);
- return {exp} ;
- },
- },
- {
- title: "Actions",
- key: "actions",
- align: "right",
- render: (_, cred) => {
- const isRevoking = revoking.has(cred.server_id);
- return (
- handleRevoke(cred.server_id)}
- disabled={isRevoking}
- title="Revoke connection"
- className={`inline-flex items-center justify-center rounded-md border border-gray-200 px-2 py-1 text-gray-400 hover:text-red-500 hover:border-red-200 transition-colors ${isRevoking ? "opacity-50 cursor-not-allowed" : "cursor-pointer"}`}
- style={{ background: "none" }}
- >
- {isRevoking ? : }
-
- );
- },
- },
- ];
-
return (
- {/* Header */}
-
App Credentials
-
Your stored OAuth connections — used automatically in chat.
+
App Credentials
+
Your stored OAuth connections; used automatically in chat
{loading ? (
-
-
+
+
+
+
+
+ App
+
+
+ Connected
+
+
+ Status
+
+
+ Actions
+
+
+
+
+ {Array.from({ length: 3 }, (_, i) => (
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ ))}
+
+
) : credentials.length === 0 ? (
-
-
- No connections yet.
-
- Go to
Apps and click
Connect to authorize an MCP server.
+
+
+
No connections yet
+
+ Go to Integrations and click{" "}
+ Connect to authorize an MCP server
+
) : (
-
-
+
+
+
+
+
+ App
+
+
+ Connected
+
+
+ Status
+
+
+ Actions
+
+
+
+
+ {credentials.map((cred) => {
+ const isRevoking = revoking.has(cred.server_id);
+ const exp = expiryLabel(cred.expires_at);
+ return (
+
+ {displayName(cred)}
+
+ {relativeTime(cred.connected_at) || "\u2014"}
+
+
+ {exp.text}
+
+
+
+
+
+ {isRevoking ? (
+
+ ) : (
+
+ )}
+
+
+
+
+ Revoke connection?
+
+ This removes the stored OAuth credential for {displayName(cred)}. You'll need to
+ reconnect to use it in chat again.
+
+
+
+ Cancel
+ handleRevoke(cred.server_id)}>
+ Revoke
+
+
+
+
+
+
+ );
+ })}
+
+
)}
diff --git a/ui/litellm-dashboard/src/components/chat/UsagePanel.tsx b/ui/litellm-dashboard/src/components/chat/UsagePanel.tsx
new file mode 100644
index 000000000000..578e389571fd
--- /dev/null
+++ b/ui/litellm-dashboard/src/components/chat/UsagePanel.tsx
@@ -0,0 +1,204 @@
+"use client";
+
+import React, { useState } from "react";
+import { BarChart3 } from "lucide-react";
+import { useQuery } from "@tanstack/react-query";
+import { userDailyActivityAggregatedCall } from "../networking";
+import { Button } from "@/components/ui/button";
+import { Skeleton } from "@/components/ui/skeleton";
+
+const USAGE_QUERY_KEY = "chat-user-usage";
+
+interface Props {
+ accessToken: string;
+ userId: string;
+}
+
+type TimeRange = "7d" | "30d" | "90d";
+
+function getDateRange(range: TimeRange): { start: Date; end: Date } {
+ const end = new Date();
+ const start = new Date();
+ const days = range === "7d" ? 7 : range === "30d" ? 30 : 90;
+ start.setDate(end.getDate() - days);
+ return { start, end };
+}
+
+interface DailyMetrics {
+ spend: number;
+ prompt_tokens: number;
+ completion_tokens: number;
+ total_tokens: number;
+ api_requests: number;
+ successful_requests: number;
+ failed_requests: number;
+}
+
+interface DailySpendEntry {
+ date: string;
+ metrics: DailyMetrics;
+}
+
+interface UsageMetadata {
+ total_spend: number;
+ total_prompt_tokens: number;
+ total_completion_tokens: number;
+ total_tokens: number;
+ total_api_requests: number;
+ total_successful_requests: number;
+ total_failed_requests: number;
+}
+
+interface UsageResponse {
+ results: DailySpendEntry[];
+ metadata: UsageMetadata;
+}
+
+function formatNumber(n: number): string {
+ if (n >= 1_000_000) return `${(n / 1_000_000).toFixed(1)}M`;
+ if (n >= 1_000) return `${(n / 1_000).toFixed(1)}K`;
+ return n.toLocaleString();
+}
+
+function SparklineBar({ data, maxVal }: { data: number[]; maxVal: number }) {
+ const barWidth = Math.max(2, Math.floor(200 / Math.max(data.length, 1)));
+ const height = 48;
+ return (
+
+ {data.map((val, i) => {
+ const h = maxVal > 0 ? Math.max(2, (val / maxVal) * height) : 2;
+ return (
+
+ );
+ })}
+
+ );
+}
+
+const TIME_RANGE_OPTIONS: { value: TimeRange; label: string }[] = [
+ { value: "7d", label: "7d" },
+ { value: "30d", label: "30d" },
+ { value: "90d", label: "90d" },
+];
+
+const UsagePanel: React.FC
= ({ accessToken, userId }) => {
+ const [timeRange, setTimeRange] = useState("30d");
+ const { start, end } = getDateRange(timeRange);
+
+ const { data, isLoading } = useQuery({
+ queryKey: [USAGE_QUERY_KEY, accessToken, userId, timeRange],
+ queryFn: () => userDailyActivityAggregatedCall(accessToken, start, end, userId),
+ enabled: !!accessToken,
+ });
+
+ const usage = data as UsageResponse | undefined;
+ const meta = usage?.metadata;
+ const dailyData = usage?.results ?? [];
+ const dailySpend = dailyData.map((d) => d.metrics.spend);
+ const dailyRequests = dailyData.map((d) => d.metrics.api_requests);
+ const maxSpend = Math.max(...dailySpend, 0);
+ const maxRequests = Math.max(...dailyRequests, 0);
+
+ const statCards: Array<{ label: string; value: string; sub?: string; subVariant?: "error" }> = meta
+ ? [
+ { label: "Total Spend", value: `$${meta.total_spend.toFixed(2)}` },
+ { label: "API Requests", value: formatNumber(meta.total_api_requests) },
+ {
+ label: "Tokens Used",
+ value: formatNumber(meta.total_tokens),
+ sub: `${formatNumber(meta.total_prompt_tokens)} in / ${formatNumber(meta.total_completion_tokens)} out`,
+ },
+ {
+ label: "Success Rate",
+ value:
+ meta.total_api_requests > 0
+ ? `${((meta.total_successful_requests / meta.total_api_requests) * 100).toFixed(1)}%`
+ : "N/A",
+ sub: meta.total_failed_requests > 0 ? `${meta.total_failed_requests} failed` : undefined,
+ subVariant: meta.total_failed_requests > 0 ? "error" : undefined,
+ },
+ ]
+ : [];
+
+ return (
+
+
+
+
Your Usage
+
Spend and request activity
+
+
+ {TIME_RANGE_OPTIONS.map((opt) => (
+ setTimeRange(opt.value)}
+ >
+ {opt.label}
+
+ ))}
+
+
+
+ {isLoading ? (
+
+ {[...Array(4)].map((_, i) => (
+
+
+
+
+ ))}
+
+ ) : !meta || meta.total_api_requests === 0 ? (
+
+
+ No usage data for this period
+
+ ) : (
+
+
+ {statCards.map((card) => (
+
+
{card.label}
+
{card.value}
+ {card.sub && (
+
+ {card.sub}
+
+ )}
+
+ ))}
+
+
+ {dailyData.length > 1 && (
+
+ )}
+
+ )}
+
+ );
+};
+
+export default UsagePanel;
diff --git a/ui/litellm-dashboard/src/components/chat/design.md b/ui/litellm-dashboard/src/components/chat/design.md
new file mode 100644
index 000000000000..498f9d1e84ea
--- /dev/null
+++ b/ui/litellm-dashboard/src/components/chat/design.md
@@ -0,0 +1,376 @@
+# Chat UI Design Reference
+
+Tactical guide for building chat UI features. Copy patterns exactly — don't improvise spacing, colors, or components.
+
+> **Agents:** Read `AGENTS.md` alongside this file. It contains decision trees, the pre-commit checklist, and the rules that govern when to use each pattern here. This file is the _what_; `AGENTS.md` is the _when and how_.
+
+---
+
+## Stack
+
+- **Next.js 16** App Router, TypeScript
+- **Tailwind CSS v4** — utility classes only, no custom CSS except in `globals.css`
+- **shadcn/ui** — import from `@/components/ui/*`. Available today: `alert-dialog`, `badge`, `button`, `collapsible`, `dialog`, `input`, `label`, `popover`, `scroll-area`, `select`, `separator`, `skeleton`, `switch`, `table`, `tabs`, `tooltip`. **Not installed**: `Card`, `Textarea`, `sonner`. Don't reference them until they're actually added — see "Known gaps" below.
+- **lucide-react** — only icon library, no emoji in UI
+- System font stack (`-apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif`), inherited from `ChatShell`'s root
+
+---
+
+## Tokens
+
+Never hardcode hex values. Use these CSS variables via Tailwind classes — all verified present in `src/app/globals.css`.
+
+### Colors
+
+| Token | Tailwind class | Use |
+| ----------------------------- | ------------------------------------- | -------------------------------------------------------------- |
+| `--background` | `bg-background` | Main content area, input surfaces |
+| `--foreground` | `text-foreground` | Primary text |
+| `--card` | `bg-card` | Popover/dialog surfaces (no `` component yet — see gaps) |
+| `--muted` | `bg-muted` | Table header rows, subtle fills |
+| `--muted-foreground` | `text-muted-foreground` | Secondary/helper text, timestamps |
+| `--border` | `border-border` (or bare `border`) | All 1px separators |
+| `--primary` | `bg-primary` / `text-primary` | Send button, checkmarks, active links |
+| `--destructive` | `bg-destructive` / `text-destructive` | Delete, error actions |
+| `--sidebar` | `bg-sidebar` | **Left sidebar background — use this, not `bg-secondary`** |
+| `--sidebar-foreground` | `text-sidebar-foreground` | Sidebar text |
+| `--sidebar-accent` | `bg-sidebar-accent` | Active/hover nav item fill |
+| `--sidebar-accent-foreground` | `text-sidebar-accent-foreground` | Active nav item text |
+| `--sidebar-border` | `border-sidebar-border` | Sidebar's own dividers/right border |
+
+**Known gotcha — verified in `globals.css`:** `--accent`, `--secondary`, and `--muted` all resolve to the _identical_ OKLCH value in both light and dark themes. Using `bg-accent` for a "selected" state against a `bg-secondary` container is **invisible** — there is zero contrast. This bit us repeatedly in this exact sidebar. Rules:
+
+- Sidebar container: `bg-sidebar`, never `bg-secondary` or `bg-accent`.
+- Active/selected nav item: `bg-sidebar-accent text-sidebar-accent-foreground`, never `bg-accent` on its own inside the sidebar.
+- Anywhere else `bg-accent`/`bg-muted` is used for hover/selected state, confirm the container isn't _also_ `bg-accent`/`bg-secondary`/`bg-muted` before shipping — check `globals.css` values, don't assume.
+
+### Status colors (semantic — don't substitute)
+
+| State | Class | Use |
+| ------------------- | -------------------------------------------------------- | --------------------------- |
+| Success / connected | `text-emerald-600 dark:text-emerald-400` | Completed, connected, ready |
+| Running / warning | `text-amber-600 dark:text-amber-400` | In-flight, expiring |
+| Error | `text-red-600 dark:text-red-400` (or `text-destructive`) | Failed, expired |
+| Info | `text-muted-foreground` | Informational |
+
+---
+
+## Typography
+
+```tsx
+// Page/greeting heading
+Good afternoon
+
+// Section heading (panel titles: "Your API Keys", "Your Usage")
+Your Usage
+
+// Body text
+Body
+
+// Secondary / helper text
+Helper
+
+// Table header
+Col
+
+// Monospace (keys, IDs, JSON, tool args)
+sk-...abcd
+```
+
+**Rules:**
+
+- Use `tracking-tight` on headings
+- Never set `text-foreground/50` or `text-foreground/70` for secondary text — use `text-muted-foreground`
+- Monospace for: masked keys, conversation/tool-call IDs, tool arguments, JSON values
+
+---
+
+## Spacing
+
+4px base grid.
+
+| Context | Value |
+| ---------------------------------- | ------------------------------------------- |
+| Sidebar outer padding | `p-2` (8px) |
+| Nav item padding | `px-2.5 py-2` |
+| Inline icon-to-label gap | `gap-2.5` in nav items, `gap-1.5` elsewhere |
+| Section divider margin | `mx-2` |
+| Panel content padding | `px-8 py-8` |
+| Card/bordered-div internal padding | `p-4` |
+| Dialog body padding | `px-6 pb-6` |
+
+---
+
+## Border Radius
+
+```tsx
+rounded-md // 8px — buttons, inputs, nav items, bordered divs
+rounded-lg // 10px — panel cards, table containers
+rounded-xl // 14px — chat input composer
+rounded-2xl // 16px — chat message bubbles
+rounded-full // pills, avatars, status dots
+```
+
+---
+
+## Components
+
+### Button
+
+Always the shadcn `Button` — never a raw `` with hand-rolled Tailwind, even for icon-only triggers. If it's borderline whether something is a "button" (e.g. a nav row, a suggestion pill), it still gets a `variant`.
+
+```tsx
+import { Button } from "@/components/ui/button"
+
+Send
+Cancel
+Nav item / low-emphasis
+Delete
+
+
+// Loading
+
+ {loading && }
+ Save
+
+```
+
+Sizes: `default` (h-9), `sm` (h-8), `xs` (h-6), `lg` (h-10), `icon` (size-9), `icon-sm` (size-8), `icon-xs` (size-6).
+
+### Sidebar nav item
+
+No dedicated shadcn `Sidebar` block is installed (see gaps). Build nav items from `Button variant="ghost"`, full width, left-aligned, with the sidebar-specific active state:
+
+```tsx
+
+
+ {label}
+
+```
+
+There is no collapsible/icon-rail sidebar mode — it was removed (added complexity, no real use case, and its collapse toggle button had nowhere sensible to live). Don't reintroduce collapse state without a concrete reason.
+
+### ScrollArea
+
+**Known gotcha — cost real debugging time:** a `ScrollArea` won't actually scroll if its container is sized with `max-height` instead of `height`, even though the box _looks_ correctly capped. Radix's `ScrollArea` viewport is `size-full` (`height: 100%`), and CSS percentage-height resolution requires the ancestor chain to have a genuinely _definite_ height — `max-height` on a flex container doesn't count as definite for this purpose, even though the browser renders the box at the capped size. The result: the viewport silently grows to its full content height instead of 100% of the visible box, `scrollHeight === clientHeight` is reported (no overflow, so no scrollbar), and scroll events fall through to whatever's behind the popover/panel instead of scrolling the list.
+
+```tsx
+// Wrong — looks capped, doesn't scroll (max-height isn't a definite height)
+
+ {items}
+
+
+// Right — explicit height propagates as definite through the whole chain
+
+ {items}
+
+```
+
+If you need "shrink to fit content, cap at N px" rather than "always N px," you cannot get both with pure CSS here — pick the fixed height (the common case: any list that can realistically exceed the cap, e.g. a model picker with hundreds of entries) over one that only works when short.
+
+### Input / Textarea
+
+`Input` exists; `Textarea` does not (see gaps — until added, a plain `