The fastest, litest AI Gateway. Rust core with Python SDK. Call 100+ LLM APIs in OpenAI (or native) format with cost tracking, guardrails, load balancing, and logging [Bedrock, Azure, OpenAI, Anthropic, OpenAI, VertexAI, vLLM, Nvidia NIM]
Python ai-gatewayanthropicazure-openaibedrockgatewaylangchainlitellmllmllm-gatewayllmopsmcp-gatewayopenaiopenai-proxyrustrust-aivertex-ai
refactor(ui): remove unreachable /chat page (#30178)
ryan-crabbe-berrie5a3083c2e21
diff --git a/ui/litellm-dashboard/eslint-suppressions.json b/ui/litellm-dashboard/eslint-suppressions.jsonindex 6dc9be0fc90..369efb7e338 100644--- a/ui/litellm-dashboard/eslint-suppressions.json+++ b/ui/litellm-dashboard/eslint-suppressions.json@@ -860,48 +860,6 @@"count": 1}},- "src/components/chat/ChatMessages.tsx": {- "react-hooks/refs": {- "count": 1- }- },- "src/components/chat/ChatPage.tsx": {- "max-params": {- "count": 2- },- "react-hooks/set-state-in-effect": {- "count": 2- },- "unused-imports/no-unused-imports": {- "count": 1- }- },- "src/components/chat/ConversationList.tsx": {- "react-hooks/set-state-in-effect": {- "count": 1- }- },- "src/components/chat/MCPAppsPanel.tsx": {- "max-nested-callbacks": {- "count": 2- },- "react-hooks/set-state-in-effect": {- "count": 2- }- },- "src/components/chat/MCPCredentialsTab.tsx": {- "no-restricted-imports": {- "count": 1- },- "react-hooks/set-state-in-effect": {- "count": 1- }- },- "src/components/chat/useChatHistory.ts": {- "react-hooks/set-state-in-effect": {- "count": 3- }- },"src/components/claude_code_plugins.tsx": {"no-restricted-imports": {"count": 1diff --git a/ui/litellm-dashboard/src/app/chat/page.tsx b/ui/litellm-dashboard/src/app/chat/page.tsxdeleted file mode 100644index 5046f162877..00000000000--- a/ui/litellm-dashboard/src/app/chat/page.tsx+++ /dev/null@@ -1,27 +0,0 @@-"use client";--import { Suspense } from "react";-import useAuthorized from "@/app/(dashboard)/hooks/useAuthorized";-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();-- return (- <ChatPage- accessToken={accessToken ?? ""}- userRole={userRole ?? ""}- userId={userId ?? ""}- userEmail={userEmail ?? ""}- />- );-};--const ChatPageRoute = () => (- <Suspense>- <ChatPageContent />- </Suspense>-);--export default ChatPageRoute;diff --git a/ui/litellm-dashboard/src/components/chat/ChatMessages.tsx b/ui/litellm-dashboard/src/components/chat/ChatMessages.tsxdeleted file mode 100644index 53877be1737..00000000000--- a/ui/litellm-dashboard/src/components/chat/ChatMessages.tsx+++ /dev/null@@ -1,590 +0,0 @@-"use client";--import { ToolOutlined, CopyOutlined, CheckOutlined, EditOutlined } from "@ant-design/icons";-import { Collapse, Tooltip } from "antd";-import React, { useEffect, useRef, useState } from "react";-import ReactMarkdown from "react-markdown";-import remarkGfm from "remark-gfm";-import { Prism as SyntaxHighlighter } from "react-syntax-highlighter";-import { coy } from "react-syntax-highlighter/dist/esm/styles/prism";-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<string, unknown>): Record<string, unknown> {- const result: Record<string, unknown> = {};- for (const [k, v] of Object.entries(obj)) {- if (REDACTED_KEY_PATTERNS.test(k)) {- result[k] = "[redacted]";- } else if (Array.isArray(v)) {- result[k] = v.map((item) =>- item !== null && typeof item === "object" && !Array.isArray(item)- ? redactSensitiveValues(item as Record<string, unknown>)- : item,- );- } else if (v !== null && typeof v === "object") {- result[k] = redactSensitiveValues(v as Record<string, unknown>);- } else {- result[k] = v;- }- }- return result;-}--function formatTimestamp(ts: number): string {- const d = new Date(ts);- const hh = String(d.getHours()).padStart(2, "0");- const mm = String(d.getMinutes()).padStart(2, "0");- 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,- children,- ...props-}: React.ComponentPropsWithoutRef<"code"> & { node?: unknown }) {- const match = /language-(\w+)/.exec(className || "");- return match ? (- <SyntaxHighlighter- style={coy as Record<string, React.CSSProperties>}- language={match[1]}- PreTag="div"- className="rounded-md my-2"- {...(props as Record<string, unknown>)}- >- {String(children).replace(/\n$/, "")}- </SyntaxHighlighter>- ) : (- <code className={`${className ?? ""} px-1.5 py-0.5 rounded bg-gray-100 text-sm font-mono`} {...props}>- {children}- </code>- );-}--// ------- Sub-components ---------interface UserBubbleProps {- message: ChatMessage;- onEdit?: (messageId: string, newContent: string) => void;- isStreaming?: boolean;-}--function UserBubble({ message, onEdit, isStreaming }: UserBubbleProps) {- const [hovered, setHovered] = useState(false);- const [editing, setEditing] = useState(false);- const [editValue, setEditValue] = useState(message.content);- const textareaRef = useRef<HTMLTextAreaElement>(null);-- useEffect(() => {- if (editing && textareaRef.current) {- textareaRef.current.focus();- textareaRef.current.selectionStart = textareaRef.current.value.length;- }- }, [editing]);-- // Auto-resize textarea- useEffect(() => {- const ta = textareaRef.current;- if (!ta) return;- ta.style.height = "auto";- ta.style.height = `${ta.scrollHeight}px`;- }, [editValue, editing]);-- const handleSave = () => {- const trimmed = editValue.trim();- if (trimmed && trimmed !== message.content && onEdit) {- onEdit(message.id, trimmed);- }- setEditing(false);- };-- const handleKeyDown = (e: React.KeyboardEvent<HTMLTextAreaElement>) => {- if (e.key === "Enter" && !e.shiftKey) {- e.preventDefault();- handleSave();- }- if (e.key === "Escape") {- setEditValue(message.content);- setEditing(false);- }- };-- if (editing) {- return (- <div style={{ display: "flex", flexDirection: "column", alignItems: "flex-end" }}>- <div- style={{- width: "72%",- background: "#fff",- border: "1.5px solid #1677ff",- borderRadius: 12,- overflow: "hidden",- boxShadow: "0 0 0 3px rgba(22,119,255,0.1)",- }}- >- <textarea- ref={textareaRef}- value={editValue}- onChange={(e) => setEditValue(e.target.value)}- onKeyDown={handleKeyDown}- style={{- width: "100%",- padding: "10px 14px",- border: "none",- outline: "none",- resize: "none",- fontSize: 14,- lineHeight: "1.6",- color: "#111827",- fontFamily: "inherit",- background: "transparent",- boxSizing: "border-box",- minHeight: 40,- }}- />- <div- style={{- display: "flex",- justifyContent: "flex-end",- gap: 8,- padding: "6px 10px 8px",- borderTop: "1px solid #f0f0f0",- }}- >- <button- onClick={() => {- setEditValue(message.content);- setEditing(false);- }}- style={{- padding: "4px 12px",- borderRadius: 6,- border: "1px solid #d1d5db",- background: "#fff",- color: "#374151",- fontSize: 13,- cursor: "pointer",- }}- >- Cancel- </button>- <button- onClick={handleSave}- disabled={!editValue.trim()}- style={{- padding: "4px 12px",- borderRadius: 6,- border: "none",- background: editValue.trim() ? "#1677ff" : "#f3f4f6",- color: editValue.trim() ? "#fff" : "#9ca3af",- fontSize: 13,- fontWeight: 500,- cursor: editValue.trim() ? "pointer" : "not-allowed",- }}- >- Save & Send- </button>- </div>- </div>- </div>- );- }-- return (- <div- style={{ display: "flex", flexDirection: "column", alignItems: "flex-end", width: "100%" }}- onMouseEnter={() => setHovered(true)}- onMouseLeave={() => setHovered(false)}- >- <div style={{ display: "flex", alignItems: "flex-end", gap: 6, maxWidth: "72%" }}>- {/* Edit button — appears on hover, to the left of the bubble */}- {hovered && !isStreaming && onEdit && (- <Tooltip title="Edit message">- <button- onClick={() => {- 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";- }}- >- <EditOutlined />- </button>- </Tooltip>- )}- <div- style={{- backgroundColor: "#f0f2f5",- borderRadius: 16,- padding: "10px 14px",- fontSize: 14,- lineHeight: "1.6",- whiteSpace: "pre-wrap",- wordBreak: "break-word",- color: "#111827",- }}- >- {message.content}- </div>- </div>- <span style={{ fontSize: 11, color: "#9ca3af", marginTop: 4 }}>{formatTimestamp(message.timestamp)}</span>- </div>- );-}--interface AssistantBubbleProps {- message: ChatMessage;- 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) {- // Ref to control ReasoningContent collapse on streaming end.- // ReasoningContent manages its own expanded state; we use a key to- // remount it (collapsed by default) when streaming finishes.- const reasoningKeyRef = useRef<number>(0);- const prevStreamingRef = useRef<boolean>(isStreaming);-- useEffect(() => {- if (prevStreamingRef.current && !isStreaming) {- // Streaming just stopped — bump the key to remount ReasoningContent- // with isExpanded default (false won't work since it starts expanded).- // ReasoningContent always starts expanded on mount; we accept that- // behaviour and leave collapse-on-finish as a best-effort remount.- reasoningKeyRef.current += 1;- }- prevStreamingRef.current = isStreaming;- }, [isStreaming]);-- const showReasoningPlaceholder = isLastMessage && isStreaming && !message.reasoningContent;-- const showReasoning = !!message.reasoningContent || showReasoningPlaceholder;-- if (isTypingIndicator) {- return (- <div style={{ display: "flex", flexDirection: "column", alignItems: "flex-start" }}>- <div style={{ display: "flex", alignItems: "center", gap: 4, padding: "10px 4px" }}>- <TypingDots />- </div>- </div>- );- }-- // Split content at trailing "[stopped]"- let mainContent = message.content;- let stoppedSuffix = false;- if (mainContent.endsWith("[stopped]")) {- mainContent = mainContent.slice(0, -"[stopped]".length);- stoppedSuffix = true;- }-- return (- <div style={{ display: "flex", flexDirection: "column", alignItems: "flex-start", maxWidth: "80%" }}>- {showReasoning &&- (showReasoningPlaceholder ? (- <ThinkingPlaceholder />- ) : (- <ReasoningContent key={reasoningKeyRef.current} reasoningContent={message.reasoningContent!} />- ))}-- <div- style={{- fontSize: 14,- lineHeight: "1.7",- color: "#111827",- wordBreak: "break-word",- }}- >- <ReactMarkdown- remarkPlugins={[remarkGfm]}- components={{- code: MarkdownCodeRenderer as React.ComponentType<React.ComponentPropsWithoutRef<"code">>,- }}- >- {mainContent}- </ReactMarkdown>- {stoppedSuffix && <span style={{ color: "#9ca3af", fontStyle: "italic" }}> [stopped]</span>}- </div>-- <CopyButton text={mainContent} />- {mcpEvents && mcpEvents.length > 0 && (- <div style={{ marginTop: 8, maxWidth: "100%" }}>- <MCPEventsDisplay events={mcpEvents} />- </div>- )}- </div>- );-}--function CopyButton({ text }: { text: string }) {- const [copied, setCopied] = useState(false);-- const handleCopy = () => {- navigator.clipboard- .writeText(text)- .then(() => {- setCopied(true);- setTimeout(() => setCopied(false), 2000);- })- .catch(() => {- // clipboard not available (non-HTTPS or permission denied) — silently no-op- });- };-- return (- <div style={{ display: "flex", alignItems: "center", gap: 4, marginTop: 6 }}>- <Tooltip title={copied ? "Copied!" : "Copy"}>- <button- onClick={handleCopy}- style={{- background: "none",- border: "none",- cursor: "pointer",- padding: "4px 6px",- borderRadius: 5,- color: copied ? "#52c41a" : "#9ca3af",- fontSize: 13,- display: "flex",- alignItems: "center",- gap: 4,- transition: "color 0.15s",- }}- onMouseEnter={(e) => {- if (!copied) (e.currentTarget as HTMLButtonElement).style.color = "#6b7280";- }}- onMouseLeave={(e) => {- if (!copied) (e.currentTarget as HTMLButtonElement).style.color = "#9ca3af";- }}- >- {copied ? <CheckOutlined /> : <CopyOutlined />}- </button>- </Tooltip>- </div>- );-}--function ThinkingPlaceholder() {- return (- <>- <style>{`- @keyframes thinking-pulse {- 0%, 100% { opacity: 0.4; }- 50% { opacity: 1; }- }- .chat-thinking-text {- animation: thinking-pulse 1.4s ease-in-out infinite;- }- `}</style>- <div- style={{- display: "inline-flex",- alignItems: "center",- gap: 6,- padding: "4px 10px",- marginBottom: 8,- backgroundColor: "#f9fafb",- border: "1px solid #e5e7eb",- borderRadius: 8,- fontSize: 12,- color: "#6b7280",- }}- >- <span className="chat-thinking-text">Thinking...</span>- </div>- </>- );-}--function TypingDots() {- return (- <>- <style>{`- @keyframes chat-typing-bounce {- 0%, 60%, 100% { transform: translateY(0); opacity: 0.4; }- 30% { transform: translateY(-4px); opacity: 1; }- }- .chat-dot {- width: 7px;- height: 7px;- border-radius: 50%;- background-color: #9ca3af;- animation: chat-typing-bounce 1.2s ease-in-out infinite;- }- .chat-dot:nth-child(2) { animation-delay: 0.2s; }- .chat-dot:nth-child(3) { animation-delay: 0.4s; }- `}</style>- <div className="chat-dot" />- <div className="chat-dot" />- <div className="chat-dot" />- </>- );-}--interface ToolCardProps {- message: ChatMessage;-}--function ToolCard({ message }: ToolCardProps) {- const redactedArgs = message.toolArgs ? redactSensitiveValues(message.toolArgs) : undefined;-- return (- <div style={{ maxWidth: "80%" }}>- <Collapse- size="small"- style={{- backgroundColor: "#fafafa",- border: "1px solid #e5e7eb",- borderRadius: 8,- }}- >- <Panel- header={- <span style={{ display: "flex", alignItems: "center", gap: 6, fontSize: 13 }}>- <ToolOutlined style={{ color: "#6b7280" }} />- <span style={{ color: "#374151", fontWeight: 500 }}>{message.toolName ?? "Tool call"}</span>- </span>- }- key="tool"- >- {redactedArgs !== undefined && (- <div style={{ marginBottom: message.toolResult ? 12 : 0 }}>- <div- style={{- fontSize: 11,- fontWeight: 600,- textTransform: "uppercase",- letterSpacing: "0.05em",- color: "#9ca3af",- marginBottom: 4,- }}- >- Arguments- </div>- <pre- style={{- margin: 0,- padding: "8px 10px",- backgroundColor: "#f3f4f6",- borderRadius: 6,- fontSize: 12,- fontFamily:- 'ui-monospace, SFMono-Regular, "SF Mono", Monaco, Consolas, "Liberation Mono", "Courier New", monospace',- whiteSpace: "pre-wrap",- wordBreak: "break-word",- color: "#374151",- }}- >- {JSON.stringify(redactedArgs, null, 2)}- </pre>- </div>- )}-- {message.toolResult && (- <div>- <div- style={{- fontSize: 11,- fontWeight: 600,- textTransform: "uppercase",- letterSpacing: "0.05em",- color: "#9ca3af",- marginBottom: 4,- }}- >- Result- </div>- <div- style={{- fontSize: 13,- color: "#374151",- whiteSpace: "pre-wrap",- wordBreak: "break-word",- fontFamily:- 'ui-monospace, SFMono-Regular, "SF Mono", Monaco, Consolas, "Liberation Mono", "Courier New", monospace',- }}- >- {message.toolResult}- </div>- </div>- )}- </Panel>- </Collapse>- <div style={{ fontSize: 11, color: "#9ca3af", marginTop: 4 }}>{formatTimestamp(message.timestamp)}</div>- </div>- );-}--// ------- Main component ---------interface Props {- messages: ChatMessage[];- isStreaming: boolean;- onEditMessage?: (messageId: string, newContent: string) => void;-}--const ChatMessages: React.FC<Props> = ({ 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 (- <div style={{ display: "flex", flexDirection: "column", gap: 16 }}>- {messages.map((msg, idx) => {- const isLastMessage = idx === lastIndex;-- if (msg.role === "user") {- return <UserBubble key={msg.id} message={msg} onEdit={onEditMessage} isStreaming={isStreaming} />;- }-- if (msg.role === "tool") {- return <ToolCard key={msg.id} message={msg} />;- }-- // assistant- return (- <AssistantBubble- key={msg.id}- message={msg}- isLastMessage={isLastMessage}- isStreaming={isStreaming}- isTypingIndicator={isLastMessage && isTypingIndicator}- mcpEvents={msg.mcpEvents}- />- );- })}- </div>- );-};--export default ChatMessages;diff --git a/ui/litellm-dashboard/src/components/chat/ChatPage.tsx b/ui/litellm-dashboard/src/components/chat/ChatPage.tsxdeleted file mode 100644index 2a7fdb75eb8..00000000000--- a/ui/litellm-dashboard/src/components/chat/ChatPage.tsx+++ /dev/null@@ -1,1512 +0,0 @@-"use client";--import React, { useCallback, useEffect, useRef, useState, useLayoutEffect } from "react";-import { Tooltip, Skeleton, Popover } from "antd";-import MessageManager from "@/components/molecules/message_manager";-import {- SettingOutlined,- PlusOutlined,- EditOutlined,- MenuFoldOutlined,- MenuUnfoldOutlined,- SearchOutlined,- MessageOutlined,- AppstoreOutlined,- KeyOutlined,- ArrowLeftOutlined,- DownOutlined,- CloseOutlined,- CheckOutlined,-} from "@ant-design/icons";-import ReactMarkdown from "react-markdown";-import remarkGfm from "remark-gfm";-import { useRouter, useSearchParams } from "next/navigation";-import { useChatHistory } from "./useChatHistory";-import ConversationList from "./ConversationList";-import ChatMessages from "./ChatMessages";-import MCPConnectPicker from "./MCPConnectPicker";-import MCPAppsPanel from "./MCPAppsPanel";-import MCPCredentialsTab from "./MCPCredentialsTab";-import { fetchAvailableModels } from "@/components/llm_calls/fetch_models";-import { makeOpenAIChatCompletionRequest } from "@/components/llm_calls/chat_completion";-import { makeOpenAIResponsesRequest } from "@/components/llm_calls/responses_api";-import type { MCPEvent } from "./types";-import { getProxyBaseUrl } from "@/components/networking";-import { useUIConfig } from "@/app/(dashboard)/hooks/uiConfig/useUIConfig";-import { getProviderLogoAndName } from "@/components/provider_info_helpers";--interface ChatPageProps {- accessToken: string;- userRole: string;- userId: string;- userEmail?: string;-}--const SUGGESTIONS = ["Write", "Learn", "Code", "Brainstorm"];-const MAX_COMPARISON_MODELS = 3;-const LOCALSTORAGE_MODEL_KEY = "litellm_chat_selected_models";--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";-}--// 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 {- const base = process.env.NEXT_PUBLIC_BASE_URL ?? "";- const trimmed = base.replace(/^\/+|\/+$/g, "");- return trimmed ? `${root}/${trimmed}/` : `${root}/`;-}--// 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<string, string>; // model → accumulated response text-}--// Module-level async helper — each model gets its own independent Promise so they all run in parallel.-async function streamToModel(- 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,-): Promise<void> {- 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<ChatPageProps> = ({ accessToken, userRole, userId, userEmail }) => {- const router = useRouter();- const searchParams = useSearchParams();- const activeConversationId = searchParams.get("id");- 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<string[]>([]);- const [models, setModels] = useState<string[]>([]);- const [isLoadingModels, setIsLoadingModels] = useState(true);- const [modelSelectorOpen, setModelSelectorOpen] = useState(false);- const [modelSearchText, setModelSearchText] = useState("");-- const [selectedMCPServers, setSelectedMCPServers] = useState<string[]>([]);- const [responsesSessionId, setResponsesSessionId] = useState<string | null>(null);- 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<ComparisonExchange[]>([]);- const [comparisonStreamingSet, setComparisonStreamingSet] = useState<Set<string>>(new Set());- const comparisonAbortControllersRef = useRef<Record<string, AbortController>>({});-- const abortControllerRef = useRef<AbortController | null>(null);- const textareaRef = useRef<HTMLTextAreaElement>(null);- const messagesScrollRef = useRef<HTMLDivElement>(null);- const [showScrollButton, setShowScrollButton] = useState(false);- const streamScrollLock = useRef<number | null>(null);-- const {- conversations,- activeConversation,- storageUnavailable,- staleId,- createConversation,- appendMessage,- updateLastAssistantMessage,- truncateFromMessage,- deleteConversation,- renameConversation,- } = useChatHistory(activeConversationId);-- // 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;- setIsLoadingModels(true);- 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(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]);-- // Reset the responses session when switching between conversations so that- // previous_response_id from conversation A is never sent for conversation B.- useEffect(() => {- setResponsesSessionId(null);- }, [activeConversationId]);-- 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,- ],- );-- 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<string, AbortController> = {};- 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,- history,- accessToken,- selectedMCPServers,- controllers[model].signal,- (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;- }),- (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<HTMLTextAreaElement>) => {- 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 = (- <div style={{ width: 280, maxHeight: 400, display: "flex", flexDirection: "column" }}>- <div style={{ padding: "8px 8px 4px" }}>- <input- autoFocus- value={modelSearchText}- onChange={(e) => 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",- }}- />- </div>- {selectedModels.length >= MAX_COMPARISON_MODELS && (- <div style={{ padding: "4px 12px", fontSize: 12, color: "#6b7280" }}>- Max {MAX_COMPARISON_MODELS} models selected — deselect one to change.- </div>- )}- <div style={{ flex: 1, overflowY: "auto" }}>- {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 (- <button- key={m}- disabled={disabled}- onClick={() => 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,- }}- >- <span- style={{- width: 16,- height: 16,- borderRadius: 3,- border: `1.5px solid ${checked ? "#1677ff" : "#d1d5db"}`,- background: checked ? "#1677ff" : "#fff",- display: "flex",- alignItems: "center",- justifyContent: "center",- flexShrink: 0,- transition: "all 0.1s",- }}- >- {checked && <CheckOutlined style={{ fontSize: 10, color: "#fff" }} />}- </span>- {logo ? (- <img- src={logo}- alt=""- style={{ width: 16, height: 16, objectFit: "contain", flexShrink: 0 }}- onError={(e) => {- (e.currentTarget as HTMLImageElement).style.display = "none";- }}- />- ) : (- <span style={{ width: 16, flexShrink: 0 }} />- )}- <span- style={{- fontSize: 13,- color: "#111827",- overflow: "hidden",- textOverflow: "ellipsis",- whiteSpace: "nowrap",- }}- >- {m}- </span>- </button>- );- })}- </div>- </div>- );-- // ---- Sidebar nav item renderer ----- const sidebarNavItem = (icon: React.ReactNode, label: string, onClick: () => void, active = false, kbd?: string) => (- <Tooltip title={sidebarCollapsed ? label : undefined} placement="right" key={label}>- <button- onClick={onClick}- style={{- display: "flex",- alignItems: "center",- gap: 10,- padding: "8px 10px",- width: "100%",- borderRadius: 7,- border: "none",- cursor: "pointer",- background: active ? "#e8f4ff" : "transparent",- color: active ? "#1677ff" : "#374151",- textAlign: "left",- fontSize: 14,- justifyContent: sidebarCollapsed ? "center" : "flex-start",- transition: "background 0.12s",- }}- onMouseEnter={(e) => {- if (!active) (e.currentTarget as HTMLButtonElement).style.background = "#f5f5f5";- }}- onMouseLeave={(e) => {- (e.currentTarget as HTMLButtonElement).style.background = active ? "#e8f4ff" : "transparent";- }}- >- <span style={{ fontSize: 16, flexShrink: 0 }}>{icon}</span>- {!sidebarCollapsed && (- <>- <span style={{ flex: 1 }}>{label}</span>- {kbd && <span style={{ fontSize: 11, color: "#9ca3af" }}>{kbd}</span>}- </>- )}- </button>- </Tooltip>- );-- // ---- Model selector trigger button ----- const modelSelectorTrigger = isLoadingModels ? (- <Skeleton.Input active style={{ width: 160, height: 28 }} />- ) : (- <Popover- open={modelSelectorOpen}- onOpenChange={(open) => {- setModelSelectorOpen(open);- if (!open) setModelSearchText("");- }}- content={modelSelectorContent}- trigger="click"- placement="bottomLeft"- >- <button- style={{- display: "flex",- alignItems: "center",- gap: 6,- padding: "5px 10px",- borderRadius: 7,- border: "1px solid transparent",- cursor: "pointer",- background: "transparent",- color: "#111827",- fontSize: 14,- fontWeight: 500,- maxWidth: 480,- overflow: "hidden",- }}- onMouseEnter={(e) => {- (e.currentTarget as HTMLButtonElement).style.background = "#f5f5f5";- }}- onMouseLeave={(e) => {- (e.currentTarget as HTMLButtonElement).style.background = "transparent";- }}- >- {selectedModels.length === 0 ? (- <span style={{ color: "#9ca3af" }}>Select model</span>- ) : selectedModels.length === 1 ? (- <>- {(() => {- const provider = getProviderFromModelName(selectedModels[0]);- const { logo } = provider ? getProviderLogoAndName(provider) : { logo: "" };- return logo ? (- <img- src={logo}- alt=""- style={{ width: 18, height: 18, objectFit: "contain", flexShrink: 0 }}- onError={(e) => {- (e.currentTarget as HTMLImageElement).style.display = "none";- }}- />- ) : null;- })()}- <span style={{ overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap", maxWidth: 240 }}>- {selectedModels[0]}- </span>- </>- ) : (- <div style={{ display: "flex", alignItems: "center", gap: 4, flexWrap: "nowrap", overflow: "hidden" }}>- {selectedModels.map((m) => {- const provider = getProviderFromModelName(m);- const { logo } = provider ? getProviderLogoAndName(provider) : { logo: "" };- return (- <span- key={m}- style={{- display: "inline-flex",- alignItems: "center",- gap: 4,- padding: "2px 8px",- background: "#f0f4ff",- borderRadius: 10,- fontSize: 12,- color: "#1677ff",- fontWeight: 500,- flexShrink: 0,- }}- >- {logo && (- <img- src={logo}- alt=""- style={{ width: 13, height: 13, objectFit: "contain" }}- onError={(e) => {- (e.currentTarget as HTMLImageElement).style.display = "none";- }}- />- )}- <span style={{ maxWidth: 120, overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>- {m}- </span>- </span>- );- })}- </div>- )}- <DownOutlined style={{ fontSize: 10, color: "#9ca3af", flexShrink: 0, marginLeft: 2 }} />- </button>- </Popover>- );-- // ---- Shared input bar ----- const inputBar = (inConversation: boolean) => (- <div- style={{- background: "#fff",- borderRadius: 12,- border: "1px solid #e5e7eb",- boxShadow: "0 1px 6px rgba(0,0,0,0.06)",- overflow: "hidden",- }}- >- <textarea- ref={textareaRef}- value={inputText}- onChange={(e) => setInputText(e.target.value)}- onKeyDown={handleKeyDown}- placeholder={inConversation ? "Send a message..." : "How can I help you today?"}- style={{- width: "100%",- minHeight: inConversation ? 52 : 80,- padding: inConversation ? "16px 20px 8px" : "20px 20px 8px",- border: "none",- outline: "none",- resize: "none",- fontSize: 15,- color: "#111827",- background: "transparent",- fontFamily: "inherit",- boxSizing: "border-box",- }}- />- <div- style={{- display: "flex",- alignItems: "center",- justifyContent: "space-between",- padding: inConversation ? "4px 12px 10px" : "8px 12px 12px",- borderTop: "1px solid #f3f4f6",- }}- >- <Popover- open={mcpPopoverOpen}- onOpenChange={setMcpPopoverOpen}- content={- <MCPConnectPicker- accessToken={accessToken}- selectedServers={selectedMCPServers}- onChange={setSelectedMCPServers}- />- }- trigger="click"- placement="topLeft"- >- <button- style={{- background: "none",- border: "1px solid #d1d5db",- borderRadius: 6,- padding: "5px 10px",- cursor: "pointer",- fontSize: 14,- color: "#6b7280",- display: "flex",- alignItems: "center",- gap: 4,- }}- >- <PlusOutlined />- {selectedMCPServers.length > 0 && (- <span style={{ fontSize: 12, color: "#1677ff", fontWeight: 500 }}>{selectedMCPServers.length}</span>- )}- </button>- </Popover>-- <div style={{ display: "flex", alignItems: "center", gap: 8 }}>- {!isComparisonMode && (- <span- style={{- fontSize: 12,- color: "#9ca3af",- maxWidth: 160,- overflow: "hidden",- textOverflow: "ellipsis",- whiteSpace: "nowrap",- }}- >- {inConversation- ? selectedMCPServers.length > 0- ? `${selectedMCPServers.length} tool${selectedMCPServers.length > 1 ? "s" : ""} connected`- : ""- : selectedModels[0] || "No model"}- </span>- )}- {isAnyStreaming ? (- <button- onClick={handleStop}- style={{- background: "none",- border: "1.5px solid #d1d5db",- borderRadius: "50%",- width: 32,- height: 32,- cursor: "pointer",- color: "#374151",- display: "flex",- alignItems: "center",- justifyContent: "center",- flexShrink: 0,- transition: "border-color 0.15s",- }}- onMouseEnter={(e) => {- (e.currentTarget as HTMLButtonElement).style.borderColor = "#9ca3af";- }}- onMouseLeave={(e) => {- (e.currentTarget as HTMLButtonElement).style.borderColor = "#d1d5db";- }}- >- <div style={{ width: 10, height: 10, background: "#374151", borderRadius: 2 }} />- </button>- ) : (- <button- onClick={() => handleSubmit(inputText)}- disabled={!inputText.trim() || isLoadingModels || selectedModels.length === 0}- style={{- background: inputText.trim() && selectedModels.length > 0 ? "#1677ff" : "#f3f4f6",- border: "none",- borderRadius: 7,- padding: "7px 16px",- cursor: inputText.trim() && selectedModels.length > 0 ? "pointer" : "not-allowed",- color: inputText.trim() && selectedModels.length > 0 ? "#fff" : "#9ca3af",- fontSize: 14,- fontWeight: 500,- transition: "background 0.15s",- }}- >- Send- </button>- )}- </div>- </div>- </div>- );-- return (- <div- style={{- display: "flex",- height: "100vh",- width: "100vw",- background: "#ffffff",- fontFamily: "-apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif",- overflow: "hidden",- }}- >- {/* ===== LEFT SIDEBAR ===== */}- <div- style={{- width: sidebarCollapsed ? 56 : 260,- flexShrink: 0,- background: "#f9fafb",- borderRight: "1px solid #e5e7eb",- display: "flex",- flexDirection: "column",- overflow: "hidden",- transition: "width 0.2s cubic-bezier(0.4, 0, 0.2, 1)",- }}- >- {/* Sidebar header: logo + collapse button */}- <div- style={{- display: "flex",- alignItems: "center",- padding: "12px 10px",- justifyContent: sidebarCollapsed ? "center" : "space-between",- flexShrink: 0,- }}- >- {!sidebarCollapsed && (- <div style={{ display: "flex", alignItems: "center", gap: 8 }}>- <img- src={logoSrc}- alt="LiteLLM"- style={{ height: 28, maxWidth: 120, objectFit: "contain", flexShrink: 0 }}- />- <span style={{ fontWeight: 700, fontSize: 15, color: "#111827", letterSpacing: "-0.01em" }}>LiteLLM</span>- </div>- )}- <Tooltip title={sidebarCollapsed ? "Expand sidebar" : "Collapse sidebar"} placement="right">- <button- onClick={() => setSidebarCollapsed((v) => !v)}- style={{- background: "none",- border: "none",- cursor: "pointer",- padding: 6,- borderRadius: 7,- color: "#6b7280",- fontSize: 16,- display: "flex",- alignItems: "center",- }}- >- {sidebarCollapsed ? <MenuUnfoldOutlined /> : <MenuFoldOutlined />}- </button>- </Tooltip>- </div>-- {/* Sidebar nav buttons */}- <div style={{ padding: "0 8px 4px", flexShrink: 0 }}>- {sidebarNavItem(<EditOutlined />, "New chat", () => router.push(getChatUrl(uiRoot)))}- {sidebarNavItem(<SearchOutlined />, "Search chats", () => setSidebarView("chats"))}- </div>-- <div style={{ height: 1, background: "#e5e7eb", margin: "4px 8px", flexShrink: 0 }} />-- {/* Chats / Apps tabs + Back to console */}- <div style={{ padding: "4px 8px", flexShrink: 0 }}>- {sidebarNavItem(<MessageOutlined />, "Chats", () => setSidebarView("chats"), sidebarView === "chats")}- {sidebarNavItem(<AppstoreOutlined />, "Apps", () => setSidebarView("apps"), sidebarView === "apps")}- {sidebarNavItem(- <KeyOutlined />,- "Credentials",- () => setSidebarView("credentials"),- sidebarView === "credentials",- )}- <Tooltip title={sidebarCollapsed ? "Back to Developer Console UI" : undefined} placement="right">- <a- href={dashboardUrl}- style={{- display: "flex",- alignItems: "center",- gap: 10,- padding: "8px 10px",- width: "100%",- borderRadius: 7,- color: "#6b7280",- textDecoration: "none",- fontSize: 14,- justifyContent: sidebarCollapsed ? "center" : "flex-start",- boxSizing: "border-box",- }}- onMouseEnter={(e) => {- (e.currentTarget as HTMLAnchorElement).style.background = "#f5f5f5";- }}- onMouseLeave={(e) => {- (e.currentTarget as HTMLAnchorElement).style.background = "transparent";- }}- >- <ArrowLeftOutlined style={{ fontSize: 16, flexShrink: 0 }} />- {!sidebarCollapsed && <span>Back to Developer Console UI</span>}- </a>- </Tooltip>- </div>-- <div style={{ height: 1, background: "#e5e7eb", margin: "4px 8px", flexShrink: 0 }} />-- {/* Sidebar content — only conversation list, only when in chats view and expanded */}- {!sidebarCollapsed && sidebarView === "chats" && (- <div style={{ flex: 1, overflow: "hidden", display: "flex", flexDirection: "column" }}>- <ConversationList- conversations={conversations}- activeConversationId={activeConversationId}- onSelect={(id) => router.push(getChatUrl(uiRoot, id))}- onDelete={deleteConversation}- onNewChat={() => router.push(getChatUrl(uiRoot))}- onRename={renameConversation}- />- </div>- )}- </div>-- {/* ===== MAIN AREA ===== */}- <div style={{ flex: 1, display: "flex", flexDirection: "column", overflow: "hidden", minWidth: 0 }}>- {/* Top bar */}- <div- style={{- display: "flex",- alignItems: "center",- justifyContent: "space-between",- padding: "8px 16px",- flexShrink: 0,- borderBottom: "1px solid #f0f0f0",- background: "#fff",- height: 48,- }}- >- {/* Left: model selector */}- <div style={{ display: "flex", alignItems: "center", gap: 8, minWidth: 0, flex: 1 }}>- {modelSelectorTrigger}- </div>-- {/* Right: settings */}- <div style={{ display: "flex", alignItems: "center", gap: 4, flexShrink: 0 }}>- <Tooltip title="Settings">- <button- style={{- background: "none",- border: "none",- cursor: "pointer",- padding: 7,- borderRadius: 7,- color: "#6b7280",- fontSize: 16,- display: "flex",- alignItems: "center",- }}- >- <SettingOutlined />- </button>- </Tooltip>- </div>- </div>-- {/* Storage warning banner */}- {storageUnavailable && !storageBannerDismissed && (- <div- style={{- background: "#fffbe6",- borderBottom: "1px solid #ffe58f",- padding: "6px 20px",- fontSize: 13,- color: "#874d00",- display: "flex",- justifyContent: "space-between",- alignItems: "center",- }}- >- <span>Chat history won't be saved in this browser session.</span>- <button- onClick={() => setStorageBannerDismissed(true)}- style={{ background: "none", border: "none", cursor: "pointer", fontSize: 16, color: "#874d00" }}- >- ×- </button>- </div>- )}-- {/* Content area */}- <div- style={{- flex: 1,- minHeight: 0,- overflow: "hidden",- display: "flex",- flexDirection: "column",- background: "#fff",- }}- >- {/* ---- Apps page view ---- */}- {sidebarView === "apps" ? (- <div- style={{- flex: 1,- minHeight: 0,- overflow: "auto",- maxWidth: 800,- margin: "0 auto",- width: "100%",- padding: "32px 24px",- }}- >- <MCPAppsPanel- accessToken={accessToken}- selectedServers={selectedMCPServers}- onChange={setSelectedMCPServers}- />- </div>- ) : sidebarView === "credentials" ? (- /* ---- Credentials view ---- */- <div- style={{- flex: 1,- minHeight: 0,- overflow: "auto",- maxWidth: 800,- margin: "0 auto",- width: "100%",- padding: "32px 24px",- }}- >- <MCPCredentialsTab accessToken={accessToken} />- </div>- ) : showBlankState ? (- /* ---- Blank state ---- */- <div- style={{- flex: 1,- display: "flex",- flexDirection: "column",- alignItems: "center",- justifyContent: "center",- padding: "0 24px 80px",- }}- >- {/* Greeting */}- <h1- style={{- margin: "0 0 32px",- fontSize: 28,- fontWeight: 600,- color: "#111827",- fontFamily: "inherit",- letterSpacing: "-0.01em",- textAlign: "center",- }}- >- {isComparisonMode ? `Compare ${selectedModels.length} models` : greeting}- </h1>-- {isComparisonMode ? (- <p style={{ margin: "-16px 0 24px", fontSize: 14, color: "#6b7280", textAlign: "center" }}>- Send a message to see responses side-by-side- </p>- ) : (- <p- style={{- margin: "-16px 0 28px",- fontSize: 14,- color: "#6b7280",- textAlign: "center",- maxWidth: 520,- lineHeight: 1.6,- }}- >- Chat with 100+ LLMs + MCP tools — authenticate once, use them here.{" "}- <button- onClick={() => setSidebarView("apps")}- style={{- background: "none",- border: "none",- cursor: "pointer",- color: "#1677ff",- fontSize: 14,- padding: 0,- fontWeight: 500,- }}- >- Open Apps →- </button>- </p>- )}-- {/* Input card */}- <div style={{ width: "100%", maxWidth: 680 }}>{inputBar(false)}</div>-- {/* Suggestion chips — only in single-model mode */}- {!isComparisonMode && (- <div style={{ display: "flex", gap: 8, marginTop: 14, flexWrap: "wrap", justifyContent: "center" }}>- {SUGGESTIONS.map((s) => (- <button- key={s}- onClick={() => 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}- </button>- ))}- </div>- )}- </div>- ) : (- /* ---- Active conversation (single-model or comparison) ---- */- <div- style={{- flex: 1,- minHeight: 0,- display: "flex",- flexDirection: "column",- maxWidth: isComparisonMode ? (selectedModels.length >= 3 ? 1200 : 960) : 760,- margin: "0 auto",- width: "100%",- padding: "0 24px",- position: "relative",- }}- >- <div- ref={messagesScrollRef}- style={{ flex: 1, minHeight: 0, overflow: "auto", paddingTop: 24, overflowAnchor: "none" }}- >- {isComparisonMode ? (- /* Comparison: multi-turn exchanges, each with user bubble + side-by-side response cards */- <div style={{ paddingBottom: 8 }}>- {comparisonExchanges.map((exchange, exchangeIdx) => {- const isLastExchange = exchangeIdx === comparisonExchanges.length - 1;- return (- <div key={exchangeIdx} style={{ marginBottom: 32 }}>- {/* User message bubble */}- <div style={{ display: "flex", justifyContent: "flex-end", marginBottom: 20 }}>- <div- style={{- background: "#f3f4f6",- borderRadius: 16,- padding: "10px 16px",- maxWidth: "75%",- fontSize: 14,- color: "#111827",- lineHeight: 1.5,- }}- >- {exchange.userMessage}- </div>- </div>-- {/* Response cards side-by-side */}- <div style={{ display: "flex", gap: 14, alignItems: "flex-start" }}>- {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 (- <div- key={model}- style={{- flex: 1,- border: "1px solid #e5e7eb",- borderRadius: 12,- overflow: "hidden",- minWidth: 0,- }}- >- {/* Card header — only show on first exchange */}- {exchangeIdx === 0 && (- <div- style={{- padding: "10px 14px",- borderBottom: "1px solid #f0f0f0",- display: "flex",- alignItems: "center",- gap: 8,- background: "#fafafa",- }}- >- {logo ? (- <img- src={logo}- alt=""- style={{ width: 18, height: 18, objectFit: "contain", flexShrink: 0 }}- onError={(e) => {- (e.currentTarget as HTMLImageElement).style.display = "none";- }}- />- ) : (- <div- style={{- width: 18,- height: 18,- borderRadius: "50%",- background: "#e5e7eb",- flexShrink: 0,- }}- />- )}- <span style={{ fontWeight: 600, fontSize: 12, color: "#374151" }}>- Response {idx + 1}- </span>- <span- style={{- fontSize: 11,- color: "#9ca3af",- overflow: "hidden",- textOverflow: "ellipsis",- whiteSpace: "nowrap",- flex: 1,- minWidth: 0,- }}- >- {model}- </span>- </div>- )}- {/* Card body */}- <div style={{ padding: "14px 16px", minHeight: 60, position: "relative" }}>- {isModelStreaming && (- <span- style={{- position: "absolute",- top: 10,- right: 12,- fontSize: 9,- color: "#1677ff",- }}- >- ●- </span>- )}- {responseText ? (- <ReactMarkdown- remarkPlugins={[remarkGfm]}- components={{- p: ({ children }) => (- <p- style={{- margin: "0 0 10px",- lineHeight: 1.6,- fontSize: 14,- color: "#111827",- }}- >- {children}- </p>- ),- code: ({ className, children }) => {- const isBlock = /language-(\w+)/.exec(className || "");- if (isBlock) {- return (- <pre- style={{- background: "#f8f9fa",- padding: "10px 12px",- borderRadius: 6,- overflow: "auto",- fontSize: 13,- margin: "8px 0",- }}- >- <code>{children}</code>- </pre>- );- }- return (- <code- style={{- background: "#f3f4f6",- padding: "2px 5px",- borderRadius: 3,- fontSize: 13,- }}- >- {children}- </code>- );- },- }}- >- {responseText}- </ReactMarkdown>- ) : isModelStreaming ? (- <span style={{ color: "#9ca3af", fontSize: 14 }}>Generating…</span>- ) : (- <span style={{ color: "#9ca3af", fontSize: 14 }}>—</span>- )}- </div>- </div>- );- })}- </div>- </div>- );- })}- </div>- ) : (- <ChatMessages- messages={activeConversation!.messages}- isStreaming={isStreaming}- onEditMessage={handleEditAndResend}- />- )}- </div>- {showScrollButton && (- <button- onClick={() => {- 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"- >- <DownOutlined style={{ fontSize: 12 }} />- </button>- )}-- {/* Input bar (in conversation) */}- <div style={{ padding: "12px 0 24px" }}>{inputBar(true)}</div>- </div>- )}- </div>- </div>- </div>- );-};--export default ChatPage;diff --git a/ui/litellm-dashboard/src/components/chat/ConversationList.tsx b/ui/litellm-dashboard/src/components/chat/ConversationList.tsxdeleted file mode 100644index f75ee8fa40a..00000000000--- a/ui/litellm-dashboard/src/components/chat/ConversationList.tsx+++ /dev/null@@ -1,450 +0,0 @@-"use client";--import React, { useState, useEffect, useRef, useCallback } from "react";-import { Button, Input, Modal, Popconfirm, Tooltip, Avatar, Typography } from "antd";-import {- EditOutlined,- DeleteOutlined,- PlusOutlined,- SearchOutlined,- UserOutlined,- MessageOutlined,-} from "@ant-design/icons";-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";--const getDateGroup = (timestamp: number): DateGroup => {- const now = dayjs();- const date = dayjs(timestamp);-- if (date.isSame(now, "day")) return "Today";- 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"];--interface GroupedConversations {- group: DateGroup;- items: Conversation[];-}--const groupConversations = (conversations: Conversation[]): GroupedConversations[] => {- const map = new Map<DateGroup, Conversation[]>();-- 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;- onSelect: (id: string) => void;- onDelete: (id: string) => void;- onRename: (id: string, newTitle: string) => void;-}--const ConversationRow: React.FC<ConversationRowProps> = ({ conv, isActive, onSelect, onDelete, onRename }) => {- const [editing, setEditing] = useState(false);- const [editValue, setEditValue] = useState(conv.title);- const inputRef = useRef<HTMLInputElement | null>(null);-- useEffect(() => {- if (editing && inputRef.current) {- inputRef.current.focus();- inputRef.current.select();- }- }, [editing]);-- const startEditing = (e: React.MouseEvent) => {- e.stopPropagation();- setEditValue(conv.title);- setEditing(true);- };-- const commitRename = () => {- const trimmed = editValue.trim();- if (trimmed && trimmed !== conv.title) {- onRename(conv.id, trimmed);- }- setEditing(false);- };-- const cancelEditing = () => {- setEditValue(conv.title);- setEditing(false);- };-- const handleKeyDown = (e: React.KeyboardEvent<HTMLInputElement>) => {- if (e.key === "Enter") {- e.preventDefault();- commitRename();- } else if (e.key === "Escape") {- e.preventDefault();- cancelEditing();- }- };-- const truncatedTitle = conv.title.length > 40 ? conv.title.slice(0, 40) + "…" : conv.title;-- return (- <div- onClick={() => !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";- }- }}- >- {editing ? (- <Input- ref={(node) => {- inputRef.current = node?.input ?? null;- }}- size="small"- value={editValue}- onChange={(e) => setEditValue(e.target.value)}- onKeyDown={handleKeyDown}- onBlur={commitRename}- onClick={(e) => e.stopPropagation()}- style={{ flex: 1, fontSize: 13 }}- />- ) : (- <>- <Text- style={{- flex: 1,- fontSize: 13,- color: isActive ? "#1677ff" : "#333",- overflow: "hidden",- whiteSpace: "nowrap",- textOverflow: "ellipsis",- fontWeight: isActive ? 500 : 400,- }}- title={conv.title}- >- {truncatedTitle}- </Text>-- {/* Action icons — visible only on hover via CSS opacity */}- <div- className="conversation-actions"- style={{- display: "flex",- gap: 2,- opacity: 0,- transition: "opacity 0.15s",- flexShrink: 0,- }}- onClick={(e) => e.stopPropagation()}- >- <Tooltip title="Rename">- <Button- type="text"- size="small"- icon={<EditOutlined style={{ fontSize: 12 }} />}- onClick={startEditing}- style={{ width: 22, height: 22, padding: 0, minWidth: 22 }}- />- </Tooltip>- <Popconfirm- title="Delete this conversation?"- onConfirm={() => onDelete(conv.id)}- okText="Delete"- cancelText="Cancel"- okButtonProps={{ danger: true }}- >- <Tooltip title="Delete">- <Button- type="text"- size="small"- danger- icon={<DeleteOutlined style={{ fontSize: 12 }} />}- style={{ width: 22, height: 22, padding: 0, minWidth: 22 }}- />- </Tooltip>- </Popconfirm>- </div>- </>- )}- </div>- );-};--// ---- Cmd+K search modal ------interface SearchModalProps {- open: boolean;- conversations: Conversation[];- onSelect: (id: string) => void;- onClose: () => void;-}--const SearchModal: React.FC<SearchModalProps> = ({ open, conversations, onSelect, onClose }) => {- const [query, setQuery] = useState("");-- useEffect(() => {- if (!open) setQuery("");- }, [open]);-- const filtered = query.trim()- ? conversations.filter((c) => c.title.toLowerCase().includes(query.trim().toLowerCase()))- : conversations;-- const handleSelect = (id: string) => {- onSelect(id);- onClose();- };-- return (- <Modal- open={open}- onCancel={onClose}- footer={null}- title={null}- width={480}- styles={{ body: { padding: "16px 16px 8px" } }}- >- <Input- autoFocus- prefix={<SearchOutlined style={{ color: "#bbb" }} />}- placeholder="Search conversations…"- value={query}- onChange={(e) => setQuery(e.target.value)}- style={{ marginBottom: 12 }}- allowClear- />-- <div style={{ maxHeight: 320, overflowY: "auto" }}>- {filtered.length === 0 ? (- <div style={{ textAlign: "center", padding: "24px 0", color: "#999" }}>No conversations found</div>- ) : (- filtered.map((conv) => {- const truncated = conv.title.length > 55 ? conv.title.slice(0, 55) + "…" : conv.title;- return (- <div- key={conv.id}- onClick={() => 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";- }}- >- <MessageOutlined style={{ color: "#999", flexShrink: 0 }} />- <Text style={{ fontSize: 13 }}>{truncated}</Text>- <Text type="secondary" style={{ fontSize: 11, marginLeft: "auto", flexShrink: 0 }}>- {dayjs(conv.updatedAt).format("MMM D")}- </Text>- </div>- );- })- )}- </div>- </Modal>- );-};--// ---- Main ConversationList component ------const ConversationList: React.FC<Props> = ({- conversations,- activeConversationId,- onSelect,- onDelete,- onNewChat,- 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();- setSearchModalOpen((prev) => !prev);- }- }, []);-- useEffect(() => {- document.addEventListener("keydown", handleGlobalKeyDown);- return () => document.removeEventListener("keydown", handleGlobalKeyDown);- }, [handleGlobalKeyDown]);-- const grouped = groupConversations(conversations);-- return (- <>- {/* Hover-reveal CSS for action icons */}- <style>{`- .conversation-row:hover .conversation-actions {- opacity: 1 !important;- }- `}</style>-- <div- style={{- display: "flex",- flexDirection: "column",- height: "100%",- width: "100%",- overflow: "hidden",- }}- >- {/* Top: New Chat button */}- <div style={{ padding: "12px 10px 8px" }}>- <Tooltip- title="Chats are saved locally in this browser. All requests are logged in Spend → Logs."- placement="right"- >- <Button type="primary" icon={<PlusOutlined />} onClick={onNewChat} style={{ width: "100%" }}>- New Chat- </Button>- </Tooltip>- </div>-- {/* Conversation list (scrollable) */}- <div- style={{- flex: 1,- overflowY: "auto",- padding: "0 6px",- }}- >- {grouped.length === 0 ? (- <div- style={{- textAlign: "center",- color: "#bbb",- fontSize: 12,- marginTop: 32,- padding: "0 12px",- }}- >- No conversations yet.- <br />- Start a new chat above.- </div>- ) : (- grouped.map(({ group, items }) => (- <div key={group} style={{ marginBottom: 8 }}>- <div- style={{- fontSize: 11,- fontWeight: 600,- color: "#999",- textTransform: "uppercase",- letterSpacing: "0.04em",- padding: "8px 8px 4px",- }}- >- {group}- </div>- {items.map((conv) => (- <ConversationRow- key={conv.id}- conv={conv}- isActive={conv.id === activeConversationId}- onSelect={onSelect}- onDelete={onDelete}- onRename={onRename}- />- ))}- </div>- ))- )}- </div>-- {/* Bottom: user avatar placeholder */}- <div- style={{- padding: "10px 12px",- borderTop: "1px solid #f0f0f0",- display: "flex",- alignItems: "center",- gap: 8,- }}- >- <Avatar- size={28}- icon={<UserOutlined />}- style={{ backgroundColor: "#e0e7ff", color: "#4f46e5", flexShrink: 0 }}- />- <Text- style={{- fontSize: 13,- color: "#555",- overflow: "hidden",- whiteSpace: "nowrap",- textOverflow: "ellipsis",- }}- >- My Account- </Text>- </div>- </div>-- {/* Cmd+K search modal */}- <SearchModal- open={searchModalOpen}- conversations={conversations}- onSelect={onSelect}- onClose={() => setSearchModalOpen(false)}- />- </>- );-};--export default ConversationList;diff --git a/ui/litellm-dashboard/src/components/chat/MCPAppsPanel.tsx b/ui/litellm-dashboard/src/components/chat/MCPAppsPanel.tsxdeleted file mode 100644index 880d408eb33..00000000000--- a/ui/litellm-dashboard/src/components/chat/MCPAppsPanel.tsx+++ /dev/null@@ -1,726 +0,0 @@-"use client";--import React, { useCallback, useEffect, useRef, useState } from "react";-import { Spin, Input, Button, Skeleton } from "antd";-import { SearchOutlined, ArrowLeftOutlined, RightOutlined, ToolOutlined, CheckCircleOutlined } from "@ant-design/icons";-import {- deleteMCPOAuthUserCredential,- fetchMCPServers,- getMCPOAuthUserCredentialStatus,- listMCPTools,-} from "../networking";-import { AUTH_TYPE, MCPServer, MCPTool, handleTransport } from "../mcp_tools/types";-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";-}--const OAuth2ConnectButton: React.FC<OAuth2ConnectButtonProps> = ({- server,- accessToken,- onConnect,- variant = "badge",-}) => {- const name = server.server_name ?? server.alias ?? server.server_id;- const { startOAuthFlow, status } = useUserMcpOAuthFlow({- accessToken,- serverId: server.server_id,- serverAlias: name,- onSuccess: useCallback(() => onConnect(server.server_id), [onConnect, server.server_id]),- });-- const loading = status === "authorizing" || status === "exchanging";-- if (variant === "button") {- return (- <Button- type="primary"- loading={loading}- onClick={startOAuthFlow}- style={{ borderRadius: 8, fontWeight: 600, height: 38, minWidth: 110 }}- >- {loading ? "Connecting…" : "Connect"}- </Button>- );- }-- return (- <span- onClick={(e) => {- 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",- }}- >- {loading ? "Connecting…" : "Connect"}- </span>- );-};-// ─────────────────────────────────────────────────────────────────────────────--interface Props {- accessToken: string;- selectedServers: string[];- onChange: (servers: string[]) => void;-}--const AVATAR_COLORS = [- "#1677ff",- "#52c41a",- "#fa8c16",- "#eb2f96",- "#722ed1",- "#13c2c2",- "#fa541c",- "#2f54eb",- "#a0d911",- "#faad14",-];--function getAvatarColor(name: string): string {- let hash = 0;- for (let i = 0; i < name.length; i++) hash = name.charCodeAt(i) + ((hash << 5) - hash);- return AVATAR_COLORS[Math.abs(hash) % AVATAR_COLORS.length];-}--type TabKey = "all" | "connected";--const MCPAppsPanel: React.FC<Props> = ({ accessToken, selectedServers, onChange }) => {- const [servers, setServers] = useState<MCPServer[]>([]);- const [loading, setLoading] = useState(true);- const [query, setQuery] = useState("");- const [activeTab, setActiveTab] = useState<TabKey>("all");- const [togglingOn, setTogglingOn] = useState<Set<string>>(new Set());- const [detailServer, setDetailServer] = useState<MCPServer | null>(null);- const [detailTools, setDetailTools] = useState<MCPTool[]>([]);- const [loadingTools, setLoadingTools] = useState(false);- // tool counts per server name, preloaded in background- const [toolCounts, setToolCounts] = useState<Record<string, number>>({});- const [loadingCounts, setLoadingCounts] = useState(false);- // OAuth2 connect state — tracks which server_ids have a stored user credential- const [oauthConnected, setOauthConnected] = useState<Set<string>>(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<MCPServer[]>([]);- useEffect(() => {- serversRef.current = servers;- }, [servers]);- const selectedServersRef = useRef<string[]>(selectedServers);- useEffect(() => {- selectedServersRef.current = selectedServers;- }, [selectedServers]);- const onChangeRef = useRef(onChange);- useEffect(() => {- onChangeRef.current = onChange;- }, [onChange]);-- const nameOf = (s: MCPServer) => s.server_name ?? s.alias ?? s.server_id;-- useEffect(() => {- let cancelled = false;- setLoading(true);-- // 1. Load servers first — show the list immediately- fetchMCPServers(accessToken)- .then((serverData) => {- if (cancelled) return;- const list: MCPServer[] = Array.isArray(serverData) ? serverData : serverData?.data ?? [];- setServers(list);- setLoading(false);-- // 2. Fetch tools per server in parallel — each resolves independently and updates counts one by one- setLoadingCounts(true);- let remaining = list.length;- if (remaining === 0) {- setLoadingCounts(false);- return;- }- list.forEach((s) => {- listMCPTools(accessToken, s.server_id)- .then((toolsData) => {- if (cancelled) return;- const tools: MCPTool[] = Array.isArray(toolsData?.tools) ? toolsData.tools : [];- const sname = nameOf(s);- setToolCounts((prev) => ({ ...prev, [sname]: tools.length }));- })- .catch(() => {})- .finally(() => {- if (cancelled) return;- remaining -= 1;- if (remaining === 0) 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) => {- getMCPOAuthUserCredentialStatus(accessToken, s.server_id)- .then((status) => {- if (cancelled) return;- if (status.has_credential && !status.is_expired) {- setOauthConnected((prev) => new Set(prev).add(s.server_id));- }- })- .catch(() => {});- });- })- .catch(() => {- if (!cancelled) {- setServers([]);- setLoading(false);- }- });- return () => {- cancelled = true;- };- }, [accessToken]);-- // 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- .filter((s) => oauthConnected.has(s.server_id) && !selectedServersRef.current.includes(nameOf(s)))- .map(nameOf);- if (namesToAdd.length > 0) {- onChangeRef.current([...selectedServersRef.current, ...namesToAdd]);- }- }, [oauthConnected]);-- 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);- next.delete(serverId);- return next;- });- }- return;- }- 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]);- }- } catch {- MessageManager.warning(`Could not load tools for ${serverName}`);- } finally {- setTogglingOn((prev) => {- const next = new Set(prev);- next.delete(serverName);- return next;- });- }- };-- // Fetch tools for the detail view — server_id must be the UUID- useEffect(() => {- if (!detailServer) {- setDetailTools([]);- return;- }- let cancelled = false;- setLoadingTools(true);- listMCPTools(accessToken, detailServer.server_id)- .then((result) => {- if (cancelled) return;- // API returns { tools: [...], error: null }- const tools: MCPTool[] = Array.isArray(result?.tools) ? result.tools : [];- setDetailTools(tools);- })- .catch(() => {- if (!cancelled) setDetailTools([]);- })- .finally(() => {- if (!cancelled) setLoadingTools(false);- });- return () => {- cancelled = true;- };- }, [detailServer, accessToken]);-- const filtered = servers.filter((s) => {- const name = nameOf(s);- const matchesQuery =- !query.trim() ||- name.toLowerCase().includes(query.toLowerCase()) ||- (s.description ?? "").toLowerCase().includes(query.toLowerCase());- const matchesTab = activeTab === "all" || selectedServers.includes(name);- return matchesQuery && matchesTab;- });-- 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);- const isTogglingOn = togglingOn.has(name);- const color = getAvatarColor(name);-- return (- <div style={{ width: "100%" }}>- {/* Back */}- <button- onClick={() => setDetailServer(null)}- style={{- display: "flex",- alignItems: "center",- gap: 6,- background: "none",- border: "none",- cursor: "pointer",- color: "#6b7280",- fontSize: 13,- padding: "0 0 20px 0",- }}- >- <ArrowLeftOutlined style={{ fontSize: 12 }} />- Back- </button>-- {/* Avatar + name + connect */}- <div style={{ display: "flex", alignItems: "flex-start", gap: 20, marginBottom: 28 }}>- {detailServer.mcp_info?.logo_url ? (- <img- src={detailServer.mcp_info.logo_url}- alt={`${name} logo`}- style={{- width: 64,- height: 64,- borderRadius: 16,- objectFit: "contain",- flexShrink: 0,- background: "#f9fafb",- }}- onError={(e) => {- const el = e.target as HTMLImageElement;- el.style.display = "none";- if (el.nextElementSibling) (el.nextElementSibling as HTMLElement).style.display = "flex";- }}- />- ) : null}- <div- style={{- width: 64,- height: 64,- borderRadius: 16,- background: color,- display: detailServer.mcp_info?.logo_url ? "none" : "flex",- alignItems: "center",- justifyContent: "center",- color: "#fff",- fontWeight: 700,- fontSize: 28,- flexShrink: 0,- }}- >- {name.charAt(0).toUpperCase()}- </div>- <div style={{ flex: 1 }}>- <h2 style={{ margin: "0 0 4px", fontSize: 22, fontWeight: 700, color: "#111827" }}>{name}</h2>- <p style={{ margin: 0, fontSize: 14, color: "#6b7280" }}>{detailServer.description ?? "MCP server"}</p>- </div>- {detailServer.auth_type === AUTH_TYPE.OAUTH2 ? (- oauthConnected.has(detailServer.server_id) ? (- <Button- type="default"- danger- onClick={async () => {- try {- await deleteMCPOAuthUserCredential(accessToken, detailServer.server_id);- } catch (_) {- // Ignore — credential may already be gone; update UI regardless.- }- setOauthConnected((prev) => {- const n = new Set(prev);- n.delete(detailServer.server_id);- return n;- });- onChangeRef.current(selectedServersRef.current.filter((s) => s !== name));- }}- style={{ borderRadius: 8, fontWeight: 600, height: 38, minWidth: 110 }}- >- Disconnect- </Button>- ) : (- <OAuth2ConnectButton- server={detailServer}- accessToken={accessToken}- onConnect={(id) => {- setOauthConnected((prev) => new Set(prev).add(id));- }}- variant="button"- />- )- ) : (- <Button- type={isConnected ? "default" : "primary"}- loading={isTogglingOn}- onClick={() => handleToggle(name, !isConnected, detailServer.server_id)}- style={{ borderRadius: 8, fontWeight: 600, height: 38, minWidth: 110 }}- >- {isConnected ? "Disconnect" : "Connect"}- </Button>- )}- </div>-- {/* Info table */}- <h3 style={{ margin: "0 0 12px", fontSize: 15, fontWeight: 600, color: "#111827" }}>Information</h3>- <div style={{ border: "1px solid #e5e7eb", borderRadius: 10, overflow: "hidden", marginBottom: 28 }}>- {[- ["Server ID", detailServer.server_id],- ["Transport", handleTransport(detailServer.transport, detailServer.spec_path)],- ["Status", isConnected ? "Connected" : "Not connected"],- ]- .filter(([, v]) => v)- .map(([label, value], i, arr) => (- <div- key={label}- style={{- display: "flex",- padding: "12px 16px",- borderBottom: i < arr.length - 1 ? "1px solid #f3f4f6" : "none",- fontSize: 13,- }}- >- <span style={{ width: 140, color: "#9ca3af", flexShrink: 0 }}>{label}</span>- <span style={{ color: "#111827", fontWeight: 500 }}>{value}</span>- </div>- ))}- </div>-- {/* Tools section */}- <div style={{ display: "flex", alignItems: "center", gap: 8, marginBottom: 12 }}>- <h3 style={{ margin: 0, fontSize: 15, fontWeight: 600, color: "#111827" }}>Available Tools</h3>- {!loadingTools && (- <span- style={{- fontSize: 11,- fontWeight: 600,- color: "#6b7280",- background: "#f3f4f6",- borderRadius: 4,- padding: "1px 6px",- }}- >- {detailTools.length}- </span>- )}- </div>- {loadingTools ? (- <div style={{ display: "flex", justifyContent: "center", padding: "24px 0" }}>- <Spin size="small" />- </div>- ) : detailTools.length === 0 ? (- <div style={{ color: "#9ca3af", fontSize: 13, padding: "8px 0" }}>No tools available</div>- ) : (- <div style={{ display: "flex", flexDirection: "column", gap: 8 }}>- {detailTools.map((tool) => (- <div- key={tool.name}- style={{- border: "1px solid #e5e7eb",- borderRadius: 8,- padding: "10px 14px",- background: "#fafafa",- }}- >- <div style={{ display: "flex", alignItems: "center", gap: 8, marginBottom: tool.description ? 4 : 0 }}>- <ToolOutlined style={{ fontSize: 13, color: "#6b7280" }} />- <span style={{ fontSize: 13, fontWeight: 600, color: "#111827", fontFamily: "monospace" }}>- {tool.name}- </span>- </div>- {tool.description && (- <p style={{ margin: 0, fontSize: 12, color: "#6b7280", paddingLeft: 21 }}>{tool.description}</p>- )}- </div>- ))}- </div>- )}- </div>- );- }-- // ── List view ──- return (- <div style={{ width: "100%" }}>- {/* Header row */}- <div- style={{- display: "flex",- alignItems: "center",- justifyContent: "space-between",- marginBottom: 20,- gap: 16,- flexWrap: "wrap",- }}- >- <div>- <div style={{ display: "flex", alignItems: "center", gap: 8, marginBottom: 4 }}>- <h2 style={{ margin: 0, fontSize: 18, fontWeight: 600, color: "#111827" }}>MCP Servers</h2>- <span- style={{- fontSize: 10,- fontWeight: 600,- color: "#1677ff",- background: "#e8f4ff",- borderRadius: 4,- padding: "1px 6px",- letterSpacing: "0.05em",- textTransform: "uppercase",- }}- >- Beta- </span>- </div>- <div style={{ display: "flex", alignItems: "center", gap: 12 }}>- <p style={{ margin: 0, fontSize: 13, color: "#6b7280" }}>- Browse tools, authenticate once, use in chat — no setup needed.- </p>- {loadingCounts ? (- <span style={{ display: "flex", alignItems: "center", gap: 5, fontSize: 12, color: "#9ca3af" }}>- <Spin size="small" style={{ transform: "scale(0.7)" }} />- Loading tools...- </span>- ) : totalTools > 0 ? (- <span style={{ display: "flex", alignItems: "center", gap: 4, fontSize: 12, color: "#6b7280" }}>- <ToolOutlined style={{ fontSize: 11 }} />- {totalTools} tool{totalTools !== 1 ? "s" : ""} available- </span>- ) : null}- </div>- </div>- <Input- prefix={<SearchOutlined style={{ color: "#9ca3af", fontSize: 13 }} />}- placeholder="Search servers..."- value={query}- onChange={(e) => setQuery(e.target.value)}- allowClear- style={{ width: 220, borderRadius: 8, fontSize: 13 }}- size="middle"- />- </div>-- {/* Tabs */}- <div style={{ display: "flex", borderBottom: "1px solid #e5e7eb", marginBottom: 16 }}>- {(["all", "connected"] as TabKey[]).map((tab) => (- <button- key={tab}- onClick={() => 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})` : ""}`}- </button>- ))}- </div>-- {/* Grid */}- {loading ? (- <div style={{ display: "flex", justifyContent: "center", padding: "48px 0" }}>- <Spin />- </div>- ) : filtered.length === 0 ? (- <div style={{ textAlign: "center", color: "#9ca3af", fontSize: 13, padding: "48px 12px" }}>- {servers.length === 0- ? "No MCP servers configured. Add servers in Tools → MCP Servers."- : activeTab === "connected"- ? "No servers connected yet."- : "No servers match your search."}- </div>- ) : (- <div- style={{- display: "grid",- gridTemplateColumns: "repeat(2, minmax(0, 1fr))",- gap: 0,- border: "1px solid #e5e7eb",- borderRadius: 10,- overflow: "hidden",- }}- >- {filtered.map((server, idx) => {- const name = nameOf(server);- const isConnected = selectedServers.includes(name);- const color = getAvatarColor(name);- const isLeftCol = idx % 2 === 0;- const count = toolCounts[name];-- return (- <div- key={server.server_id}- onClick={() => 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";- }}- >- {server.mcp_info?.logo_url ? (- <img- src={server.mcp_info.logo_url}- alt={`${name} logo`}- style={{- width: 38,- height: 38,- borderRadius: 10,- objectFit: "contain",- flexShrink: 0,- background: "#f9fafb",- }}- onError={(e) => {- const el = e.target as HTMLImageElement;- el.style.display = "none";- if (el.nextElementSibling) (el.nextElementSibling as HTMLElement).style.display = "flex";- }}- />- ) : null}- <div- style={{- width: 38,- height: 38,- borderRadius: 10,- background: color,- display: server.mcp_info?.logo_url ? "none" : "flex",- alignItems: "center",- justifyContent: "center",- color: "#fff",- fontWeight: 700,- fontSize: 16,- flexShrink: 0,- }}- >- {name.charAt(0).toUpperCase()}- </div>- <div style={{ flex: 1, minWidth: 0 }}>- <div- style={{- fontSize: 14,- fontWeight: 500,- color: "#111827",- overflow: "hidden",- textOverflow: "ellipsis",- whiteSpace: "nowrap",- }}- >- {name}- </div>- <div- style={{- fontSize: 12,- color: "#9ca3af",- marginTop: 1,- display: "flex",- alignItems: "center",- gap: 6,- }}- >- <span style={{ overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>- {server.description ?? "MCP server"}- </span>- {count !== undefined ? (- count > 0 ? (- <span- style={{ flexShrink: 0, display: "flex", alignItems: "center", gap: 3, color: "#9ca3af" }}- >- · <ToolOutlined style={{ fontSize: 10 }} /> {count}- </span>- ) : null- ) : loadingCounts ? (- <Skeleton.Input- active- size="small"- style={{ width: 28, height: 12, minWidth: 28, flexShrink: 0 }}- />- ) : null}- </div>- </div>- {server.auth_type === AUTH_TYPE.OAUTH2 ? (- oauthConnected.has(server.server_id) ? (- <CheckCircleOutlined style={{ fontSize: 14, color: "#52c41a", flexShrink: 0 }} />- ) : (- <OAuth2ConnectButton- server={server}- accessToken={accessToken}- onConnect={(id) => {- setOauthConnected((prev) => new Set(prev).add(id));- }}- variant="badge"- />- )- ) : isConnected ? (- <span style={{ width: 7, height: 7, borderRadius: "50%", background: "#1677ff", flexShrink: 0 }} />- ) : null}- <RightOutlined style={{ fontSize: 11, color: "#d1d5db", flexShrink: 0 }} />- </div>- );- })}- </div>- )}- </div>- );-};--export default MCPAppsPanel;diff --git a/ui/litellm-dashboard/src/components/chat/MCPConnectPicker.tsx b/ui/litellm-dashboard/src/components/chat/MCPConnectPicker.tsxdeleted file mode 100644index 3e13ec9dc87..00000000000--- a/ui/litellm-dashboard/src/components/chat/MCPConnectPicker.tsx+++ /dev/null@@ -1,171 +0,0 @@-import React, { useEffect, useState } from "react";-import { Switch, Spin } from "antd";-import MessageManager from "@/components/molecules/message_manager";-import { fetchMCPServers, listMCPTools } from "../networking";-import { MCPServer } from "../mcp_tools/types";--interface Props {- accessToken: string;- selectedServers: string[];- onChange: (servers: string[]) => void;-}--const MCPConnectPicker: React.FC<Props> = ({ accessToken, selectedServers, onChange }) => {- const [servers, setServers] = useState<MCPServer[]>([]);- const [loadingServers, setLoadingServers] = useState(true);- // Track which individual servers are being toggled on (verifying tools)- const [togglingOn, setTogglingOn] = useState<Set<string>>(new Set());-- useEffect(() => {- let cancelled = false;-- const load = async () => {- setLoadingServers(true);- 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 {- if (!cancelled) {- setServers([]);- }- } finally {- if (!cancelled) {- setLoadingServers(false);- }- }- };-- load();-- return () => {- cancelled = true;- };- }, [accessToken]);-- 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- 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- } finally {- setTogglingOn((prev) => {- const next = new Set(prev);- next.delete(serverName);- return next;- });- }- };-- return (- <div- style={{- maxWidth: 320,- maxHeight: 400,- overflowY: "auto",- padding: "8px 0",- }}- >- {loadingServers ? (- <div style={{ display: "flex", justifyContent: "center", padding: "24px 0" }}>- <Spin />- </div>- ) : servers.length === 0 ? (- <div style={{ padding: "16px 12px", color: "#8c8c8c", fontSize: 13, textAlign: "center" }}>- No MCP servers configured- </div>- ) : (- servers.map((server) => {- const name = server.server_name ?? server.alias ?? server.server_id;- const isSelected = selectedServers.includes(name);- const isTogglingOn = togglingOn.has(name);-- return (- <div- key={server.server_id}- style={{- display: "flex",- alignItems: "flex-start",- justifyContent: "space-between",- padding: "8px 12px",- gap: 12,- }}- >- {server.mcp_info?.logo_url && (- <img- src={server.mcp_info.logo_url}- alt={`${name} logo`}- style={{- width: 24,- height: 24,- borderRadius: 6,- objectFit: "contain",- flexShrink: 0,- marginTop: 1,- }}- onError={(e) => {- (e.target as HTMLImageElement).style.display = "none";- }}- />- )}- <div style={{ flex: 1, minWidth: 0 }}>- <div- style={{- fontWeight: 500,- fontSize: 13,- color: "#1f1f1f",- whiteSpace: "nowrap",- overflow: "hidden",- textOverflow: "ellipsis",- }}- >- {name}- </div>- {server.description && (- <div- style={{- fontSize: 12,- color: "#8c8c8c",- marginTop: 2,- whiteSpace: "nowrap",- overflow: "hidden",- textOverflow: "ellipsis",- }}- >- {server.description}- </div>- )}- </div>- <Switch- size="small"- checked={isSelected}- loading={isTogglingOn}- onChange={(checked) => handleToggle(name, checked)}- />- </div>- );- })- )}- </div>- );-};--export default MCPConnectPicker;diff --git a/ui/litellm-dashboard/src/components/chat/MCPCredentialsTab.tsx b/ui/litellm-dashboard/src/components/chat/MCPCredentialsTab.tsxdeleted file mode 100644index 4a8a3785f29..00000000000--- a/ui/litellm-dashboard/src/components/chat/MCPCredentialsTab.tsx+++ /dev/null@@ -1,166 +0,0 @@-"use client";--/**- * MCPCredentialsTab- *- * Shows all OAuth2 MCP connections the calling user has stored.- * Lives in the Chat sidebar's "Credentials" tab.- */--import React, { useCallback, useEffect, useState } from "react";-import { Spin } from "antd";-import MessageManager from "@/components/molecules/message_manager";-import { DeleteOutlined, LinkOutlined } from "@ant-design/icons";-import { Badge, Table, TableBody, TableCell, TableHead, TableHeaderCell, TableRow } from "@tremor/react";-import { deleteMCPOAuthUserCredential, listMCPUserCredentials, MCPUserCredentialListItem } from "../networking";--interface Props {- accessToken: string;-}--function relativeTime(isoString: string | null | undefined): string {- if (!isoString) return "";- try {- const date = new Date(isoString);- const diffMs = Date.now() - date.getTime();- const diffSec = Math.floor(diffMs / 1000);- if (diffSec < 60) return "just now";- const diffMin = Math.floor(diffSec / 60);- if (diffMin < 60) return `${diffMin}m ago`;- const diffHr = Math.floor(diffMin / 60);- if (diffHr < 24) return `${diffHr}h ago`;- return `${Math.floor(diffHr / 24)}d ago`;- } catch {- return "";- }-}--function expiryLabel(isoString: string | null | undefined): string {- if (!isoString) return "Does not expire";- try {- const exp = new Date(isoString);- const diffMs = exp.getTime() - Date.now();- if (diffMs <= 0) return "Expired";- 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`;- } catch {- return "";- }-}--const MCPCredentialsTab: React.FC<Props> = ({ accessToken }) => {- const [credentials, setCredentials] = useState<MCPUserCredentialListItem[]>([]);- const [loading, setLoading] = useState(true);- const [revoking, setRevoking] = useState<Set<string>>(new Set());-- const load = useCallback(() => {- setLoading(true);- listMCPUserCredentials(accessToken)- .then(setCredentials)- .catch(() => setCredentials([]))- .finally(() => setLoading(false));- }, [accessToken]);-- useEffect(() => {- load();- }, [load]);-- const handleRevoke = async (serverId: string) => {- setRevoking((prev) => new Set(prev).add(serverId));- try {- await deleteMCPOAuthUserCredential(accessToken, serverId);- setCredentials((prev) => prev.filter((c) => c.server_id !== serverId));- } catch {- MessageManager.error("Failed to revoke connection. Please try again.");- } finally {- setRevoking((prev) => {- const n = new Set(prev);- n.delete(serverId);- return n;- });- }- };-- const displayName = (c: MCPUserCredentialListItem) => c.alias || c.server_name || c.server_id;-- return (- <div className="w-full">- {/* Header */}- <div className="mb-4">- <h2 className="text-base font-semibold text-gray-900 mb-0.5">App Credentials</h2>- <p className="text-sm text-gray-500 m-0">Your stored OAuth connections — used automatically in chat.</p>- </div>-- {loading ? (- <div className="flex justify-center py-12">- <Spin />- </div>- ) : credentials.length === 0 ? (- <div className="text-center text-gray-400 text-sm py-12 border border-dashed border-gray-200 rounded-lg">- <LinkOutlined className="text-2xl mb-3 block text-gray-300" />- No connections yet.- <br />- Go to <strong>Apps</strong> and click <strong>Connect</strong> to authorize an MCP server.- </div>- ) : (- <div className="rounded-lg border border-gray-200 overflow-hidden">- <Table>- <TableHead>- <TableRow>- <TableHeaderCell className="text-xs font-medium text-gray-500 py-2 px-4">App</TableHeaderCell>- <TableHeaderCell className="text-xs font-medium text-gray-500 py-2 px-4">Connected</TableHeaderCell>- <TableHeaderCell className="text-xs font-medium text-gray-500 py-2 px-4">Status</TableHeaderCell>- <TableHeaderCell className="text-xs font-medium text-gray-500 py-2 px-4 text-right">- Actions- </TableHeaderCell>- </TableRow>- </TableHead>- <TableBody>- {credentials.map((cred) => {- const name = displayName(cred);- const isRevoking = revoking.has(cred.server_id);- const exp = expiryLabel(cred.expires_at);- const connected = relativeTime(cred.connected_at);- const isExpired = exp === "Expired";-- return (- <TableRow key={cred.server_id} className="h-10 hover:bg-gray-50">- <TableCell className="py-2 px-4">- <span className="text-sm font-medium text-gray-900">{name}</span>- </TableCell>- <TableCell className="py-2 px-4">- <span className="text-sm text-gray-500">{connected || "—"}</span>- </TableCell>- <TableCell className="py-2 px-4">- <Badge color={isExpired ? "red" : "green"} size="xs">- {exp}- </Badge>- </TableCell>- <TableCell className="py-2 px-4 text-right">- <button- onClick={() => 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 ? <Spin size="small" /> : <DeleteOutlined className="text-sm" />}- </button>- </TableCell>- </TableRow>- );- })}- </TableBody>- </Table>- </div>- )}- </div>- );-};--export default MCPCredentialsTab;diff --git a/ui/litellm-dashboard/src/components/chat/types.ts b/ui/litellm-dashboard/src/components/chat/types.tsdeleted file mode 100644index 9b657306db6..00000000000--- a/ui/litellm-dashboard/src/components/chat/types.ts+++ /dev/null@@ -1,25 +0,0 @@-import type { MCPEvent } from "../mcp_tools/types";-export type { MCPEvent };--export interface ChatMessage {- id: string;- role: "user" | "assistant" | "tool";- content: string;- reasoningContent?: string;- /** MCP tool events that occurred during this assistant turn, in order. */- mcpEvents?: MCPEvent[];- toolName?: string;- toolArgs?: Record<string, unknown>;- toolResult?: string;- timestamp: number;-}--export interface Conversation {- id: string;- title: string;- model: string;- messages: ChatMessage[];- mcpServerNames: string[];- createdAt: number;- updatedAt: number;-}diff --git a/ui/litellm-dashboard/src/components/chat/useChatHistory.ts b/ui/litellm-dashboard/src/components/chat/useChatHistory.tsdeleted file mode 100644index 274ae6a79c9..00000000000--- a/ui/litellm-dashboard/src/components/chat/useChatHistory.ts+++ /dev/null@@ -1,213 +0,0 @@-import { useCallback, useEffect, useRef, useState } from "react";-import { ChatMessage, Conversation } from "./types";--const STORAGE_KEY = "litellm_chat_history_v1";-const MAX_CONVERSATIONS = 100;-const TITLE_MAX_LENGTH = 40;--function generateTitle(firstUserMessage: string): string {- const trimmed = firstUserMessage.trim();- if (trimmed.length <= TITLE_MAX_LENGTH) {- return trimmed;- }- return trimmed.slice(0, TITLE_MAX_LENGTH) + "…";-}--function loadFromStorage(): { conversations: Conversation[]; storageUnavailable: boolean } {- try {- const raw = localStorage.getItem(STORAGE_KEY);- if (!raw) {- return { conversations: [], storageUnavailable: false };- }- const parsed = JSON.parse(raw) as Conversation[];- return { conversations: parsed, storageUnavailable: false };- } catch {- return { conversations: [], storageUnavailable: true };- }-}--function saveToStorage(conversations: Conversation[]): boolean {- try {- localStorage.setItem(STORAGE_KEY, JSON.stringify(conversations));- return true;- } catch {- return false;- }-}--function trimConversations(conversations: Conversation[]): Conversation[] {- if (conversations.length <= MAX_CONVERSATIONS) {- return conversations;- }- return [...conversations].sort((a, b) => b.updatedAt - a.updatedAt).slice(0, MAX_CONVERSATIONS);-}--export function useChatHistory(activeConversationId: string | null): {- conversations: Conversation[];- activeConversation: Conversation | null;- storageUnavailable: boolean;- staleId: boolean;- createConversation: (model: string) => string;- appendMessage: (conversationId: string, message: Omit<ChatMessage, "id" | "timestamp">) => void;- updateLastAssistantMessage: (- conversationId: string,- updates: Partial<Pick<ChatMessage, "content" | "reasoningContent" | "mcpEvents">>,- ) => void;- /** Remove the message with `messageId` and all subsequent messages from the conversation. */- truncateFromMessage: (conversationId: string, messageId: string) => void;- deleteConversation: (id: string) => void;- renameConversation: (id: string, newTitle: string) => void;- setActiveConversationId: (id: string | null) => void;-} {- const [conversations, setConversations] = useState<Conversation[]>([]);- const [storageUnavailable, setStorageUnavailable] = useState(false);- const [staleId, setStaleId] = useState(false);- const [currentActiveId, setCurrentActiveId] = useState<string | null>(activeConversationId);- // Ref so updater functions stay pure (no state setter calls inside setConversations)- const storageUnavailableRef = useRef(false);- const initializedRef = useRef(false);-- // Sync internal active id whenever the URL-derived prop changes (e.g. "New chat" → null)- useEffect(() => {- setCurrentActiveId(activeConversationId);- setStaleId(false);- }, [activeConversationId]);-- useEffect(() => {- const { conversations: loaded, storageUnavailable: unavailable } = loadFromStorage();- storageUnavailableRef.current = unavailable;- setConversations(loaded);- setStorageUnavailable(unavailable);- initializedRef.current = true;-- if (activeConversationId !== null) {- const found = loaded.some((c) => c.id === activeConversationId);- if (!found) {- setStaleId(true);- }- }- }, []); // eslint-disable-line react-hooks/exhaustive-deps-- // Persist to localStorage after every conversations change (pure effect, no setState inside updaters)- useEffect(() => {- if (!initializedRef.current) return;- if (storageUnavailableRef.current) return;- const success = saveToStorage(conversations);- if (!success) {- storageUnavailableRef.current = true;- setStorageUnavailable(true);- }- }, [conversations]);-- const createConversation = useCallback((model: string): string => {- const id = crypto.randomUUID();- const now = Date.now();- const newConversation: Conversation = {- id,- title: "New conversation",- model,- messages: [],- mcpServerNames: [],- createdAt: now,- updatedAt: now,- };- setConversations((prev) => trimConversations([newConversation, ...prev]));- setCurrentActiveId(id);- return id;- }, []);-- const appendMessage = useCallback((conversationId: string, message: Omit<ChatMessage, "id" | "timestamp">) => {- const newMessage: ChatMessage = {- ...message,- id: crypto.randomUUID(),- timestamp: Date.now(),- };-- setConversations((prev) => {- const updated = prev.map((conv) => {- if (conv.id !== conversationId) return conv;- const updatedMessages = [...conv.messages, newMessage];- let title = conv.title;- if (- title === "New conversation" &&- newMessage.role === "user" &&- conv.messages.filter((m) => m.role === "user").length === 0- ) {- title = generateTitle(newMessage.content);- }- return { ...conv, title, messages: updatedMessages, updatedAt: Date.now() };- });- return trimConversations(updated);- });- }, []);-- const updateLastAssistantMessage = useCallback(- (conversationId: string, updates: Partial<Pick<ChatMessage, "content" | "reasoningContent" | "mcpEvents">>) => {- setConversations((prev) => {- const updated = prev.map((conv) => {- if (conv.id !== conversationId) return conv;- const messages = [...conv.messages];- const lastAssistantIndex = messages.reduceRight((found, msg, idx) => {- if (found !== -1) return found;- return msg.role === "assistant" ? idx : -1;- }, -1);- if (lastAssistantIndex === -1) return conv;- messages[lastAssistantIndex] = { ...messages[lastAssistantIndex], ...updates };- return { ...conv, messages, updatedAt: Date.now() };- });- return trimConversations(updated);- });- },- [],- );-- const truncateFromMessage = useCallback((conversationId: string, messageId: string) => {- setConversations((prev) => {- const updated = prev.map((conv) => {- if (conv.id !== conversationId) return conv;- const idx = conv.messages.findIndex((m) => m.id === messageId);- if (idx === -1) return conv;- return { ...conv, messages: conv.messages.slice(0, idx), updatedAt: Date.now() };- });- return trimConversations(updated);- });- }, []);-- const deleteConversation = useCallback(- (id: string) => {- setConversations((prev) => trimConversations(prev.filter((c) => c.id !== id)));- if (currentActiveId === id) setCurrentActiveId(null);- },- [currentActiveId],- );-- const renameConversation = useCallback((id: string, newTitle: string) => {- setConversations((prev) =>- trimConversations(- prev.map((conv) => (conv.id === id ? { ...conv, title: newTitle, updatedAt: Date.now() } : conv)),- ),- );- }, []);-- const setActiveConversationId = useCallback((id: string | null) => {- setCurrentActiveId(id);- setStaleId(false);- }, []);-- const activeConversation =- currentActiveId !== null ? conversations.find((c) => c.id === currentActiveId) ?? null : null;-- return {- conversations,- activeConversation,- storageUnavailable,- staleId,- createConversation,- appendMessage,- updateLastAssistantMessage,- truncateFromMessage,- deleteConversation,- renameConversation,- setActiveConversationId,- };-}