AutoGPT is the vision of accessible AI for everyone, to use and to build on. Our mission is to provide the tools, so that you can focus on what matters.
feat(platform): load copilot messages from newest first with cursor-based pagination (#12328)
Krzysztof Czerwinski67bdef13e788
diff --git a/autogpt_platform/backend/backend/api/features/chat/routes.py b/autogpt_platform/backend/backend/api/features/chat/routes.pyindex e8a5e32069..57a7b9a204 100644--- a/autogpt_platform/backend/backend/api/features/chat/routes.py+++ b/autogpt_platform/backend/backend/api/features/chat/routes.py@@ -16,6 +16,7 @@ from pydantic import BaseModel, ConfigDict, Field, field_validatorfrom backend.copilot import service as chat_servicefrom backend.copilot import stream_registryfrom backend.copilot.config import ChatConfig, CopilotMode+from backend.copilot.db import get_chat_messages_paginatedfrom backend.copilot.executor.utils import enqueue_cancel_task, enqueue_copilot_turnfrom backend.copilot.model import (ChatMessage,@@ -155,6 +156,8 @@ class SessionDetailResponse(BaseModel):user_id: str | Nonemessages: list[dict]active_stream: ActiveStreamInfo | None = None # Present if stream is still active+ has_more_messages: bool = False+ oldest_sequence: int | None = Nonetotal_prompt_tokens: int = 0total_completion_tokens: int = 0metadata: ChatSessionMetadata = ChatSessionMetadata()@@ -394,60 +397,78 @@ async def update_session_title_route(async def get_session(session_id: str,user_id: Annotated[str, Security(auth.get_user_id)],+ limit: int = Query(default=50, ge=1, le=200),+ before_sequence: int | None = Query(default=None, ge=0),) -> SessionDetailResponse:"""Retrieve the details of a specific chat session.- Looks up a chat session by ID for the given user (if authenticated) and returns all session data including messages.- If there's an active stream for this session, returns active_stream info for reconnection.+ Supports cursor-based pagination via ``limit`` and ``before_sequence``.+ When no pagination params are provided, returns the most recent messages.Args:session_id: The unique identifier for the desired chat session.- user_id: The optional authenticated user ID, or None for anonymous access.+ user_id: The authenticated user's ID.+ limit: Maximum number of messages to return (1-200, default 50).+ before_sequence: Return messages with sequence < this value (cursor).Returns:- SessionDetailResponse: Details for the requested session, including active_stream info if applicable.-+ SessionDetailResponse: Details for the requested session, including+ active_stream info and pagination metadata."""- session = await get_chat_session(session_id, user_id)- if not session:+ page = await get_chat_messages_paginated(+ session_id, limit, before_sequence, user_id=user_id+ )+ if page is None:raise NotFoundError(f"Session {session_id} not found.")+ messages = [message.model_dump() for message in page.messages]- messages = [message.model_dump() for message in session.messages]-- # Check if there's an active stream for this session+ # Only check active stream on initial load (not on "load more" requests)active_stream_info = None- active_session, last_message_id = await stream_registry.get_active_session(- session_id, user_id- )- logger.info(- f"[GET_SESSION] session={session_id}, active_session={active_session is not None}, "- f"msg_count={len(messages)}, last_role={messages[-1].get('role') if messages else 'none'}"- )- if active_session:- # Keep the assistant message (including tool_calls) so the frontend can- # render the correct tool UI (e.g. CreateAgent with mini game).- # convertChatSessionToUiMessages handles isComplete=false by setting- # tool parts without output to state "input-available".- active_stream_info = ActiveStreamInfo(- turn_id=active_session.turn_id,- last_message_id=last_message_id,+ if before_sequence is None:+ active_session, last_message_id = await stream_registry.get_active_session(+ session_id, user_id+ )+ logger.info(+ f"[GET_SESSION] session={session_id}, active_session={active_session is not None}, "+ f"msg_count={len(messages)}, last_role={messages[-1].get('role') if messages else 'none'}")+ if active_session:+ active_stream_info = ActiveStreamInfo(+ turn_id=active_session.turn_id,+ last_message_id=last_message_id,+ )- # Sum token usage from session- total_prompt = sum(u.prompt_tokens for u in session.usage)- total_completion = sum(u.completion_tokens for u in session.usage)+ # Skip session metadata on "load more" — frontend only needs messages+ if before_sequence is not None:+ return SessionDetailResponse(+ id=page.session.session_id,+ created_at=page.session.started_at.isoformat(),+ updated_at=page.session.updated_at.isoformat(),+ user_id=page.session.user_id or None,+ messages=messages,+ active_stream=None,+ has_more_messages=page.has_more,+ oldest_sequence=page.oldest_sequence,+ total_prompt_tokens=0,+ total_completion_tokens=0,+ )++ total_prompt = sum(u.prompt_tokens for u in page.session.usage)+ total_completion = sum(u.completion_tokens for u in page.session.usage)return SessionDetailResponse(- id=session.session_id,- created_at=session.started_at.isoformat(),- updated_at=session.updated_at.isoformat(),- user_id=session.user_id or None,+ id=page.session.session_id,+ created_at=page.session.started_at.isoformat(),+ updated_at=page.session.updated_at.isoformat(),+ user_id=page.session.user_id or None,messages=messages,active_stream=active_stream_info,+ has_more_messages=page.has_more,+ oldest_sequence=page.oldest_sequence,total_prompt_tokens=total_prompt,total_completion_tokens=total_completion,- metadata=session.metadata,+ metadata=page.session.metadata,)diff --git a/autogpt_platform/backend/backend/copilot/db.py b/autogpt_platform/backend/backend/copilot/db.pyindex ea48cf78ce..a1dd93e752 100644--- a/autogpt_platform/backend/backend/copilot/db.py+++ b/autogpt_platform/backend/backend/copilot/db.py@@ -14,6 +14,7 @@ from prisma.types import (ChatSessionUpdateInput,ChatSessionWhereInput,)+from pydantic import BaseModelfrom backend.data import dbfrom backend.util.json import SafeJson, sanitize_string@@ -30,6 +31,15 @@ from .model import get_chat_session as get_chat_session_cachedlogger = logging.getLogger(__name__)+class PaginatedMessages(BaseModel):+ """Result of a paginated message query."""++ messages: list[ChatMessage]+ has_more: bool+ oldest_sequence: int | None+ session: ChatSessionInfo++async def get_chat_session(session_id: str) -> ChatSession | None:"""Get a chat session by ID from the database."""session = await PrismaChatSession.prisma().find_unique(@@ -39,6 +49,116 @@ async def get_chat_session(session_id: str) -> ChatSession | None:return ChatSession.from_db(session) if session else None+async def get_chat_session_metadata(session_id: str) -> ChatSessionInfo | None:+ """Get chat session metadata (without messages) for ownership validation."""+ session = await PrismaChatSession.prisma().find_unique(+ where={"id": session_id},+ )+ return ChatSessionInfo.from_db(session) if session else None+++async def get_chat_messages_paginated(+ session_id: str,+ limit: int = 50,+ before_sequence: int | None = None,+ user_id: str | None = None,+) -> PaginatedMessages | None:+ """Get paginated messages for a session, newest first.++ Verifies session existence (and ownership when ``user_id`` is provided)+ in parallel with the message query. Returns ``None`` when the session+ is not found or does not belong to the user.++ Args:+ session_id: The chat session ID.+ limit: Max messages to return.+ before_sequence: Cursor — return messages with sequence < this value.+ user_id: If provided, filters via ``Session.userId`` so only the+ session owner's messages are returned (acts as an ownership guard).+ """+ # Build session-existence / ownership check+ session_where: ChatSessionWhereInput = {"id": session_id}+ if user_id is not None:+ session_where["userId"] = user_id++ # Build message include — fetch paginated messages in the same query+ msg_include: dict[str, Any] = {+ "order_by": {"sequence": "desc"},+ "take": limit + 1,+ }+ if before_sequence is not None:+ msg_include["where"] = {"sequence": {"lt": before_sequence}}++ # Single query: session existence/ownership + paginated messages+ session = await PrismaChatSession.prisma().find_first(+ where=session_where,+ include={"Messages": msg_include},+ )++ if session is None:+ return None++ session_info = ChatSessionInfo.from_db(session)+ results = list(session.Messages) if session.Messages else []++ has_more = len(results) > limit+ results = results[:limit]++ # Reverse to ascending order+ results.reverse()++ # Tool-call boundary fix: if the oldest message is a tool message,+ # expand backward to include the preceding assistant message that+ # owns the tool_calls, so convertChatSessionMessagesToUiMessages+ # can pair them correctly.+ _BOUNDARY_SCAN_LIMIT = 10+ if results and results[0].role == "tool":+ boundary_where: dict[str, Any] = {+ "sessionId": session_id,+ "sequence": {"lt": results[0].sequence},+ }+ if user_id is not None:+ boundary_where["Session"] = {"is": {"userId": user_id}}+ extra = await PrismaChatMessage.prisma().find_many(+ where=boundary_where,+ order={"sequence": "desc"},+ take=_BOUNDARY_SCAN_LIMIT,+ )+ # Find the first non-tool message (should be the assistant)+ boundary_msgs = []+ found_owner = False+ for msg in extra:+ boundary_msgs.append(msg)+ if msg.role != "tool":+ found_owner = True+ break+ boundary_msgs.reverse()+ if not found_owner:+ logger.warning(+ "Boundary expansion did not find owning assistant message "+ "for session=%s before sequence=%s (%d msgs scanned)",+ session_id,+ results[0].sequence,+ len(extra),+ )+ if boundary_msgs:+ results = boundary_msgs + results+ # Only mark has_more if the expanded boundary isn't the+ # very start of the conversation (sequence 0).+ if boundary_msgs[0].sequence > 0:+ has_more = True++ messages = [ChatMessage.from_db(m) for m in results]+ oldest_sequence = messages[0].sequence if messages else None++ return PaginatedMessages(+ messages=messages,+ has_more=has_more,+ oldest_sequence=oldest_sequence,+ session=session_info,+ )++async def create_chat_session(session_id: str,user_id: str,diff --git a/autogpt_platform/backend/backend/copilot/db_test.py b/autogpt_platform/backend/backend/copilot/db_test.pyindex 17d670ffb1..27fa788702 100644--- a/autogpt_platform/backend/backend/copilot/db_test.py+++ b/autogpt_platform/backend/backend/copilot/db_test.py@@ -1,7 +1,341 @@+"""Unit tests for copilot.db — paginated message queries."""++from __future__ import annotations++from datetime import UTC, datetime+from typing import Any+from unittest.mock import AsyncMock, patch+import pytest+from prisma.models import ChatMessage as PrismaChatMessage+from prisma.models import ChatSession as PrismaChatSession++from backend.copilot.db import (+ PaginatedMessages,+ get_chat_messages_paginated,+ set_turn_duration,+)+from backend.copilot.model import ChatMessage as CopilotChatMessage+from backend.copilot.model import ChatSession, get_chat_session, upsert_chat_session+++def _make_msg(+ sequence: int,+ role: str = "assistant",+ content: str | None = "hello",+ tool_calls: Any = None,+) -> PrismaChatMessage:+ """Build a minimal PrismaChatMessage for testing."""+ return PrismaChatMessage(+ id=f"msg-{sequence}",+ createdAt=datetime.now(UTC),+ sessionId="sess-1",+ role=role,+ content=content,+ sequence=sequence,+ toolCalls=tool_calls,+ name=None,+ toolCallId=None,+ refusal=None,+ functionCall=None,+ )+++def _make_session(+ session_id: str = "sess-1",+ user_id: str = "user-1",+ messages: list[PrismaChatMessage] | None = None,+) -> PrismaChatSession:+ """Build a minimal PrismaChatSession for testing."""+ now = datetime.now(UTC)+ session = PrismaChatSession.model_construct(+ id=session_id,+ createdAt=now,+ updatedAt=now,+ userId=user_id,+ credentials={},+ successfulAgentRuns={},+ successfulAgentSchedules={},+ totalPromptTokens=0,+ totalCompletionTokens=0,+ title=None,+ metadata={},+ Messages=messages or [],+ )+ return session+++SESSION_ID = "sess-1"+++def mock_db():+ """Patch ChatSession.prisma().find_first and ChatMessage.prisma().find_many.++ find_first is used for the main query (session + included messages).+ find_many is used only for boundary expansion queries.+ """+ with (+ patch.object(PrismaChatSession, "prisma") as mock_session_prisma,+ patch.object(PrismaChatMessage, "prisma") as mock_msg_prisma,+ ):+ find_first = AsyncMock()+ mock_session_prisma.return_value.find_first = find_first++ find_many = AsyncMock(return_value=[])+ mock_msg_prisma.return_value.find_many = find_many++ yield find_first, find_many+++# ---------- Basic pagination ----------+++async def test_basic_page_returns_messages_ascending(+ mock_db: tuple[AsyncMock, AsyncMock],+):+ """Messages are returned in ascending sequence order."""+ find_first, _ = mock_db+ find_first.return_value = _make_session(+ messages=[_make_msg(3), _make_msg(2), _make_msg(1)],+ )++ page = await get_chat_messages_paginated(SESSION_ID, limit=5)++ assert isinstance(page, PaginatedMessages)+ assert [m.sequence for m in page.messages] == [1, 2, 3]+ assert page.has_more is False+ assert page.oldest_sequence == 1+++async def test_has_more_when_results_exceed_limit(+ mock_db: tuple[AsyncMock, AsyncMock],+):+ """has_more is True when DB returns more than limit items."""+ find_first, _ = mock_db+ find_first.return_value = _make_session(+ messages=[_make_msg(3), _make_msg(2), _make_msg(1)],+ )++ page = await get_chat_messages_paginated(SESSION_ID, limit=2)++ assert page is not None+ assert page.has_more is True+ assert len(page.messages) == 2+ assert [m.sequence for m in page.messages] == [2, 3]+++async def test_empty_session_returns_no_messages(+ mock_db: tuple[AsyncMock, AsyncMock],+):+ find_first, _ = mock_db+ find_first.return_value = _make_session(messages=[])++ page = await get_chat_messages_paginated(SESSION_ID, limit=50)++ assert page is not None+ assert page.messages == []+ assert page.has_more is False+ assert page.oldest_sequence is None+++async def test_before_sequence_filters_correctly(+ mock_db: tuple[AsyncMock, AsyncMock],+):+ """before_sequence is passed as a where filter inside the Messages include."""+ find_first, _ = mock_db+ find_first.return_value = _make_session(+ messages=[_make_msg(2), _make_msg(1)],+ )++ await get_chat_messages_paginated(SESSION_ID, limit=50, before_sequence=5)++ call_kwargs = find_first.call_args+ include = call_kwargs.kwargs.get("include") or call_kwargs[1].get("include")+ assert include["Messages"]["where"] == {"sequence": {"lt": 5}}+++async def test_no_where_on_messages_without_before_sequence(+ mock_db: tuple[AsyncMock, AsyncMock],+):+ """Without before_sequence, the Messages include has no where clause."""+ find_first, _ = mock_db+ find_first.return_value = _make_session(messages=[_make_msg(1)])++ await get_chat_messages_paginated(SESSION_ID, limit=50)++ call_kwargs = find_first.call_args+ include = call_kwargs.kwargs.get("include") or call_kwargs[1].get("include")+ assert "where" not in include["Messages"]+++async def test_user_id_filter_applied_to_session_where(+ mock_db: tuple[AsyncMock, AsyncMock],+):+ """user_id adds a userId filter to the session-level where clause."""+ find_first, _ = mock_db+ find_first.return_value = _make_session(messages=[_make_msg(1)])++ await get_chat_messages_paginated(SESSION_ID, limit=50, user_id="user-abc")++ call_kwargs = find_first.call_args+ where = call_kwargs.kwargs.get("where") or call_kwargs[1].get("where")+ assert where["userId"] == "user-abc"+++async def test_session_not_found_returns_none(+ mock_db: tuple[AsyncMock, AsyncMock],+):+ """Returns None when session doesn't exist or user doesn't own it."""+ find_first, _ = mock_db+ find_first.return_value = None++ page = await get_chat_messages_paginated(SESSION_ID, limit=50)++ assert page is None+++async def test_session_info_included_in_result(+ mock_db: tuple[AsyncMock, AsyncMock],+):+ """PaginatedMessages includes session metadata."""+ find_first, _ = mock_db+ find_first.return_value = _make_session(messages=[_make_msg(1)])++ page = await get_chat_messages_paginated(SESSION_ID, limit=50)++ assert page is not None+ assert page.session.session_id == SESSION_ID+++# ---------- Backward boundary expansion ----------+++async def test_boundary_expansion_includes_assistant(+ mock_db: tuple[AsyncMock, AsyncMock],+):+ """When page starts with a tool message, expand backward to include+ the owning assistant message."""+ find_first, find_many = mock_db+ find_first.return_value = _make_session(+ messages=[_make_msg(5, role="tool"), _make_msg(4, role="tool")],+ )+ find_many.return_value = [_make_msg(3, role="assistant")]++ page = await get_chat_messages_paginated(SESSION_ID, limit=5)++ assert page is not None+ assert [m.sequence for m in page.messages] == [3, 4, 5]+ assert page.messages[0].role == "assistant"+ assert page.oldest_sequence == 3+++async def test_boundary_expansion_includes_multiple_tool_msgs(+ mock_db: tuple[AsyncMock, AsyncMock],+):+ """Boundary expansion scans past consecutive tool messages to find+ the owning assistant."""+ find_first, find_many = mock_db+ find_first.return_value = _make_session(+ messages=[_make_msg(7, role="tool")],+ )+ find_many.return_value = [+ _make_msg(6, role="tool"),+ _make_msg(5, role="tool"),+ _make_msg(4, role="assistant"),+ ]++ page = await get_chat_messages_paginated(SESSION_ID, limit=5)++ assert page is not None+ assert [m.sequence for m in page.messages] == [4, 5, 6, 7]+ assert page.messages[0].role == "assistant"+++async def test_boundary_expansion_sets_has_more_when_not_at_start(+ mock_db: tuple[AsyncMock, AsyncMock],+):+ """After boundary expansion, has_more=True if expanded msgs aren't at seq 0."""+ find_first, find_many = mock_db+ find_first.return_value = _make_session(+ messages=[_make_msg(3, role="tool")],+ )+ find_many.return_value = [_make_msg(2, role="assistant")]++ page = await get_chat_messages_paginated(SESSION_ID, limit=5)++ assert page is not None+ assert page.has_more is True+++async def test_boundary_expansion_no_has_more_at_conversation_start(+ mock_db: tuple[AsyncMock, AsyncMock],+):+ """has_more stays False when boundary expansion reaches seq 0."""+ find_first, find_many = mock_db+ find_first.return_value = _make_session(+ messages=[_make_msg(1, role="tool")],+ )+ find_many.return_value = [_make_msg(0, role="assistant")]++ page = await get_chat_messages_paginated(SESSION_ID, limit=5)++ assert page is not None+ assert page.has_more is False+ assert page.oldest_sequence == 0+++async def test_no_boundary_expansion_when_first_msg_not_tool(+ mock_db: tuple[AsyncMock, AsyncMock],+):+ """No boundary expansion when the first message is not a tool message."""+ find_first, find_many = mock_db+ find_first.return_value = _make_session(+ messages=[_make_msg(3, role="user"), _make_msg(2, role="assistant")],+ )++ page = await get_chat_messages_paginated(SESSION_ID, limit=5)++ assert page is not None+ assert find_many.call_count == 0+ assert [m.sequence for m in page.messages] == [2, 3]+++async def test_boundary_expansion_warns_when_no_owner_found(+ mock_db: tuple[AsyncMock, AsyncMock],+):+ """When boundary scan doesn't find a non-tool message, a warning is logged+ and the boundary messages are still included."""+ find_first, find_many = mock_db+ find_first.return_value = _make_session(+ messages=[_make_msg(10, role="tool")],+ )+ find_many.return_value = [_make_msg(i, role="tool") for i in range(9, -1, -1)]++ with patch("backend.copilot.db.logger") as mock_logger:+ page = await get_chat_messages_paginated(SESSION_ID, limit=5)+ mock_logger.warning.assert_called_once()++ assert page is not None+ assert page.messages[0].role == "tool"+ assert len(page.messages) > 1+-from .db import set_turn_duration-from .model import ChatMessage, ChatSession, get_chat_session, upsert_chat_session+# ---------- Turn duration (integration tests) ----------@pytest.mark.asyncio(loop_scope="session")@@ -15,8 +349,8 @@ async def test_set_turn_duration_updates_cache_in_place(setup_test_user, test_us"""session = ChatSession.new(user_id=test_user_id, dry_run=False)session.messages = [- ChatMessage(role="user", content="hello"),- ChatMessage(role="assistant", content="hi there"),+ CopilotChatMessage(role="user", content="hello"),+ CopilotChatMessage(role="assistant", content="hi there"),]session = await upsert_chat_session(session)@@ -41,7 +375,7 @@ async def test_set_turn_duration_no_assistant_message(setup_test_user, test_user"""set_turn_duration is a no-op when there are no assistant messages."""session = ChatSession.new(user_id=test_user_id, dry_run=False)session.messages = [- ChatMessage(role="user", content="hello"),+ CopilotChatMessage(role="user", content="hello"),]session = await upsert_chat_session(session)diff --git a/autogpt_platform/backend/backend/copilot/model.py b/autogpt_platform/backend/backend/copilot/model.pyindex e1d3b28b79..9bb7964b93 100644--- a/autogpt_platform/backend/backend/copilot/model.py+++ b/autogpt_platform/backend/backend/copilot/model.py@@ -64,6 +64,7 @@ class ChatMessage(BaseModel):refusal: str | None = Nonetool_calls: list[dict] | None = Nonefunction_call: dict | None = None+ sequence: int | None = Noneduration_ms: int | None = None@staticmethod@@ -77,6 +78,7 @@ class ChatMessage(BaseModel):refusal=prisma_message.refusal,tool_calls=_parse_json_field(prisma_message.toolCalls),function_call=_parse_json_field(prisma_message.functionCall),+ sequence=prisma_message.sequence,duration_ms=prisma_message.durationMs,)diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/CopilotPage.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/CopilotPage.tsxindex c4cc08a501..46fbe1ed6e 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/CopilotPage.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/CopilotPage.tsx@@ -89,6 +89,10 @@ export function CopilotPage() {isUploadingFiles,isUserLoading,isLoggedIn,+ // Pagination+ hasMoreMessages,+ isLoadingMore,+ loadMore,// Mobile drawerisMobile,isDrawerOpen,@@ -197,6 +201,9 @@ export function CopilotPage() {onSend={onSend}onStop={stop}isUploadingFiles={isUploadingFiles}+ hasMoreMessages={hasMoreMessages}+ isLoadingMore={isLoadingMore}+ onLoadMore={loadMore}droppedFiles={droppedFiles}onDroppedFilesConsumed={handleDroppedFilesConsumed}historicalDurations={historicalDurations}diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatContainer/ChatContainer.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatContainer/ChatContainer.tsxindex 38cec3d38c..6e67c8fc48 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatContainer/ChatContainer.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatContainer/ChatContainer.tsx@@ -27,6 +27,9 @@ export interface ChatContainerProps {onSend: (message: string, files?: File[]) => void | Promise<void>;onStop: () => void;isUploadingFiles?: boolean;+ hasMoreMessages?: boolean;+ isLoadingMore?: boolean;+ onLoadMore?: () => void;/** Files dropped onto the chat window. */droppedFiles?: File[];/** Called after droppedFiles have been consumed by ChatInput. */@@ -48,6 +51,9 @@ export const ChatContainer = ({onSend,onStop,isUploadingFiles,+ hasMoreMessages,+ isLoadingMore,+ onLoadMore,droppedFiles,onDroppedFilesConsumed,historicalDurations,@@ -102,6 +108,9 @@ export const ChatContainer = ({error={error}isLoading={isLoadingSession}sessionID={sessionId}+ hasMoreMessages={hasMoreMessages}+ isLoadingMore={isLoadingMore}+ onLoadMore={onLoadMore}onRetry={handleRetry}historicalDurations={historicalDurations}/>diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatMessagesContainer/ChatMessagesContainer.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatMessagesContainer/ChatMessagesContainer.tsxindex 205fa74bd0..5161103f4b 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatMessagesContainer/ChatMessagesContainer.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatMessagesContainer/ChatMessagesContainer.tsx@@ -1,4 +1,4 @@-import { useEffect, useMemo, useRef } from "react";+import { useMemo, useState } from "react";import {Conversation,ConversationContent,@@ -11,6 +11,8 @@ import {} from "@/components/ai-elements/message";import { LoadingSpinner } from "@/components/atoms/LoadingSpinner/LoadingSpinner";import { FileUIPart, UIDataTypes, UIMessage, UITools } from "ai";+import { useEffect, useLayoutEffect, useRef } from "react";+import { useStickToBottomContext } from "use-stick-to-bottom";import { TOOL_PART_PREFIX } from "../JobStatsBar/constants";import { TurnStatsBar } from "../JobStatsBar/TurnStatsBar";import { useElapsedTimer } from "../JobStatsBar/useElapsedTimer";@@ -37,6 +39,9 @@ interface Props {error: Error | undefined;isLoading: boolean;sessionID?: string | null;+ hasMoreMessages?: boolean;+ isLoadingMore?: boolean;+ onLoadMore?: () => void;onRetry?: () => void;historicalDurations?: Map<string, number>;}@@ -106,15 +111,120 @@ function extractGraphExecId(return null;}+/**+ * Triggers `onLoadMore` when scrolled near the top, and preserves the+ * user's scroll position after older messages are prepended to the DOM.+ *+ * Scroll preservation works by:+ * 1. Capturing `scrollHeight` / `scrollTop` in the observer callback+ * (synchronous, before React re-renders).+ * 2. Restoring `scrollTop` in a `useLayoutEffect` keyed on+ * `messageCount` so it only fires when messages actually change+ * (not on intermediate renders like the loading-spinner toggle).+ */+function LoadMoreSentinel({+ hasMore,+ isLoading,+ messageCount,+ onLoadMore,+}: {+ hasMore: boolean;+ isLoading: boolean;+ messageCount: number;+ onLoadMore: () => void;+}) {+ const sentinelRef = useRef<HTMLDivElement>(null);+ const onLoadMoreRef = useRef(onLoadMore);+ onLoadMoreRef.current = onLoadMore;+ // Pre-mutation scroll snapshot, written synchronously before onLoadMore+ const scrollSnapshotRef = useRef({ scrollHeight: 0, scrollTop: 0 });+ const { scrollRef } = useStickToBottomContext();++ // IntersectionObserver to trigger load when sentinel is near viewport.+ // Only fires when the container is actually scrollable to prevent+ // exhausting all pages when content fits without scrolling.+ useEffect(() => {+ if (!sentinelRef.current || !hasMore || isLoading) return;+ const observer = new IntersectionObserver(+ ([entry]) => {+ if (!entry.isIntersecting) return;+ const scrollParent =+ sentinelRef.current?.closest('[role="log"]') ??+ sentinelRef.current?.parentElement;+ if (+ scrollParent &&+ scrollParent.scrollHeight <= scrollParent.clientHeight+ )+ return;+ // Capture scroll metrics *before* the state update+ const el = scrollRef.current;+ if (el) {+ scrollSnapshotRef.current = {+ scrollHeight: el.scrollHeight,+ scrollTop: el.scrollTop,+ };+ }+ onLoadMoreRef.current();+ },+ { rootMargin: "200px 0px 0px 0px" },+ );+ observer.observe(sentinelRef.current);+ return () => observer.disconnect();+ }, [hasMore, isLoading, scrollRef]);++ // After React commits new DOM nodes (prepended messages), adjust+ // scrollTop so the user stays at the same visual position.+ // Keyed on messageCount so it only fires when messages actually+ // change — NOT on intermediate renders (loading spinner, etc.)+ // that would consume the snapshot too early.+ useLayoutEffect(() => {+ const el = scrollRef.current;+ const { scrollHeight: prevHeight, scrollTop: prevTop } =+ scrollSnapshotRef.current;+ if (!el || prevHeight === 0) return;+ const delta = el.scrollHeight - prevHeight;+ if (delta > 0) {+ el.scrollTop = prevTop + delta;+ }+ scrollSnapshotRef.current = { scrollHeight: 0, scrollTop: 0 };+ }, [messageCount, scrollRef]);++ return (+ <div ref={sentinelRef} className="flex justify-center py-1">+ {isLoading && <LoadingSpinner className="h-5 w-5 text-neutral-400" />}+ </div>+ );+}+export function ChatMessagesContainer({messages,status,error,isLoading,sessionID,+ hasMoreMessages,+ isLoadingMore,+ onLoadMore,onRetry,historicalDurations,}: Props) {+ // Hide the container for one frame when messages first load so+ // StickToBottom can scroll to the bottom before the user sees it.+ const [settled, setSettled] = useState(false);+ const [prevSessionID, setPrevSessionID] = useState(sessionID);+ if (sessionID !== prevSessionID) {+ setPrevSessionID(sessionID);+ if (settled) setSettled(false);+ }+ const messagesReady = messages.length > 0 || !isLoading;+ useEffect(() => {+ if (settled || !messagesReady) return;+ const raf = requestAnimationFrame(() => setSettled(true));+ return () => cancelAnimationFrame(raf);+ }, [settled, messagesReady]);+ // opacity-0 only during the single frame between messages arriving and scroll settling+ const hideForScroll = messagesReady && !settled;+const lastMessage = messages[messages.length - 1];const graphExecId = useMemo(() => extractGraphExecId(messages), [messages]);@@ -162,13 +272,27 @@ export function ChatMessagesContainer({});return (- <Conversation className="min-h-0 flex-1">- <ConversationContent className="flex flex-1 flex-col gap-6 px-3 py-6">+ <Conversation+ key={sessionID ?? "new"}+ resize={settled ? "smooth" : "instant"}+ className={+ "min-h-0 flex-1 " ++ (hideForScroll+ ? "opacity-0"+ : "opacity-100 transition-opacity duration-100 ease-out")+ }+ >+ <ConversationContent className="flex min-h-full flex-1 flex-col gap-6 px-3 py-6">+ {hasMoreMessages && onLoadMore && (+ <LoadMoreSentinel+ hasMore={hasMoreMessages}+ isLoading={!!isLoadingMore}+ messageCount={messages.length}+ onLoadMore={onLoadMore}+ />+ )}{isLoading && messages.length === 0 && (- <div- className="flex flex-1 items-center justify-center"- style={{ minHeight: "calc(100vh - 12rem)" }}- >+ <div className="flex flex-1 items-center justify-center"><LoadingSpinner className="text-neutral-600" /></div>)}diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/helpers/convertChatSessionToUiMessages.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/helpers/convertChatSessionToUiMessages.tsindex 2211c27277..5021d661f0 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/helpers/convertChatSessionToUiMessages.ts+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/helpers/convertChatSessionToUiMessages.ts@@ -6,6 +6,7 @@ interface SessionChatMessage {content: string | null;tool_call_id: string | null;tool_calls: unknown[] | null;+ sequence: number | null;duration_ms: number | null;}@@ -35,6 +36,7 @@ function coerceSessionChatMessages(? null: String(msg.tool_call_id),tool_calls: Array.isArray(msg.tool_calls) ? msg.tool_calls : null,+ sequence: typeof msg.sequence === "number" ? msg.sequence : null,duration_ms:typeof msg.duration_ms === "number" ? msg.duration_ms : null,};@@ -101,10 +103,67 @@ function toToolInput(rawArguments: unknown): unknown {return {};}+/**+ * Concatenate two UIMessage arrays, merging consecutive assistant messages+ * at the join point so that reasoning + response parts stay in a single bubble.+ *+ * Within each page, `convertChatSessionMessagesToUiMessages` already merges+ * consecutive assistant DB rows. This handles the boundary between pages+ * (or between older-pages and the current/streaming page).+ */+export function concatWithAssistantMerge(+ a: UIMessage<unknown, UIDataTypes, UITools>[],+ b: UIMessage<unknown, UIDataTypes, UITools>[],+): UIMessage<unknown, UIDataTypes, UITools>[] {+ if (a.length === 0) return b;+ if (b.length === 0) return a;+ const last = a[a.length - 1];+ const first = b[0];+ if (last.role === "assistant" && first.role === "assistant") {+ return [+ ...a.slice(0, -1),+ { ...last, parts: [...last.parts, ...first.parts] },+ ...b.slice(1),+ ];+ }+ return [...a, ...b];+}++/**+ * Extract a toolCallId → output map from raw API messages.+ * Used to provide cross-page tool output context when converting+ * older pages that may have assistant tool_calls whose results+ * are in a newer page.+ */+export function extractToolOutputsFromRaw(+ rawMessages: unknown[],+): Map<string, unknown> {+ const map = new Map<string, unknown>();+ for (const raw of rawMessages) {+ if (!raw || typeof raw !== "object") continue;+ const msg = raw as Record<string, unknown>;+ if (+ msg.role === "tool" &&+ typeof msg.tool_call_id === "string" &&+ msg.content != null+ ) {+ map.set(+ msg.tool_call_id,+ typeof msg.content === "string" ? msg.content : String(msg.content),+ );+ }+ }+ return map;+}+export function convertChatSessionMessagesToUiMessages(sessionId: string,rawMessages: unknown[],- options?: { isComplete?: boolean },+ options?: {+ isComplete?: boolean;+ /** Tool outputs from adjacent pages, for cross-page tool_call matching. */+ extraToolOutputs?: Map<string, unknown>;+ },): {messages: UIMessage<unknown, UIDataTypes, UITools>[];durations: Map<string, number>;@@ -112,6 +171,14 @@ export function convertChatSessionMessagesToUiMessages(const messages = coerceSessionChatMessages(rawMessages);const toolOutputsByCallId = new Map<string, unknown>();+ // Seed with extra tool outputs from adjacent pages first;+ // outputs from this page will override if present in both.+ if (options?.extraToolOutputs) {+ for (const [id, output] of options.extraToolOutputs) {+ toolOutputsByCallId.set(id, output);+ }+ }+for (const msg of messages) {if (msg.role !== "tool") continue;if (!msg.tool_call_id) continue;@@ -122,7 +189,7 @@ export function convertChatSessionMessagesToUiMessages(const uiMessages: UIMessage<unknown, UIDataTypes, UITools>[] = [];const durations = new Map<string, number>();- messages.forEach((msg, index) => {+ messages.forEach((msg) => {if (msg.role === "tool") return;if (msg.role !== "user" && msg.role !== "assistant") return;@@ -200,7 +267,7 @@ export function convertChatSessionMessagesToUiMessages(return;}- const msgId = `${sessionId}-${index}`;+ const msgId = `${sessionId}-seq-${msg.sequence}`;uiMessages.push({id: msgId,role: msg.role,diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/useChatSession.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/useChatSession.tsindex 1e3bd583ec..e001792456 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/useChatSession.ts+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/useChatSession.ts@@ -15,7 +15,7 @@ export function useChatSession() {const [sessionId, setSessionId] = useQueryState("sessionId", parseAsString);const queryClient = useQueryClient();- const sessionQuery = useGetV2GetSession(sessionId ?? "", {+ const sessionQuery = useGetV2GetSession(sessionId ?? "", undefined, {query: {enabled: !!sessionId,staleTime: Infinity, // Manual invalidation on session switch@@ -57,6 +57,17 @@ export function useChatSession() {return !!sessionQuery.data.data.active_stream;}, [sessionQuery.data, sessionQuery.isFetching, sessionId]);+ // Pagination metadata from the initial page load+ const hasMoreMessages = useMemo(() => {+ if (sessionQuery.data?.status !== 200) return false;+ return !!sessionQuery.data.data.has_more_messages;+ }, [sessionQuery.data]);++ const oldestSequence = useMemo(() => {+ if (sessionQuery.data?.status !== 200) return null;+ return sessionQuery.data.data.oldest_sequence ?? null;+ }, [sessionQuery.data]);+// Memoize so the effect in useCopilotPage doesn't infinite-loop on a new// array reference every render. Re-derives only when query data changes.// When the session is complete (no active stream), mark dangling tool@@ -127,12 +138,22 @@ export function useChatSession() {}}+ // Raw messages from the initial page — exposed for cross-page+ // tool output matching by useLoadMoreMessages.+ const rawSessionMessages =+ sessionQuery.data?.status === 200+ ? ((sessionQuery.data.data.messages ?? []) as unknown[])+ : [];+return {sessionId,setSessionId,hydratedMessages,+ rawSessionMessages,historicalDurations,hasActiveStream,+ hasMoreMessages,+ oldestSequence,isLoadingSession: sessionQuery.isLoading,isSessionError: sessionQuery.isError,createSession,diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/useCopilotPage.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/useCopilotPage.tsindex 68db690863..4d97a9619d 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/useCopilotPage.ts+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/useCopilotPage.ts@@ -12,10 +12,12 @@ import { useQueryClient } from "@tanstack/react-query";import type { FileUIPart } from "ai";import { Flag, useGetFlag } from "@/services/feature-flags/use-get-flag";import { useEffect, useRef, useState } from "react";+import { concatWithAssistantMerge } from "./helpers/convertChatSessionToUiMessages";import { useCopilotUIStore } from "./store";import { useChatSession } from "./useChatSession";import { useCopilotNotifications } from "./useCopilotNotifications";import { useCopilotStream } from "./useCopilotStream";+import { useLoadMoreMessages } from "./useLoadMoreMessages";import { useWorkflowImportAutoSubmit } from "./useWorkflowImportAutoSubmit";const TITLE_POLL_INTERVAL_MS = 2_000;@@ -47,8 +49,11 @@ export function useCopilotPage() {sessionId,setSessionId,hydratedMessages,+ rawSessionMessages,historicalDurations,hasActiveStream,+ hasMoreMessages,+ oldestSequence,isLoadingSession,isSessionError,createSession,@@ -57,7 +62,7 @@ export function useCopilotPage() {} = useChatSession();const {- messages,+ messages: currentMessages,sendMessage,stop,status,@@ -75,6 +80,19 @@ export function useCopilotPage() {copilotMode: isModeToggleEnabled ? copilotMode : undefined,});+ const { olderMessages, hasMore, isLoadingMore, loadMore } =+ useLoadMoreMessages({+ sessionId,+ initialOldestSequence: oldestSequence,+ initialHasMore: hasMoreMessages,+ initialPageRawMessages: rawSessionMessages,+ });++ // Combine older (paginated) messages with current page messages,+ // merging consecutive assistant UIMessages at the page boundary so+ // reasoning + response parts stay in a single bubble.+ const messages = concatWithAssistantMerge(olderMessages, currentMessages);+useCopilotNotifications(sessionId);// --- Delete session ---@@ -371,6 +389,10 @@ export function useCopilotPage() {isLoggedIn,createSession,onSend,+ // Pagination+ hasMoreMessages: hasMore,+ isLoadingMore,+ loadMore,// Mobile drawerisMobile,isDrawerOpen,diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/useLoadMoreMessages.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/useLoadMoreMessages.tsnew file mode 100644index 0000000000..13efd957f9--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/useLoadMoreMessages.ts@@ -0,0 +1,161 @@+import { getV2GetSession } from "@/app/api/__generated__/endpoints/chat/chat";+import type { UIDataTypes, UIMessage, UITools } from "ai";+import { useEffect, useMemo, useRef, useState } from "react";+import {+ convertChatSessionMessagesToUiMessages,+ extractToolOutputsFromRaw,+} from "./helpers/convertChatSessionToUiMessages";++interface UseLoadMoreMessagesArgs {+ sessionId: string | null;+ initialOldestSequence: number | null;+ initialHasMore: boolean;+ /** Raw messages from the initial page, used for cross-page tool output matching. */+ initialPageRawMessages: unknown[];+}++const MAX_CONSECUTIVE_ERRORS = 3;+const MAX_OLDER_MESSAGES = 2000;++export function useLoadMoreMessages({+ sessionId,+ initialOldestSequence,+ initialHasMore,+ initialPageRawMessages,+}: UseLoadMoreMessagesArgs) {+ // Store accumulated raw messages from all older pages (in ascending order).+ // Re-converting them all together ensures tool outputs are matched across+ // inter-page boundaries.+ const [olderRawMessages, setOlderRawMessages] = useState<unknown[]>([]);+ const [oldestSequence, setOldestSequence] = useState<number | null>(+ initialOldestSequence,+ );+ const [hasMore, setHasMore] = useState(initialHasMore);+ const [isLoadingMore, setIsLoadingMore] = useState(false);+ const isLoadingMoreRef = useRef(false);+ const consecutiveErrorsRef = useRef(0);+ // Epoch counter to discard stale loadMore responses after a reset+ const epochRef = useRef(0);++ // Track the sessionId and initial cursor to reset state on change+ const prevSessionIdRef = useRef(sessionId);+ const prevInitialOldestRef = useRef(initialOldestSequence);++ // Sync initial values from parent when they change+ useEffect(() => {+ if (prevSessionIdRef.current !== sessionId) {+ // Session changed — full reset+ prevSessionIdRef.current = sessionId;+ prevInitialOldestRef.current = initialOldestSequence;+ setOlderRawMessages([]);+ setOldestSequence(initialOldestSequence);+ setHasMore(initialHasMore);+ setIsLoadingMore(false);+ isLoadingMoreRef.current = false;+ consecutiveErrorsRef.current = 0;+ epochRef.current += 1;+ } else if (+ prevInitialOldestRef.current !== initialOldestSequence &&+ olderRawMessages.length > 0+ ) {+ // Same session but initial window shifted (e.g. new messages arrived) —+ // clear paged state to avoid gaps/duplicates+ prevInitialOldestRef.current = initialOldestSequence;+ setOlderRawMessages([]);+ setOldestSequence(initialOldestSequence);+ setHasMore(initialHasMore);+ setIsLoadingMore(false);+ isLoadingMoreRef.current = false;+ consecutiveErrorsRef.current = 0;+ epochRef.current += 1;+ } else {+ // Update from parent when initial data changes (e.g. refetch)+ prevInitialOldestRef.current = initialOldestSequence;+ setOldestSequence(initialOldestSequence);+ setHasMore(initialHasMore);+ }+ }, [sessionId, initialOldestSequence, initialHasMore]);++ // Convert all accumulated raw messages in one pass so tool outputs+ // are matched across inter-page boundaries. Initial page tool outputs+ // are included via extraToolOutputs to handle the boundary between+ // the last older page and the initial/streaming page.+ const olderMessages: UIMessage<unknown, UIDataTypes, UITools>[] =+ useMemo(() => {+ if (!sessionId || olderRawMessages.length === 0) return [];+ const extraToolOutputs =+ initialPageRawMessages.length > 0+ ? extractToolOutputsFromRaw(initialPageRawMessages)+ : undefined;+ return convertChatSessionMessagesToUiMessages(+ sessionId,+ olderRawMessages,+ { isComplete: true, extraToolOutputs },+ ).messages;+ }, [sessionId, olderRawMessages, initialPageRawMessages]);++ async function loadMore() {+ if (+ !sessionId ||+ !hasMore ||+ isLoadingMoreRef.current ||+ oldestSequence === null+ )+ return;++ const requestEpoch = epochRef.current;+ isLoadingMoreRef.current = true;+ setIsLoadingMore(true);+ try {+ const response = await getV2GetSession(sessionId, {+ limit: 50,+ before_sequence: oldestSequence,+ });++ // Discard response if session/pagination was reset while awaiting+ if (epochRef.current !== requestEpoch) return;++ if (response.status !== 200) {+ consecutiveErrorsRef.current += 1;+ console.warn(+ `[loadMore] Failed to load messages (status=${response.status}, attempt=${consecutiveErrorsRef.current})`,+ );+ if (consecutiveErrorsRef.current >= MAX_CONSECUTIVE_ERRORS) {+ setHasMore(false);+ }+ return;+ }++ consecutiveErrorsRef.current = 0;++ const newRaw = (response.data.messages ?? []) as unknown[];+ setOlderRawMessages((prev) => {+ const merged = [...newRaw, ...prev];+ if (merged.length > MAX_OLDER_MESSAGES) {+ return merged.slice(merged.length - MAX_OLDER_MESSAGES);+ }+ return merged;+ });+ setOldestSequence(response.data.oldest_sequence ?? null);+ if (newRaw.length + olderRawMessages.length >= MAX_OLDER_MESSAGES) {+ setHasMore(false);+ } else {+ setHasMore(!!response.data.has_more_messages);+ }+ } catch (error) {+ if (epochRef.current !== requestEpoch) return;+ consecutiveErrorsRef.current += 1;+ console.warn("[loadMore] Network error:", error);+ if (consecutiveErrorsRef.current >= MAX_CONSECUTIVE_ERRORS) {+ setHasMore(false);+ }+ } finally {+ if (epochRef.current === requestEpoch) {+ isLoadingMoreRef.current = false;+ setIsLoadingMore(false);+ }+ }+ }++ return { olderMessages, hasMore, isLoadingMore, loadMore };+}diff --git a/autogpt_platform/frontend/src/app/api/openapi.json b/autogpt_platform/frontend/src/app/api/openapi.jsonindex b876a64e23..a17b03f6df 100644--- a/autogpt_platform/frontend/src/app/api/openapi.json+++ b/autogpt_platform/frontend/src/app/api/openapi.json@@ -1134,7 +1134,7 @@"get": {"tags": ["v2", "chat", "chat"],"summary": "Get Session",- "description": "Retrieve the details of a specific chat session.\n\nLooks up a chat session by ID for the given user (if authenticated) and returns all session data including messages.\nIf there's an active stream for this session, returns active_stream info for reconnection.\n\nArgs:\n session_id: The unique identifier for the desired chat session.\n user_id: The optional authenticated user ID, or None for anonymous access.\n\nReturns:\n SessionDetailResponse: Details for the requested session, including active_stream info if applicable.",+ "description": "Retrieve the details of a specific chat session.\n\nSupports cursor-based pagination via ``limit`` and ``before_sequence``.\nWhen no pagination params are provided, returns the most recent messages.\n\nArgs:\n session_id: The unique identifier for the desired chat session.\n user_id: The authenticated user's ID.\n limit: Maximum number of messages to return (1-200, default 50).\n before_sequence: Return messages with sequence < this value (cursor).\n\nReturns:\n SessionDetailResponse: Details for the requested session, including\n active_stream info and pagination metadata.","operationId": "getV2GetSession","security": [{ "HTTPBearerJWT": [] }],"parameters": [@@ -1143,6 +1143,30 @@"in": "path","required": true,"schema": { "type": "string", "title": "Session Id" }+ },+ {+ "name": "limit",+ "in": "query",+ "required": false,+ "schema": {+ "type": "integer",+ "maximum": 200,+ "minimum": 1,+ "default": 50,+ "title": "Limit"+ }+ },+ {+ "name": "before_sequence",+ "in": "query",+ "required": false,+ "schema": {+ "anyOf": [+ { "type": "integer", "minimum": 0 },+ { "type": "null" }+ ],+ "title": "Before Sequence"+ }}],"responses": {@@ -12444,6 +12468,15 @@{ "type": "null" }]},+ "has_more_messages": {+ "type": "boolean",+ "title": "Has More Messages",+ "default": false+ },+ "oldest_sequence": {+ "anyOf": [{ "type": "integer" }, { "type": "null" }],+ "title": "Oldest Sequence"+ },"total_prompt_tokens": {"type": "integer","title": "Total Prompt Tokens",diff --git a/autogpt_platform/frontend/src/components/ai-elements/conversation.tsx b/autogpt_platform/frontend/src/components/ai-elements/conversation.tsxindex 7c67361284..cda40eb57f 100644--- a/autogpt_platform/frontend/src/components/ai-elements/conversation.tsx+++ b/autogpt_platform/frontend/src/components/ai-elements/conversation.tsx@@ -1,7 +1,6 @@"use client";import { Button } from "@/components/ui/button";-import { scrollbarStyles } from "@/components/styles/scrollbars";import { cn } from "@/lib/utils";import { ArrowDownIcon } from "lucide-react";import type { ComponentProps } from "react";@@ -12,12 +11,8 @@ export type ConversationProps = ComponentProps<typeof StickToBottom>;export const Conversation = ({ className, ...props }: ConversationProps) => (<StickToBottom- className={cn(- "relative flex-1 overflow-y-hidden",- scrollbarStyles,- className,- )}- initial="smooth"+ className={cn("relative flex-1 overflow-y-hidden", className)}+ initial="instant"resize="smooth"role="log"{...props}@@ -30,10 +25,15 @@ export type ConversationContentProps = ComponentProps<export const ConversationContent = ({className,+ scrollClassName,...props}: ConversationContentProps) => (<StickToBottom.ContentclassName={cn("flex flex-col gap-8 p-4", className)}+ scrollClassName={cn(+ "scrollbar-thin scrollbar-track-transparent scrollbar-thumb-zinc-300",+ scrollClassName,+ )}{...props}/>);