diff --git a/litellm/responses/mcp/mcp_streaming_iterator.py b/litellm/responses/mcp/mcp_streaming_iterator.py index 3c24a703b686..c705a04963ca 100644 --- a/litellm/responses/mcp/mcp_streaming_iterator.py +++ b/litellm/responses/mcp/mcp_streaming_iterator.py @@ -24,6 +24,8 @@ else: MCPTool = Any +MAX_MCP_TOOL_CALL_ROUNDS = 5 + async def create_mcp_list_tools_events( mcp_tools_with_litellm_proxy: List[ToolParam], @@ -265,9 +267,7 @@ def __init__( self.should_auto_execute = self._should_auto_execute_tools() # Streaming state management - self.phase = ( - "initial_response" # initial_response -> mcp_discovery -> tool_execution -> follow_up_response -> finished - ) + self.phase = "initial_response" # initial_response -> mcp_discovery -> (continue_initial_response <-> tool_execution) -> finished self.finished = False # Event queues and generation flags @@ -281,11 +281,23 @@ def __init__( # Iterator references self.base_iterator: Optional[Union[Any, ResponsesAPIResponse]] = base_iterator # Will be created when needed - self.follow_up_iterator: Optional[Any] = None # Response collection for tool execution self.collected_response: Optional[ResponsesAPIResponse] = None + # Counts completed rounds of tool execution, so a model that keeps + # calling tools (e.g. retrying after an error) can't loop forever. + # Capped in _create_follow_up_iterator, which drops "tools" from the + # request once the cap is hit so the model must answer in text. + self.tool_call_round = 0 + # The collected_response that self.tool_results was computed from. + # _create_follow_up_iterator only builds a follow-up when this is + # still the current collected_response — otherwise a round whose + # response had no tool calls (e.g. the model finally answered in + # text) would incorrectly reuse tool_results left over from an + # earlier round and keep looping instead of finishing. + self._tool_results_for_response: Optional[ResponsesAPIResponse] = None + # Set up model metadata (will be updated when we get the real iterator) self.model = self.original_request_params.get("model", "unknown") self.litellm_metadata = {} @@ -376,10 +388,11 @@ async def __anext__(self) -> ResponsesAPIStreamingResponse: Phase-based streaming: 1. initial_response - Stream the first LLM response (includes response.created, response.in_progress, response.output_item.added) 2. mcp_discovery - Emit MCP discovery events (after response.output_item.added) - 3. continue_initial_response - Continue streaming the initial response content + 3. continue_initial_response - Stream the current round's response (initial or follow-up). + On completion, if auto-execute is on and the response contains tool calls, loops back + through tool_execution/follow-up instead of ending, up to MAX_MCP_TOOL_CALL_ROUNDS. 4. tool_execution - Emit tool execution events - 5. follow_up_response - Stream the follow-up response - 6. finished - End iteration + 5. finished - End iteration """ # Phase 1: Initial Response Stream (emit standard OpenAI events first) @@ -415,21 +428,17 @@ async def __anext__(self) -> ResponsesAPIStreamingResponse: if self.tool_execution_events: return self.tool_execution_events.pop(0) - # Move to follow-up response phase - self.phase = "follow_up_response" + # Route the follow-up call back through continue_initial_response so + # its completion is checked for further tool calls the same way the + # initial response is — otherwise a model that needs a second round + # of tool calls (e.g. retrying after an error) would have that round + # silently dropped and the stream would end with no final text. await self._create_follow_up_iterator() - - # Phase 5: Follow-up Response Stream - if self.phase == "follow_up_response": - if self.follow_up_iterator: - try: - return await cast(Any, self.follow_up_iterator).__anext__() # type: ignore[attr-defined] - except StopAsyncIteration: - self.phase = "finished" - raise - else: - self.phase = "finished" - raise StopAsyncIteration + if self.base_iterator is not None: + self.phase = "continue_initial_response" + return await self.__anext__() + self.phase = "finished" + raise StopAsyncIteration # Phase 6: Finished if self.phase == "finished": @@ -599,6 +608,7 @@ async def _generate_tool_execution_events(self) -> None: tool_calls = [] if not tool_calls: return + self.tool_call_round += 1 for tool_call in tool_calls: ( @@ -686,6 +696,7 @@ async def _generate_tool_execution_events(self) -> None: # Store tool results for follow-up call self.tool_results = tool_results + self._tool_results_for_response = self.collected_response except Exception as e: verbose_logger.error(f"Error in tool execution: {e}") @@ -693,10 +704,16 @@ async def _generate_tool_execution_events(self) -> None: traceback.print_exc() self.tool_results = [] + self._tool_results_for_response = self.collected_response async def _create_follow_up_iterator(self) -> None: """Create the follow-up response iterator with tool results""" - if not self.collected_response or not hasattr(self, "tool_results"): + if self.collected_response is None or self.collected_response is not self._tool_results_for_response: + # Either no response to follow up on, or the current round's + # response had no tool calls (self.tool_results is stale from an + # earlier round) — there is nothing to follow up with, so end + # the stream instead of reusing stale tool results. + self.base_iterator = None return from litellm.responses.main import aresponses @@ -726,18 +743,31 @@ async def _create_follow_up_iterator(self) -> None: # Remove tool_choice to avoid forcing more tool calls follow_up_params.pop("tool_choice", None) + if self.tool_call_round >= MAX_MCP_TOOL_CALL_ROUNDS: + # Hit the round cap: drop tools entirely so the model must + # answer in text instead of emitting another (unexecuted) + # tool call that would otherwise end the stream in silence. + follow_up_params.pop("tools", None) + verbose_logger.warning( + "MCP auto-execute hit MAX_MCP_TOOL_CALL_ROUNDS=%s; forcing a text-only follow-up.", + MAX_MCP_TOOL_CALL_ROUNDS, + ) + follow_up_response = await aresponses(**follow_up_params) - # Set up the follow-up iterator + # Route the follow-up through the same base_iterator machinery as + # the initial call so its completion is checked for further tool + # calls (see phase 4 in __anext__). if hasattr(follow_up_response, "__aiter__"): - self.follow_up_iterator = follow_up_response + self.base_iterator = follow_up_response + self.collected_response = None except Exception as e: verbose_logger.error(f"Error creating follow-up iterator: {e}") import traceback traceback.print_exc() - self.follow_up_iterator = None + self.base_iterator = None def __iter__(self): return self diff --git a/tests/test_litellm/responses/mcp/test_mcp_streaming_iterator.py b/tests/test_litellm/responses/mcp/test_mcp_streaming_iterator.py new file mode 100644 index 000000000000..ecf89ce18d4d --- /dev/null +++ b/tests/test_litellm/responses/mcp/test_mcp_streaming_iterator.py @@ -0,0 +1,171 @@ +import sys +import types +from types import SimpleNamespace +from unittest.mock import AsyncMock, MagicMock + +import pytest +from mcp.types import CallToolResult, TextContent + +import litellm # noqa: F401 - ensures litellm.responses.main is registered in sys.modules +from litellm.responses.mcp.mcp_streaming_iterator import ( + MAX_MCP_TOOL_CALL_ROUNDS, + MCPEnhancedStreamingIterator, +) +from litellm.types.llms.openai import ResponsesAPIResponse, ResponsesAPIStreamEvents + +# `litellm.__init__` re-exports a function named `responses`, which shadows the +# `litellm.responses` subpackage as an attribute — `import litellm.responses.main` +# can resolve to the unrelated third-party `responses` package instead. Look the +# real submodule up in sys.modules directly to sidestep the shadowing. +responses_main_module = sys.modules["litellm.responses.main"] + + +class _FakeAsyncStream: + """Minimal async iterator yielding pre-built chunks, one per __anext__ call.""" + + def __init__(self, chunks): + self._chunks = list(chunks) + + def __aiter__(self): + return self + + async def __anext__(self): + if not self._chunks: + raise StopAsyncIteration + return self._chunks.pop(0) + + +def _output_item_added_chunk(): + return SimpleNamespace(type=ResponsesAPIStreamEvents.OUTPUT_ITEM_ADDED) + + +def _completed_chunk(output): + response = ResponsesAPIResponse(id="resp-1", created_at=0, output=output) + return SimpleNamespace(type=ResponsesAPIStreamEvents.RESPONSE_COMPLETED, response=response) + + +def _function_call(call_id: str, name: str, arguments: str = "{}"): + return {"type": "function_call", "call_id": call_id, "name": name, "arguments": arguments} + + +def _text_message(text: str): + return {"type": "message", "role": "assistant", "content": [{"type": "output_text", "text": text}]} + + +def _tool_call_stream(call_id: str, tool_name: str) -> _FakeAsyncStream: + return _FakeAsyncStream([_completed_chunk([_function_call(call_id, tool_name)])]) + + +def _text_only_stream(text: str) -> _FakeAsyncStream: + return _FakeAsyncStream([_completed_chunk([_text_message(text)])]) + + +def _mock_mcp_environment(monkeypatch: pytest.MonkeyPatch) -> AsyncMock: + """Patch the MCP tool-call plumbing so _execute_tool_calls can run in tests.""" + call_tool = AsyncMock(return_value=CallToolResult(content=[TextContent(type="text", text="ok")], isError=False)) + fake_manager = types.SimpleNamespace( + call_tool=call_tool, + _get_mcp_server_from_tool_name=MagicMock(return_value=None), + ) + monkeypatch.setattr( + "litellm.proxy._experimental.mcp_server.mcp_server_manager.global_mcp_server_manager", + fake_manager, + ) + monkeypatch.setitem( + sys.modules, + "litellm.proxy.proxy_server", + types.SimpleNamespace(proxy_logging_obj=MagicMock()), + ) + return call_tool + + +def _make_iterator(initial_chunks) -> MCPEnhancedStreamingIterator: + return MCPEnhancedStreamingIterator( + base_iterator=_FakeAsyncStream(initial_chunks), + mcp_events=[], + tool_server_map={"read_wiki_contents": "deepwiki"}, + mcp_tools_with_litellm_proxy=[{"require_approval": "never"}], + user_api_key_auth=None, + original_request_params={ + "model": "gpt-4", + "input": "what is berriai/litellm?", + "tools": [{"type": "mcp"}], + }, + ) + + +@pytest.mark.asyncio +async def test_second_round_tool_call_is_executed_and_reaches_final_text(monkeypatch): + """ + Regression test: a tool call that errors, followed by the model retrying + the tool in its follow-up turn, must have that second tool call executed + too — the stream should not silently end after round 1 with no final + text (see PR discussion: deepwiki tool call errors, model retries once, + reply used to just stop with no explanation). + """ + call_tool = _mock_mcp_environment(monkeypatch) + + aresponses_mock = AsyncMock( + side_effect=[ + _tool_call_stream("call_2", "read_wiki_contents"), # round 2: model retries + _text_only_stream("Here's what I found after retrying."), # round 3: final answer + ] + ) + monkeypatch.setattr(responses_main_module, "aresponses", aresponses_mock) + + iterator = _make_iterator( + [ + _output_item_added_chunk(), + _completed_chunk([_function_call("call_1", "read_wiki_contents")]), # round 1: errors + ] + ) + + chunks = [chunk async for chunk in iterator] + + # Both rounds' tool calls were actually executed, not just streamed unexecuted. + assert call_tool.call_count == 2 + assert iterator.tool_call_round == 2 + + # The stream reached round 3 and produced the final text response instead + # of stopping after round 1 or round 2. + completed_chunks = [c for c in chunks if getattr(c, "type", None) == ResponsesAPIStreamEvents.RESPONSE_COMPLETED] + assert len(completed_chunks) == 3 + final_output = completed_chunks[-1].response.output + assert final_output[0]["content"][0]["text"] == "Here's what I found after retrying." + + +@pytest.mark.asyncio +async def test_tool_call_rounds_are_capped(monkeypatch): + """ + A model that keeps calling tools every round must not loop forever — + auto-execution stops at MAX_MCP_TOOL_CALL_ROUNDS, and the follow-up made + at the cap drops "tools" from the request so the model is forced to + answer in text instead of the stream just hanging. + """ + call_tool = _mock_mcp_environment(monkeypatch) + + # Rounds 2..MAX_MCP_TOOL_CALL_ROUNDS keep calling the tool; the call made + # once the cap is hit returns a text-only response. + tool_call_streams = [ + _tool_call_stream(f"call_{i}", "read_wiki_contents") for i in range(2, MAX_MCP_TOOL_CALL_ROUNDS + 1) + ] + aresponses_mock = AsyncMock(side_effect=[*tool_call_streams, _text_only_stream("giving up on tools")]) + monkeypatch.setattr(responses_main_module, "aresponses", aresponses_mock) + + iterator = _make_iterator( + [ + _output_item_added_chunk(), + _completed_chunk([_function_call("call_1", "read_wiki_contents")]), + ] + ) + + _ = [chunk async for chunk in iterator] + + assert iterator.tool_call_round == MAX_MCP_TOOL_CALL_ROUNDS + assert call_tool.call_count == MAX_MCP_TOOL_CALL_ROUNDS + assert aresponses_mock.call_count == MAX_MCP_TOOL_CALL_ROUNDS + + # Every follow-up before the cap still offered tools; only the capped one drops them. + for call in aresponses_mock.call_args_list[:-1]: + assert "tools" in call.kwargs + assert "tools" not in aresponses_mock.call_args_list[-1].kwargs diff --git a/ui/litellm-dashboard/src/app/chat/api-keys/page.tsx b/ui/litellm-dashboard/src/app/chat/api-keys/page.tsx new file mode 100644 index 000000000000..ffba47479a11 --- /dev/null +++ b/ui/litellm-dashboard/src/app/chat/api-keys/page.tsx @@ -0,0 +1,14 @@ +"use client"; + +import { useChatShell } from "@/contexts/ChatShellContext"; +import KeysPanel from "@/components/chat/KeysPanel"; + +export default function ApiKeysPage() { + const { accessToken, userId, premiumUser } = useChatShell(); + + return ( +
+ +
+ ); +} diff --git a/ui/litellm-dashboard/src/app/chat/credentials/page.tsx b/ui/litellm-dashboard/src/app/chat/credentials/page.tsx new file mode 100644 index 000000000000..d82ed603e044 --- /dev/null +++ b/ui/litellm-dashboard/src/app/chat/credentials/page.tsx @@ -0,0 +1,14 @@ +"use client"; + +import { useChatShell } from "@/contexts/ChatShellContext"; +import MCPCredentialsTab from "@/components/chat/MCPCredentialsTab"; + +export default function CredentialsPage() { + const { accessToken } = useChatShell(); + + return ( +
+ +
+ ); +} diff --git a/ui/litellm-dashboard/src/app/chat/integrations/page.tsx b/ui/litellm-dashboard/src/app/chat/integrations/page.tsx new file mode 100644 index 000000000000..f85dd591199c --- /dev/null +++ b/ui/litellm-dashboard/src/app/chat/integrations/page.tsx @@ -0,0 +1,38 @@ +"use client"; + +import { Suspense, useEffect } from "react"; +import { useRouter, useSearchParams } from "next/navigation"; +import { useChatShell } from "@/contexts/ChatShellContext"; +import MCPAppsPanel from "@/components/chat/MCPAppsPanel"; + +// useSearchParams() requires a Suspense boundary for static export. +function IntegrationsPageContent() { + const { accessToken, selectedMCPServers, setSelectedMCPServers } = useChatShell(); + const router = useRouter(); + const searchParams = useSearchParams(); + const oauthReturn = searchParams.get("mcpOauthReturn"); + + // Clean up the OAuth return param after it's been consumed — real routing means + // we no longer need it to pick a tab, but it should not linger in the address bar. + useEffect(() => { + if (oauthReturn) { + const url = new URL(window.location.href); + url.searchParams.delete("mcpOauthReturn"); + router.replace(url.pathname + url.search); + } + }, [oauthReturn, router]); + + return ( +
+ +
+ ); +} + +export default function IntegrationsPage() { + return ( + + + + ); +} diff --git a/ui/litellm-dashboard/src/app/chat/layout.test.tsx b/ui/litellm-dashboard/src/app/chat/layout.test.tsx new file mode 100644 index 000000000000..642fb6880573 --- /dev/null +++ b/ui/litellm-dashboard/src/app/chat/layout.test.tsx @@ -0,0 +1,86 @@ +import { afterEach, describe, expect, it, vi } from "vitest"; +import { render, screen } from "@testing-library/react"; +import ChatLayout from "./layout"; + +const { mockUseAuthorized, mockUseUISettings, mockReplace, mockMigratedHref, state } = vi.hoisted(() => { + const state = { + enableChatUI: false, + isUISettingsLoading: false, + }; + return { + state, + mockReplace: vi.fn(), + mockMigratedHref: vi.fn((segment: string) => `/mocked-ui/${segment}`), + mockUseAuthorized: vi.fn(() => ({ + accessToken: "token-123", + userRole: "Internal User", + userId: "user-1", + userEmail: "user@example.com", + premiumUser: false, + })), + mockUseUISettings: vi.fn(() => ({ + data: { values: { enable_chat_ui: state.enableChatUI } }, + isLoading: state.isUISettingsLoading, + })), + }; +}); + +vi.mock("next/navigation", () => ({ + useRouter: () => ({ replace: mockReplace }), +})); +vi.mock("@/app/(dashboard)/hooks/useAuthorized", () => ({ default: mockUseAuthorized })); +vi.mock("@/app/(dashboard)/hooks/uiSettings/useUISettings", () => ({ useUISettings: mockUseUISettings })); +vi.mock("@/utils/migratedPages", () => ({ migratedHref: mockMigratedHref })); +vi.mock("@/components/navbar", () => ({ default: () =>
})); +vi.mock("@/contexts/ThemeContext", () => ({ + ThemeProvider: ({ children }: { children: React.ReactNode }) => <>{children}, +})); +vi.mock("@/contexts/ChatShellContext", () => ({ + ChatShellProvider: ({ children }: { children: React.ReactNode }) => <>{children}, +})); +vi.mock("@/components/chat/ChatShell", () => ({ + default: ({ children }: { children: React.ReactNode }) =>
{children}
, +})); + +describe("ChatLayout", () => { + afterEach(() => { + state.enableChatUI = false; + state.isUISettingsLoading = false; + mockReplace.mockClear(); + mockMigratedHref.mockClear(); + }); + + it("renders the chat shell when enable_chat_ui is on", () => { + state.enableChatUI = true; + render( + +
+ , + ); + expect(screen.getByTestId("chat-shell")).toBeInTheDocument(); + expect(screen.getByTestId("page-content")).toBeInTheDocument(); + expect(mockReplace).not.toHaveBeenCalled(); + }); + + it("redirects to the dashboard when enable_chat_ui is off", () => { + state.enableChatUI = false; + render( + +
+ , + ); + expect(screen.queryByTestId("chat-shell")).not.toBeInTheDocument(); + expect(mockReplace).toHaveBeenCalledWith("/mocked-ui/"); + }); + + it("renders nothing while UI settings are still loading", () => { + state.isUISettingsLoading = true; + render( + +
+ , + ); + expect(screen.queryByTestId("chat-shell")).not.toBeInTheDocument(); + expect(mockReplace).not.toHaveBeenCalled(); + }); +}); diff --git a/ui/litellm-dashboard/src/app/chat/layout.tsx b/ui/litellm-dashboard/src/app/chat/layout.tsx new file mode 100644 index 000000000000..fe7c327d25b9 --- /dev/null +++ b/ui/litellm-dashboard/src/app/chat/layout.tsx @@ -0,0 +1,54 @@ +"use client"; + +import { Suspense, useEffect } from "react"; +import { useRouter } from "next/navigation"; +import useAuthorized from "@/app/(dashboard)/hooks/useAuthorized"; +import { useUISettings } from "@/app/(dashboard)/hooks/uiSettings/useUISettings"; +import Navbar from "@/components/navbar"; +import { ThemeProvider } from "@/contexts/ThemeContext"; +import { ChatShellProvider } from "@/contexts/ChatShellContext"; +import ChatShell from "@/components/chat/ChatShell"; +import { migratedHref } from "@/utils/migratedPages"; + +// ChatShellProvider uses useSearchParams(), which requires a Suspense boundary for static export. +function ChatLayoutContent({ children }: { children: React.ReactNode }) { + const { accessToken, userRole, userId, userEmail, premiumUser } = useAuthorized(); + const { data: uiSettings, isLoading: isUISettingsLoading } = useUISettings(); + const router = useRouter(); + + const chatEnabled = Boolean(uiSettings?.values?.enable_chat_ui); + const blocked = !isUISettingsLoading && !chatEnabled; + + useEffect(() => { + if (blocked) router.replace(migratedHref("")); + }, [blocked, router]); + + if (isUISettingsLoading || blocked) return null; + + return ( + +
+ +
+ + {children} + +
+
+
+ ); +} + +export default function ChatLayout({ children }: { children: React.ReactNode }) { + return ( + + {children} + + ); +} diff --git a/ui/litellm-dashboard/src/app/chat/page.test.tsx b/ui/litellm-dashboard/src/app/chat/page.test.tsx deleted file mode 100644 index 658142d47a6d..000000000000 --- a/ui/litellm-dashboard/src/app/chat/page.test.tsx +++ /dev/null @@ -1,83 +0,0 @@ -import { afterEach, describe, expect, it, vi } from "vitest"; -import { render, screen } from "@testing-library/react"; -import ChatPageRoute from "./page"; - -const { mockUseAuthorized, mockUseUISettings, mockUseUIConfig, mockReplace, state } = vi.hoisted(() => { - const state = { - userRole: "Internal User" as string, - enableChatUI: false, - isUISettingsLoading: false, - serverRootPath: undefined as string | undefined, - }; - return { - state, - mockReplace: vi.fn(), - mockUseAuthorized: vi.fn(() => ({ - accessToken: "token-123", - userRole: state.userRole, - userId: "user-1", - userEmail: "user@example.com", - })), - mockUseUISettings: vi.fn(() => ({ - data: { values: { enable_chat_ui: state.enableChatUI } }, - isLoading: state.isUISettingsLoading, - })), - mockUseUIConfig: vi.fn(() => ({ data: { server_root_path: state.serverRootPath } })), - }; -}); - -vi.mock("next/navigation", () => ({ - useRouter: () => ({ replace: mockReplace }), -})); -vi.mock("@/app/(dashboard)/hooks/useAuthorized", () => ({ default: mockUseAuthorized })); -vi.mock("@/app/(dashboard)/hooks/uiSettings/useUISettings", () => ({ useUISettings: mockUseUISettings })); -vi.mock("@/app/(dashboard)/hooks/uiConfig/useUIConfig", () => ({ useUIConfig: mockUseUIConfig })); -vi.mock("@/components/chat/ChatPage", () => ({ default: () =>
})); - -describe("ChatPageRoute", () => { - afterEach(() => { - state.userRole = "Internal User"; - state.enableChatUI = false; - state.isUISettingsLoading = false; - state.serverRootPath = undefined; - mockReplace.mockClear(); - }); - - it("renders the chat page when enable_chat_ui is on", () => { - state.enableChatUI = true; - render(); - expect(screen.getByTestId("chat-page")).toBeInTheDocument(); - expect(mockReplace).not.toHaveBeenCalled(); - }); - - it("redirects non-admins to the dashboard when enable_chat_ui is off", () => { - state.enableChatUI = false; - state.userRole = "Internal User"; - render(); - expect(screen.queryByTestId("chat-page")).not.toBeInTheDocument(); - expect(mockReplace).toHaveBeenCalledWith("/ui/"); - }); - - it("redirects admins to the dashboard when enable_chat_ui is off", () => { - state.enableChatUI = false; - state.userRole = "Admin"; - render(); - expect(screen.queryByTestId("chat-page")).not.toBeInTheDocument(); - expect(mockReplace).toHaveBeenCalledWith("/ui/"); - }); - - it("renders nothing while UI settings are still loading", () => { - state.isUISettingsLoading = true; - render(); - expect(screen.queryByTestId("chat-page")).not.toBeInTheDocument(); - expect(mockReplace).not.toHaveBeenCalled(); - }); - - it("respects a custom server_root_path when redirecting", () => { - state.enableChatUI = false; - state.userRole = "Internal User"; - state.serverRootPath = "/api/v1"; - render(); - expect(mockReplace).toHaveBeenCalledWith("/api/v1/ui/"); - }); -}); diff --git a/ui/litellm-dashboard/src/app/chat/page.tsx b/ui/litellm-dashboard/src/app/chat/page.tsx index f1053bec78da..57bb740fbde1 100644 --- a/ui/litellm-dashboard/src/app/chat/page.tsx +++ b/ui/litellm-dashboard/src/app/chat/page.tsx @@ -1,46 +1,590 @@ "use client"; -import { Suspense, useEffect } from "react"; +import React, { useCallback, useEffect, useRef, useState, useLayoutEffect } from "react"; +import { Plus, ChevronDown, Check, X } from "lucide-react"; +import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover"; +import { Skeleton } from "@/components/ui/skeleton"; +import { ScrollArea } from "@/components/ui/scroll-area"; +import { Input } from "@/components/ui/input"; +import { Button } from "@/components/ui/button"; +import MessageManager from "@/components/molecules/message_manager"; import { useRouter } from "next/navigation"; -import useAuthorized from "@/app/(dashboard)/hooks/useAuthorized"; -import { useUIConfig } from "@/app/(dashboard)/hooks/uiConfig/useUIConfig"; -import { useUISettings } from "@/app/(dashboard)/hooks/uiSettings/useUISettings"; -import ChatPage from "@/components/chat/ChatPage"; - -// ChatPage uses useSearchParams() which requires a Suspense boundary for static export. -const ChatPageContent = () => { - const { accessToken, userRole, userId, userEmail } = useAuthorized(); - const { data: uiSettings, isLoading: isUISettingsLoading } = useUISettings(); - const { data: uiConfig } = useUIConfig(); +import { useChatShell } from "@/contexts/ChatShellContext"; +import { CHAT_ROUTES } from "@/components/chat/ChatShell"; +import ChatMessages from "@/components/chat/ChatMessages"; +import MCPConnectPicker from "@/components/chat/MCPConnectPicker"; +import { fetchAvailableModels } from "@/components/llm_calls/fetch_models"; +import { makeOpenAIResponsesRequest } from "@/components/llm_calls/responses_api"; +import type { MCPEvent } from "@/components/chat/types"; +import { getProviderLogoAndName } from "@/components/provider_info_helpers"; + +const SUGGESTIONS = ["Write", "Learn", "Code", "Brainstorm"]; +const LOCALSTORAGE_MODEL_KEY = "litellm_chat_selected_model"; + +function getGreeting(): string { + const h = new Date().getHours(); + if (h >= 5 && h < 12) return "Good morning"; + if (h >= 12 && h < 17) return "Good afternoon"; + return "Good evening"; +} + +// Extract provider from model name for logo lookup. +// Handles prefixed models ("groq/llama-3"), and detects well-known providers by keyword. +function getProviderFromModelName(modelName: string): string { + if (!modelName) return ""; + const lower = modelName.toLowerCase(); + const slash = lower.indexOf("/"); + if (slash > 0) return lower.slice(0, slash); + // Keyword matching — order matters (more specific first) + if (lower.includes("claude")) return "anthropic"; + if (lower.includes("gemini")) return "gemini"; + if (lower.includes("gpt") || lower.includes("chatgpt") || /^o[0-9]/.test(lower)) return "openai"; + if (lower.includes("mistral") || lower.includes("codestral")) return "mistral"; + if (lower.includes("llama")) return "meta_llama"; + if (lower.includes("deepseek")) return "deepseek"; + if (lower.includes("grok")) return "xai"; + if (lower.includes("command")) return "cohere"; + if (lower.includes("nova") || lower.includes("titan")) return "bedrock"; + return ""; +} + +export default function ChatConversationPage() { const router = useRouter(); + const { + accessToken, + userId, + userEmail, + selectedMCPServers, + setSelectedMCPServers, + activeConversationId, + activeConversation, + storageUnavailable, + staleId, + createConversation, + appendMessage, + updateLastAssistantMessage, + truncateFromMessage, + } = useChatShell(); + const hadActiveConversationOnMountRef = useRef(activeConversationId !== null); + + const [selectedModel, setSelectedModel] = useState(null); + const [models, setModels] = useState([]); + const [isLoadingModels, setIsLoadingModels] = useState(true); + const [modelSelectorOpen, setModelSelectorOpen] = useState(false); + const [modelSearchText, setModelSearchText] = useState(""); + + const [responsesSessionId, setResponsesSessionId] = useState(null); + const [prevConversationIdForSessionReset, setPrevConversationIdForSessionReset] = useState(activeConversationId); + const [isStreaming, setIsStreaming] = useState(false); + const [inputText, setInputText] = useState(""); + const [mcpPopoverOpen, setMcpPopoverOpen] = useState(false); + const [storageBannerDismissed, setStorageBannerDismissed] = useState(false); - const uiRoot = - uiConfig?.server_root_path && uiConfig.server_root_path !== "/" - ? uiConfig.server_root_path.replace(/\/+$/, "") - : ""; - const chatEnabled = Boolean(uiSettings?.values?.enable_chat_ui); - const blocked = !isUISettingsLoading && !chatEnabled; + const abortControllerRef = useRef(null); + const textareaRef = useRef(null); + const messagesScrollRef = useRef(null); + const [showScrollButton, setShowScrollButton] = useState(false); + const streamScrollLock = useRef(null); useEffect(() => { - if (blocked) router.replace(`${uiRoot}/ui/`); - }, [blocked, uiRoot, router]); + if (staleId) router.replace(CHAT_ROUTES.chats); + }, [staleId, router]); - if (isUISettingsLoading || blocked) return null; + // Load models + useEffect(() => { + if (!accessToken) return; + fetchAvailableModels(accessToken) + .then((data) => { + const names = (data || []).map((m: { model_group?: string }) => m.model_group ?? "").filter(Boolean); + setModels(names); + try { + const saved = localStorage.getItem(LOCALSTORAGE_MODEL_KEY); + if (saved && names.includes(saved)) { + setSelectedModel(saved); + return; + } + } catch { + // ignore parse errors + } + if (names.length > 0) { + setSelectedModel(names[0]); + localStorage.setItem(LOCALSTORAGE_MODEL_KEY, names[0]); + } + }) + .catch(() => MessageManager.error("Could not load models")) + .finally(() => setIsLoadingModels(false)); + }, [accessToken]); - return ( - + // Reset the responses session when switching between conversations so that + // previous_response_id from conversation A is never sent for conversation B. + if (activeConversationId !== prevConversationIdForSessionReset) { + setPrevConversationIdForSessionReset(activeConversationId); + setResponsesSessionId(null); + } + + const selectModel = useCallback((model: string) => { + setSelectedModel(model); + localStorage.setItem(LOCALSTORAGE_MODEL_KEY, model); + setModelSelectorOpen(false); + setModelSearchText(""); + }, []); + + const handleSend = useCallback( + async (text: string, historyOverride?: Array<{ role: "user" | "assistant"; content: string }>) => { + const trimmed = text.trim(); + if (!trimmed || !selectedModel || isStreaming) return; + const model = selectedModel; + setInputText(""); + + let convId = activeConversationId; + if (!convId) { + convId = createConversation(model); + setResponsesSessionId(null); // new conversation starts a fresh session + router.push(`${CHAT_ROUTES.chats}?id=${convId}`); + } + + appendMessage(convId, { role: "user", content: trimmed }); + appendMessage(convId, { role: "assistant", content: "" }); + + setIsStreaming(true); + abortControllerRef.current = new AbortController(); + + // When historyOverride is set (edit / retry), the existing server-side + // session chain covers messages that were just truncated and is no longer + // valid for the rewritten history. Eagerly clear the session so that a + // failed/aborted edit does not leave a stale session ID that contaminates + // the next regular send. + if (historyOverride) { + setResponsesSessionId(null); + } + + // On a normal continuation turn with an active session, the Responses API + // already holds the prior context server-side, so we only pass the new + // user message (sending the full history would double-count it). + // + // On the very first turn (no session yet), we send the full history. + const previousResponseId = historyOverride ? null : responsesSessionId; + + const history: Array<{ role: "user" | "assistant"; content: string }> = historyOverride + ? [...historyOverride, { role: "user" as const, content: trimmed }] + : previousResponseId + ? [{ role: "user" as const, content: trimmed }] + : [ + // Explicitly filter to only user/assistant roles — tool messages + // lack a required tool_call_id and would cause API errors. + ...(activeConversation?.messages ?? []) + .filter( + (m): m is typeof m & { role: "user" | "assistant" } => m.role === "user" || m.role === "assistant", + ) + .map((m) => ({ role: m.role, content: m.content })), + { role: "user" as const, content: trimmed }, + ]; + + let accumulatedContent = ""; + let accumulatedReasoning = ""; + // MCP events accumulated locally so we can persist them to the message + // without relying on component state (which would cause stale closures). + const accumulatedMCPEvents: MCPEvent[] = []; + // Track clean completion so partial events are not shown on error/abort. + let streamCompletedCleanly = false; + + try { + await makeOpenAIResponsesRequest( + history, + (_role: string, chunk: string) => { + accumulatedContent += chunk; + updateLastAssistantMessage(convId!, { content: accumulatedContent }); + }, + model, + accessToken, + undefined, // tags + abortControllerRef.current.signal, + (rc: string) => { + accumulatedReasoning += rc; + updateLastAssistantMessage(convId!, { reasoningContent: accumulatedReasoning }); + }, + undefined, + undefined, + undefined, + undefined, + undefined, + undefined, + selectedMCPServers.length > 0 ? selectedMCPServers : undefined, + previousResponseId, + (id: string) => setResponsesSessionId(id), + (event: MCPEvent) => { + // Accumulate locally only — persisted once in finally to avoid + // one full localStorage write per MCP event during streaming. + accumulatedMCPEvents.push(event); + }, + ); + streamCompletedCleanly = true; + } catch (err: unknown) { + if (err instanceof Error && err.name === "AbortError") { + updateLastAssistantMessage(convId!, { + content: accumulatedContent + " [stopped]", + }); + } else { + updateLastAssistantMessage(convId!, { + content: "[Something went wrong. The partial response has been saved.]", + }); + } + } finally { + // Only persist MCP events on clean completion — partial events from an + // aborted or errored turn would show incomplete tool calls to the user. + if (accumulatedMCPEvents.length > 0 && streamCompletedCleanly) { + updateLastAssistantMessage(convId!, { mcpEvents: accumulatedMCPEvents }); + } + setIsStreaming(false); + abortControllerRef.current = null; + } + }, + [ + activeConversationId, + activeConversation, + selectedModel, + selectedMCPServers, + accessToken, + createConversation, + appendMessage, + updateLastAssistantMessage, + router, + isStreaming, + responsesSessionId, + ], ); -}; -const ChatPageRoute = () => ( - - - -); + const handleStop = useCallback(() => { + abortControllerRef.current?.abort(); + }, []); + + const handleEditAndResend = useCallback( + (messageId: string, newContent: string) => { + if (!activeConversationId || isStreaming) return; + // Compute the truncated history synchronously before the async state update lands, + // so handleSend receives the correct pre-edit context rather than the stale closure value. + const msgs = activeConversation?.messages ?? []; + const idx = msgs.findIndex((m) => m.id === messageId); + const priorMessages = (idx === -1 ? msgs : msgs.slice(0, idx)) + .filter((m) => m.role === "user" || m.role === "assistant") + .map((m) => ({ role: m.role as "user" | "assistant", content: m.content })); + truncateFromMessage(activeConversationId, messageId); + handleSend(newContent, priorMessages); + }, + [activeConversationId, isStreaming, activeConversation, truncateFromMessage, handleSend], + ); + + const handleKeyDown = (e: React.KeyboardEvent) => { + if (e.key === "Enter" && !e.shiftKey) { + e.preventDefault(); + handleSend(inputText); + } + }; + + // Auto-resize textarea + useEffect(() => { + const ta = textareaRef.current; + if (!ta) return; + ta.style.height = "auto"; + ta.style.height = `${Math.min(ta.scrollHeight, 180)}px`; + }, [inputText]); -export default ChatPageRoute; + // Track scroll position to show/hide scroll-to-bottom button + useEffect(() => { + const el = messagesScrollRef.current; + if (!el) return; + const onScroll = () => { + const distFromBottom = el.scrollHeight - el.scrollTop - el.clientHeight; + setShowScrollButton(distFromBottom > 120); + if (streamScrollLock.current !== null) { + streamScrollLock.current = el.scrollTop; // track user-initiated scroll + } + }; + el.addEventListener("scroll", onScroll, { passive: true }); + return () => el.removeEventListener("scroll", onScroll); + }, [activeConversation]); + + // Start/stop the scroll lock when streaming begins/ends + useEffect(() => { + const el = messagesScrollRef.current; + if (isStreaming) { + streamScrollLock.current = el?.scrollTop ?? 0; + } else { + streamScrollLock.current = null; + } + }, [isStreaming]); + + // After every render during streaming, restore the locked scroll position + useLayoutEffect(() => { + if (streamScrollLock.current === null) return; + const el = messagesScrollRef.current; + if (!el) return; + el.scrollTop = streamScrollLock.current; + }); + + // Scroll to bottom only when message COUNT increases (new message added) + const prevMsgCountRef = useRef(0); + useLayoutEffect(() => { + const count = activeConversation?.messages?.length ?? 0; + const prev = prevMsgCountRef.current; + prevMsgCountRef.current = count; + if (count > prev) { + const el = messagesScrollRef.current; + if (el) el.scrollTop = el.scrollHeight; + } + }, [activeConversation?.messages]); + + const showBlankState = !activeConversation || activeConversation.messages.length === 0; + const displayName = userEmail?.split("@")[0] ?? userId ?? ""; + const greeting = displayName ? `${getGreeting()}, ${displayName}` : getGreeting(); + + // Filtered models: selected one floats to the top, then alphabetical + const filteredModels = ( + modelSearchText ? models.filter((m) => m.toLowerCase().includes(modelSearchText.toLowerCase())) : models + ).sort((a, b) => { + if (a === selectedModel) return -1; + if (b === selectedModel) return 1; + return 0; + }); + + const modelSelectorContent = ( +
+
+ setModelSearchText(e.target.value)} + placeholder="Search models..." + className="h-8 text-[13px]" + /> +
+ + {filteredModels.map((m) => { + const checked = m === selectedModel; + const provider = getProviderFromModelName(m); + const { logo } = provider ? getProviderLogoAndName(provider) : { logo: "" }; + return ( + + ); + })} + +
+ ); + + const modelSelectorTrigger = isLoadingModels ? ( + + ) : ( + { + setModelSelectorOpen(open); + if (!open) setModelSearchText(""); + }} + > + + + + + {modelSelectorContent} + + + ); + + const inputBar = (inConversation: boolean) => ( +
+