Skip to content

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.

fix(platform/copilot): revert forward pagination, add visibility guarantee for blank chat (#12831)

Zamil Majdy6d770d99179a
diff --git a/autogpt_platform/backend/backend/api/features/chat/routes.py b/autogpt_platform/backend/backend/api/features/chat/routes.py
index 63d49ac43a..cbde6a40fe 100644
--- a/autogpt_platform/backend/backend/api/features/chat/routes.py
+++ b/autogpt_platform/backend/backend/api/features/chat/routes.py
@@ -190,8 +190,6 @@ class SessionDetailResponse(BaseModel):
active_stream: ActiveStreamInfo | None = None # Present if stream is still active
has_more_messages: bool = False
oldest_sequence: int | None = None
- newest_sequence: int | None = None
- forward_paginated: bool = False
total_prompt_tokens: int = 0
total_completion_tokens: int = 0
metadata: ChatSessionMetadata = ChatSessionMetadata()
@@ -456,113 +454,39 @@ 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,
- description="Maximum number of messages to return.",
- ),
- before_sequence: int | None = Query(
- default=None,
- ge=0,
- description=(
- "Backward pagination cursor. Return messages with sequence number "
- "strictly less than this value. Used by active-session load-more. "
- "Mutually exclusive with after_sequence."
- ),
- ),
- after_sequence: int | None = Query(
- default=None,
- ge=0,
- description=(
- "Forward pagination cursor. Return messages with sequence number "
- "strictly greater than this value. Used by completed-session load-more. "
- "Mutually exclusive with before_sequence."
- ),
- ),
+ 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.
- Supports cursor-based pagination via ``limit``, ``before_sequence``, and
- ``after_sequence``. The two cursor parameters are mutually exclusive.
-
- On the initial load (no cursor provided) of a completed session, messages
- are returned in forward order starting from sequence 0 so the user always
- sees their initial prompt. Active sessions use the legacy newest-first
- order so streaming context is preserved.
+ Supports cursor-based pagination via ``limit`` and ``before_sequence``.
+ When no pagination params are provided, returns the most recent messages.
"""
- if before_sequence is not None and after_sequence is not None:
- raise HTTPException(
- status_code=400,
- detail="before_sequence and after_sequence are mutually exclusive",
- )
-
- is_initial_load = before_sequence is None and after_sequence is None
-
- # Check active stream before the DB query on initial loads so we can
- # choose the correct pagination direction (forward for completed sessions,
- # newest-first for active ones).
- active_session = None
- last_message_id = None
- if is_initial_load:
- active_session, last_message_id = await stream_registry.get_active_session(
- session_id, user_id
- )
-
- # Completed sessions on initial load start from sequence 0 so the user's
- # initial prompt is always visible. Active sessions keep the legacy
- # newest-first behavior to preserve streaming context.
- from_start = is_initial_load and active_session is None
- forward_paginated = from_start or after_sequence is not None
-
page = await get_chat_messages_paginated(
- session_id,
- limit,
- before_sequence=before_sequence,
- after_sequence=after_sequence,
- from_start=from_start,
- user_id=user_id,
+ session_id, limit, before_sequence, user_id=user_id
)
if page is None:
raise NotFoundError(f"Session {session_id} not found.")
- # Close the TOCTOU window: if the session was active at pre-check, re-verify
- # after the DB fetch. The session may have completed between the two awaits,
- # which would have caused messages to be fetched newest-first even though the
- # session is now complete. Re-fetch from seq 0 so the initial prompt is
- # always visible.
- if is_initial_load and active_session is not None:
- post_active, _ = await stream_registry.get_active_session(session_id, user_id)
- if post_active is None:
- active_session = None
- last_message_id = None
- from_start = True
- forward_paginated = True
- page = await get_chat_messages_paginated(
- session_id,
- limit,
- before_sequence=None,
- after_sequence=None,
- from_start=True,
- user_id=user_id,
- )
- if page is None:
- raise NotFoundError(f"Session {session_id} not found.")
-
messages = [
_strip_injected_context(message.model_dump()) for message in page.messages
]
+ # Only check active stream on initial load (not on "load more" requests)
active_stream_info = None
- if active_session and last_message_id is not None:
- 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
)
+ if active_session:
+ active_stream_info = ActiveStreamInfo(
+ turn_id=active_session.turn_id,
+ last_message_id=last_message_id,
+ )
# Skip session metadata on "load more" — frontend only needs messages
- if not is_initial_load:
+ if before_sequence is not None:
return SessionDetailResponse(
id=page.session.session_id,
created_at=page.session.started_at.isoformat(),
@@ -572,8 +496,6 @@ async def get_session(
active_stream=None,
has_more_messages=page.has_more,
oldest_sequence=page.oldest_sequence,
- newest_sequence=page.newest_sequence,
- forward_paginated=forward_paginated,
total_prompt_tokens=0,
total_completion_tokens=0,
)
@@ -590,8 +512,6 @@ async def get_session(
active_stream=active_stream_info,
has_more_messages=page.has_more,
oldest_sequence=page.oldest_sequence,
- newest_sequence=page.newest_sequence,
- forward_paginated=forward_paginated,
total_prompt_tokens=total_prompt,
total_completion_tokens=total_completion,
metadata=page.session.metadata,
diff --git a/autogpt_platform/backend/backend/api/features/chat/routes_test.py b/autogpt_platform/backend/backend/api/features/chat/routes_test.py
index a1ad07deae..011dd05053 100644
--- a/autogpt_platform/backend/backend/api/features/chat/routes_test.py
+++ b/autogpt_platform/backend/backend/api/features/chat/routes_test.py
@@ -759,7 +759,7 @@ def test_disconnect_stream_returns_404_when_session_missing(
mock_disconnect.assert_not_awaited()
-# ─── GET /sessions/{session_id} — forward/backward pagination ──────────────────
+# ─── GET /sessions/{session_id} — backward pagination ─────────────────────────
def _make_paginated_messages(
@@ -784,7 +784,6 @@ def _make_paginated_messages(
messages=[ChatMessage(role="user", content="hello", sequence=0)],
has_more=has_more,
oldest_sequence=0,
- newest_sequence=0,
session=session_info,
)
mock_paginate = mocker.patch(
@@ -795,11 +794,11 @@ def _make_paginated_messages(
return page, mock_paginate
-def test_get_session_completed_returns_forward_paginated(
+def test_get_session_returns_backward_paginated(
mocker: pytest_mock.MockerFixture,
test_user_id: str,
) -> None:
- """Completed sessions (no active stream) return forward_paginated=True."""
+ """All sessions use backward (newest-first) pagination."""
_make_paginated_messages(mocker)
mocker.patch(
"backend.api.features.chat.routes.stream_registry.get_active_session",
@@ -811,92 +810,6 @@ def test_get_session_completed_returns_forward_paginated(
assert response.status_code == 200
data = response.json()
- assert data["forward_paginated"] is True
- assert data["newest_sequence"] == 0
-
-
-def test_get_session_active_returns_backward_paginated(
- mocker: pytest_mock.MockerFixture,
- test_user_id: str,
-) -> None:
- """Active sessions (with running stream) return forward_paginated=False."""
- from backend.copilot.stream_registry import ActiveSession
-
- _make_paginated_messages(mocker)
- active = MagicMock(spec=ActiveSession)
- active.turn_id = "turn-1"
- mocker.patch(
- "backend.api.features.chat.routes.stream_registry.get_active_session",
- new_callable=AsyncMock,
- return_value=(active, "msg-1"),
- )
-
- response = client.get("/sessions/sess-1")
-
- assert response.status_code == 200
- data = response.json()
- assert data["forward_paginated"] is False
- assert data["active_stream"] is not None
- assert data["active_stream"]["turn_id"] == "turn-1"
-
-
-def test_get_session_after_sequence_returns_forward_paginated(
- mocker: pytest_mock.MockerFixture,
- test_user_id: str,
-) -> None:
- """after_sequence param returns forward_paginated=True; no stream check needed."""
- _, mock_paginate = _make_paginated_messages(mocker)
-
- response = client.get("/sessions/sess-1?after_sequence=10")
-
- assert response.status_code == 200
- data = response.json()
- assert data["forward_paginated"] is True
- call_kwargs = mock_paginate.call_args
- assert call_kwargs.kwargs.get("after_sequence") == 10
- assert call_kwargs.kwargs.get("before_sequence") is None
-
-
-def test_get_session_both_cursors_returns_400(
- test_user_id: str,
-) -> None:
- """Sending both before_sequence and after_sequence returns 400."""
- response = client.get("/sessions/sess-1?before_sequence=5&after_sequence=10")
-
- assert response.status_code == 400
-
-
-def test_get_session_toctou_refetch_when_session_completes_mid_request(
- mocker: pytest_mock.MockerFixture,
- test_user_id: str,
-) -> None:
- """Race condition: session was active at pre-check but completes before DB fetch.
-
- The route should detect the race via a post-fetch re-check, then re-fetch
- from seq 0 so the initial prompt is always visible.
- """
- from backend.copilot.stream_registry import ActiveSession
-
- page, mock_paginate = _make_paginated_messages(mocker)
- active = MagicMock(spec=ActiveSession)
- active.turn_id = "turn-1"
-
- # First call: session appears active. Second call: session has completed.
- mock_get_active = mocker.patch(
- "backend.api.features.chat.routes.stream_registry.get_active_session",
- new_callable=AsyncMock,
- side_effect=[(active, "msg-1"), (None, None)],
- )
-
- response = client.get("/sessions/sess-1")
-
- assert response.status_code == 200
- data = response.json()
- # Post-race: session is now completed → forward_paginated=True, no stream
- assert data["forward_paginated"] is True
- assert data["active_stream"] is None
- # The DB was queried twice: once newest-first, once from_start=True
- assert mock_paginate.call_count == 2
- assert mock_get_active.call_count == 2
- second_call = mock_paginate.call_args_list[1]
- assert second_call.kwargs.get("from_start") is True
+ assert data["oldest_sequence"] == 0
+ assert "forward_paginated" not in data
+ assert "newest_sequence" not in data
diff --git a/autogpt_platform/backend/backend/copilot/db.py b/autogpt_platform/backend/backend/copilot/db.py
index bc4964ec35..263334d114 100644
--- a/autogpt_platform/backend/backend/copilot/db.py
+++ b/autogpt_platform/backend/backend/copilot/db.py
@@ -41,7 +41,6 @@ class PaginatedMessages(BaseModel):
messages: list[ChatMessage]
has_more: bool
oldest_sequence: int | None
- newest_sequence: int | None
session: ChatSessionInfo
@@ -66,48 +65,30 @@ async def get_chat_messages_paginated(
session_id: str,
limit: int = 50,
before_sequence: int | None = None,
- after_sequence: int | None = None,
- from_start: bool = False,
user_id: str | None = None,
) -> PaginatedMessages | None:
- """Get paginated messages for a session.
-
- Three modes:
-
- - ``before_sequence`` set: backward pagination (DESC), returns messages
- with sequence < ``before_sequence``. Used for active sessions or manual
- backward navigation.
- - ``from_start=True`` or ``after_sequence`` set: forward pagination (ASC).
- Returns messages from sequence 0 (``from_start``) or after
- ``after_sequence``. Used on initial load of completed sessions and for
- loading subsequent forward pages.
- - Both cursors ``None`` and ``from_start=False``: newest-first (DESC
- without filter). Used for active sessions on initial load.
-
- Verifies session existence (and ownership when ``user_id`` is provided).
- Returns ``None`` when the session is not found or does not belong to the
- user.
+ """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.
+
+ After fetching, a visibility guarantee ensures the page contains at least
+ one user or assistant message. If the entire page is tool messages (which
+ are hidden in the UI), it expands backward until a visible message is found
+ so the chat never appears blank.
"""
# Build session-existence / ownership check
session_where: ChatSessionWhereInput = {"id": session_id}
if user_id is not None:
session_where["userId"] = user_id
- forward = from_start or after_sequence is not None
-
- # Build message include — fetch paginated messages in the same query.
- # Note: when both from_start=True and after_sequence is not None, the
- # after_sequence filter takes precedence (the elif branch below is skipped).
- # This combination is not reachable via the HTTP route (mutual exclusion is
- # enforced there), so we rely on the documented priority here without an
- # additional assertion.
+ # Build message include — fetch paginated messages in the same query
msg_include: FindManyChatMessageArgsFromChatSession = {
- "order_by": {"sequence": "asc" if forward else "desc"},
+ "order_by": {"sequence": "desc"},
"take": limit + 1,
}
- if after_sequence is not None:
- msg_include["where"] = {"sequence": {"gt": after_sequence}}
- elif before_sequence is not None:
+ if before_sequence is not None:
msg_include["where"] = {"sequence": {"lt": before_sequence}}
# Single query: session existence/ownership + paginated messages
@@ -125,100 +106,129 @@ async def get_chat_messages_paginated(
has_more = len(results) > limit
results = results[:limit]
- if not forward:
- # Backward mode: DB returned DESC; reverse to ascending order.
- results.reverse()
+ # 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.
- if results and results[0].role == "tool":
- boundary_where: ChatMessageWhereInput = {
- "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
- else:
- # Forward mode: DB returned ASC.
- # Tool-call tail boundary fix: if the last message in this page is a
- # tool message, the NEXT forward page would start after it and begin
- # mid-tool-group — the owning assistant message is on this page but
- # the following tool results are on the next page.
- # Trim the current page so it ends on the owning assistant message,
- # which keeps tool groups intact across page boundaries.
- if results and results[-1].role == "tool":
- # Walk backward through results to find the last non-tool message.
- trim_idx = len(results) - 1
- while trim_idx >= 0 and results[trim_idx].role == "tool":
- trim_idx -= 1
-
- if trim_idx >= 0:
- # Trim results so the page ends at the owning assistant.
- # Mark has_more=True so the client knows to fetch the rest.
- results = results[: trim_idx + 1]
- has_more = True
- else:
- # Entire page is tool messages with no visible owner — log and
- # keep as-is so the caller is not stuck with an empty page.
- logger.warning(
- "Forward tail boundary: entire page is tool messages "
- "for session=%s, no owning assistant found (%d msgs)",
- session_id,
- len(results),
- )
+ # 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.
+ if results and results[0].role == "tool":
+ results, has_more = await _expand_tool_boundary(
+ session_id, results, has_more, user_id
+ )
+
+ # Visibility guarantee: if the entire page has no user/assistant messages
+ # (all tool messages), the chat would appear blank. Expand backward
+ # until we find at least one visible message.
+ if results and not any(m.role in ("user", "assistant") for m in results):
+ results, has_more = await _expand_for_visibility(
+ session_id, results, has_more, user_id
+ )
messages = [ChatMessage.from_db(m) for m in results]
- # oldest_sequence is only meaningful in backward mode (used as backward
- # pagination cursor). In forward mode the page always starts near seq 0
- # and clients should use newest_sequence as the forward cursor instead.
- # Return None in forward mode so clients don't accidentally treat it as a
- # backward cursor on a forward-paginated session.
- oldest_sequence = messages[0].sequence if (messages and not forward) else None
- # newest_sequence is only meaningful in forward mode; in backward mode it
- # points to the last message of the page (not the session's newest message)
- # which is not a valid forward cursor. Return None in backward mode so
- # clients don't accidentally use it as one.
- newest_sequence = messages[-1].sequence if (messages and forward) else None
+ oldest_sequence = messages[0].sequence if messages else None
return PaginatedMessages(
messages=messages,
has_more=has_more,
oldest_sequence=oldest_sequence,
- newest_sequence=newest_sequence,
session=session_info,
)
+async def _expand_tool_boundary(
+ session_id: str,
+ results: list[Any],
+ has_more: bool,
+ user_id: str | None,
+) -> tuple[list[Any], bool]:
+ """Expand backward from the oldest message to include the owning assistant
+ message when the page starts mid-tool-group."""
+ boundary_where: ChatMessageWhereInput = {
+ "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
+ has_more = boundary_msgs[0].sequence > 0
+ return results, has_more
+
+
+_VISIBILITY_EXPAND_LIMIT = 200
+
+
+async def _expand_for_visibility(
+ session_id: str,
+ results: list[Any],
+ has_more: bool,
+ user_id: str | None,
+) -> tuple[list[Any], bool]:
+ """Expand backward until the page contains at least one user or assistant
+ message, so the chat is never blank."""
+ expand_where: ChatMessageWhereInput = {
+ "sessionId": session_id,
+ "sequence": {"lt": results[0].sequence},
+ }
+ if user_id is not None:
+ expand_where["Session"] = {"is": {"userId": user_id}}
+ extra = await PrismaChatMessage.prisma().find_many(
+ where=expand_where,
+ order={"sequence": "desc"},
+ take=_VISIBILITY_EXPAND_LIMIT,
+ )
+ if not extra:
+ return results, has_more
+
+ # Collect messages until we find a visible one (user/assistant)
+ prepend = []
+ found_visible = False
+ for msg in extra:
+ prepend.append(msg)
+ if msg.role in ("user", "assistant"):
+ found_visible = True
+ break
+
+ if not found_visible:
+ logger.warning(
+ "Visibility expansion did not find any user/assistant message "
+ "for session=%s before sequence=%s (%d msgs scanned)",
+ session_id,
+ results[0].sequence,
+ len(extra),
+ )
+
+ prepend.reverse()
+ if prepend:
+ results = prepend + results
+ has_more = prepend[0].sequence > 0
+ return results, has_more
+
+
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.py
index f9e7ad515f..93368093a1 100644
--- a/autogpt_platform/backend/backend/copilot/db_test.py
+++ b/autogpt_platform/backend/backend/copilot/db_test.py
@@ -175,185 +175,136 @@ async def test_no_where_on_messages_without_before_sequence(
assert "where" not in include["Messages"]
-# ---------- Forward pagination (from_start / after_sequence) ----------
+# ---------- Visibility guarantee ----------
@pytest.mark.asyncio
-async def test_from_start_uses_asc_order_no_where(
+async def test_visibility_expands_when_all_tool_messages(
mock_db: tuple[AsyncMock, AsyncMock],
):
- """from_start=True queries messages in ASC order with no where filter."""
- find_first, _ = mock_db
- find_first.return_value = _make_session(
- messages=[_make_msg(0), _make_msg(1), _make_msg(2)],
- )
-
- await get_chat_messages_paginated(SESSION_ID, limit=50, from_start=True)
-
- call_kwargs = find_first.call_args
- include = call_kwargs.kwargs.get("include") or call_kwargs[1].get("include")
- assert include["Messages"]["order_by"] == {"sequence": "asc"}
- assert "where" not in include["Messages"]
-
-
-async def test_from_start_returns_messages_ascending(
- mock_db: tuple[AsyncMock, AsyncMock],
-):
- """from_start=True returns messages in ascending sequence order."""
- find_first, _ = mock_db
- find_first.return_value = _make_session(
- messages=[_make_msg(0), _make_msg(1), _make_msg(2)],
- )
-
- page = await get_chat_messages_paginated(SESSION_ID, limit=50, from_start=True)
-
- assert page is not None
- assert [m.sequence for m in page.messages] == [0, 1, 2]
- assert (
- page.oldest_sequence is None
- ) # None in forward mode — not a valid backward cursor
- assert page.newest_sequence == 2
- assert page.has_more is False
-
-
-async def test_from_start_has_more_when_results_exceed_limit(
- mock_db: tuple[AsyncMock, AsyncMock],
-):
- """from_start=True sets has_more when DB returns more than limit items."""
- find_first, _ = mock_db
+ """When the entire page is tool messages, expand backward to find
+ at least one visible (user/assistant) message so the chat isn't blank."""
+ find_first, find_many = mock_db
+ # Newest 3 messages are all tool messages (DESC → reversed to ASC)
find_first.return_value = _make_session(
- messages=[_make_msg(0), _make_msg(1), _make_msg(2)],
+ messages=[
+ _make_msg(12, role="tool"),
+ _make_msg(11, role="tool"),
+ _make_msg(10, role="tool"),
+ ],
)
+ # Boundary expansion finds the owning assistant first (boundary fix),
+ # then visibility expansion finds a user message further back
+ find_many.side_effect = [
+ # First call: boundary fix (oldest msg is tool → find owner)
+ [_make_msg(9, role="tool"), _make_msg(8, role="tool")],
+ # Second call: visibility expansion (still all tool → find visible)
+ [_make_msg(7, role="tool"), _make_msg(6, role="assistant")],
+ ]
- page = await get_chat_messages_paginated(SESSION_ID, limit=2, from_start=True)
+ page = await get_chat_messages_paginated(SESSION_ID, limit=3)
assert page is not None
+ # Should include the expanded messages + original tool messages
+ roles = [m.role for m in page.messages]
+ assert "assistant" in roles or "user" in roles
assert page.has_more is True
- assert [m.sequence for m in page.messages] == [0, 1]
- assert page.newest_sequence == 1
-
-
-async def test_after_sequence_uses_gt_filter_asc_order(
- mock_db: tuple[AsyncMock, AsyncMock],
-):
- """after_sequence adds a sequence > N where clause and uses ASC order."""
- find_first, _ = mock_db
- find_first.return_value = _make_session(
- messages=[_make_msg(11), _make_msg(12)],
- )
-
- await get_chat_messages_paginated(SESSION_ID, limit=50, after_sequence=10)
-
- call_kwargs = find_first.call_args
- include = call_kwargs.kwargs.get("include") or call_kwargs[1].get("include")
- assert include["Messages"]["order_by"] == {"sequence": "asc"}
- assert include["Messages"]["where"] == {"sequence": {"gt": 10}}
@pytest.mark.asyncio
-async def test_after_sequence_returns_messages_in_order(
+async def test_no_visibility_expansion_when_visible_messages_present(
mock_db: tuple[AsyncMock, AsyncMock],
):
- """after_sequence returns only messages with sequence > cursor, ascending."""
- find_first, _ = mock_db
+ """No visibility expansion needed when page already has visible messages."""
+ find_first, find_many = mock_db
+ # Page has an assistant message among tool messages
find_first.return_value = _make_session(
- messages=[_make_msg(11), _make_msg(12), _make_msg(13)],
+ messages=[
+ _make_msg(5, role="tool"),
+ _make_msg(4, role="assistant"),
+ _make_msg(3, role="user"),
+ ],
)
- page = await get_chat_messages_paginated(SESSION_ID, limit=50, after_sequence=10)
+ page = await get_chat_messages_paginated(SESSION_ID, limit=3)
assert page is not None
- assert [m.sequence for m in page.messages] == [11, 12, 13]
- assert (
- page.oldest_sequence is None
- ) # None in forward mode — not a valid backward cursor
- assert page.newest_sequence == 13
- assert page.has_more is False
+ # Boundary expansion might fire (oldest is tool), but NOT visibility
+ assert [m.sequence for m in page.messages][0] <= 3
@pytest.mark.asyncio
-async def test_newest_sequence_none_for_backward_mode(
+async def test_visibility_no_expansion_when_no_earlier_messages(
mock_db: tuple[AsyncMock, AsyncMock],
):
- """newest_sequence is None in backward mode — it is not a valid forward cursor."""
- find_first, _ = mock_db
+ """When the page is all tool messages but there are no earlier messages
+ in the DB, visibility expansion returns early without changes."""
+ find_first, find_many = mock_db
find_first.return_value = _make_session(
- messages=[_make_msg(5), _make_msg(4), _make_msg(3)],
+ messages=[_make_msg(1, role="tool"), _make_msg(0, role="tool")],
)
+ # Boundary expansion: no earlier messages
+ # Visibility expansion: no earlier messages
+ find_many.side_effect = [[], []]
- page = await get_chat_messages_paginated(SESSION_ID, limit=50)
+ page = await get_chat_messages_paginated(SESSION_ID, limit=2)
assert page is not None
- assert page.newest_sequence is None
- assert page.oldest_sequence == 3
+ assert all(m.role == "tool" for m in page.messages)
@pytest.mark.asyncio
-async def test_forward_mode_no_boundary_expansion(
+async def test_visibility_expansion_reaches_seq_zero(
mock_db: tuple[AsyncMock, AsyncMock],
):
- """Forward pagination never triggers backward boundary expansion."""
+ """When visibility expansion finds a visible message at sequence 0,
+ has_more should be False."""
find_first, find_many = mock_db
find_first.return_value = _make_session(
- messages=[_make_msg(0, role="tool"), _make_msg(1, role="tool")],
+ messages=[_make_msg(5, role="tool"), _make_msg(4, role="tool")],
)
-
- await get_chat_messages_paginated(SESSION_ID, limit=50, from_start=True)
-
- assert find_many.call_count == 0
-
-
-async def test_forward_tail_boundary_trims_trailing_tool_messages(
- mock_db: tuple[AsyncMock, AsyncMock],
-):
- """Forward pages that end with tool messages are trimmed to the owning
- assistant so the next after_sequence page doesn't start mid-tool-group."""
- find_first, _ = mock_db
- # DB returns 4 messages ASC: assistant at 0, tool at 1, tool at 2, tool at 3
- find_first.return_value = _make_session(
- messages=[
- _make_msg(0, role="assistant"),
- _make_msg(1, role="tool"),
+ find_many.side_effect = [
+ # Boundary expansion
+ [_make_msg(3, role="tool")],
+ # Visibility expansion — finds user at seq 0
+ [
_make_msg(2, role="tool"),
- _make_msg(3, role="tool"),
+ _make_msg(1, role="tool"),
+ _make_msg(0, role="user"),
],
- )
+ ]
- page = await get_chat_messages_paginated(SESSION_ID, limit=10, from_start=True)
+ page = await get_chat_messages_paginated(SESSION_ID, limit=2)
assert page is not None
- # Page should be trimmed to end at the assistant message
- assert [m.sequence for m in page.messages] == [0]
- assert page.newest_sequence == 0
- # has_more must be True so the client fetches the tool messages on next page
- assert page.has_more is True
+ assert page.messages[0].role == "user"
+ assert page.messages[0].sequence == 0
+ assert page.has_more is False
@pytest.mark.asyncio
-async def test_forward_tail_boundary_no_trim_when_last_not_tool(
+async def test_visibility_expansion_with_user_id(
mock_db: tuple[AsyncMock, AsyncMock],
):
- """Forward pages that end with a non-tool message are not trimmed."""
- find_first, _ = mock_db
+ """Visibility expansion passes user_id filter to the boundary query."""
+ find_first, find_many = mock_db
find_first.return_value = _make_session(
- messages=[
- _make_msg(0, role="user"),
- _make_msg(1, role="assistant"),
- _make_msg(2, role="tool"),
- _make_msg(3, role="assistant"),
- ],
+ messages=[_make_msg(10, role="tool")],
)
+ find_many.side_effect = [
+ # Boundary expansion
+ [_make_msg(9, role="tool")],
+ # Visibility expansion
+ [_make_msg(8, role="assistant")],
+ ]
- page = await get_chat_messages_paginated(SESSION_ID, limit=10, from_start=True)
+ await get_chat_messages_paginated(SESSION_ID, limit=1, user_id="user-abc")
- assert page is not None
- assert [m.sequence for m in page.messages] == [0, 1, 2, 3]
- assert page.newest_sequence == 3
- assert page.has_more is False
+ # Both find_many calls should include the user_id session filter
+ for call in find_many.call_args_list:
+ where = call.kwargs.get("where") or call[1].get("where")
+ assert "Session" in where
+ assert where["Session"] == {"is": {"userId": "user-abc"}}
@pytest.mark.asyncio
@@ -510,7 +461,8 @@ async def test_boundary_expansion_warns_when_no_owner_found(
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()
+ # Two warnings: boundary expansion + visibility expansion (all tool msgs)
+ assert mock_logger.warning.call_count == 2
assert page is not None
assert page.messages[0].role == "tool"
diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/CopilotPage.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/CopilotPage.tsx
index 62255037eb..88f70c75d8 100644
--- a/autogpt_platform/frontend/src/app/(platform)/copilot/CopilotPage.tsx
+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/CopilotPage.tsx
@@ -93,7 +93,6 @@ export function CopilotPage() {
hasMoreMessages,
isLoadingMore,
loadMore,
- forwardPaginated,
// Mobile drawer
isMobile,
isDrawerOpen,
@@ -218,7 +217,6 @@ export function CopilotPage() {
hasMoreMessages={hasMoreMessages}
isLoadingMore={isLoadingMore}
onLoadMore={loadMore}
- forwardPaginated={forwardPaginated}
droppedFiles={droppedFiles}
onDroppedFilesConsumed={handleDroppedFilesConsumed}
historicalDurations={historicalDurations}
diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/__tests__/useChatSession.test.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/__tests__/useChatSession.test.ts
index a6d8c5e896..a35d5c58a9 100644
--- a/autogpt_platform/frontend/src/app/(platform)/copilot/__tests__/useChatSession.test.ts
+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/__tests__/useChatSession.test.ts
@@ -48,75 +48,40 @@ function makeQueryResult(data: object | null) {
};
}
-describe("useChatSession — newestSequence and forwardPaginated", () => {
+describe("useChatSession — pagination metadata", () => {
beforeEach(() => {
vi.clearAllMocks();
});
- it("returns null / false when no session data", () => {
+ it("returns null for oldestSequence when no session data", () => {
mockUseGetV2GetSession.mockReturnValue(makeQueryResult(null));
const { result } = renderHook(() => useChatSession());
- expect(result.current.newestSequence).toBeNull();
- expect(result.current.forwardPaginated).toBe(false);
+ expect(result.current.oldestSequence).toBeNull();
});
- it("returns newestSequence from session data", () => {
+ it("returns oldestSequence from session data", () => {
mockUseGetV2GetSession.mockReturnValue(
makeQueryResult({
messages: [],
has_more_messages: true,
- oldest_sequence: 0,
- newest_sequence: 99,
- forward_paginated: false,
- active_stream: null,
- }),
- );
- const { result } = renderHook(() => useChatSession());
- expect(result.current.newestSequence).toBe(99);
- });
-
- it("returns null for newestSequence when field is missing", () => {
- mockUseGetV2GetSession.mockReturnValue(
- makeQueryResult({
- messages: [],
- has_more_messages: false,
- oldest_sequence: 0,
- newest_sequence: null,
- forward_paginated: false,
+ oldest_sequence: 50,
active_stream: null,
}),
);
const { result } = renderHook(() => useChatSession());
- expect(result.current.newestSequence).toBeNull();
+ expect(result.current.oldestSequence).toBe(50);
});
- it("returns forwardPaginated=true when session is forward-paginated", () => {
+ it("returns hasMoreMessages from session data", () => {
mockUseGetV2GetSession.mockReturnValue(
makeQueryResult({
messages: [],
has_more_messages: true,
oldest_sequence: 0,
- newest_sequence: 49,
- forward_paginated: true,
- active_stream: null,
- }),
- );
- const { result } = renderHook(() => useChatSession());
- expect(result.current.forwardPaginated).toBe(true);
- });
-
- it("returns forwardPaginated=false when session is backward-paginated", () => {
- mockUseGetV2GetSession.mockReturnValue(
- makeQueryResult({
- messages: [],
- has_more_messages: true,
- oldest_sequence: 50,
- newest_sequence: 99,
- forward_paginated: false,
active_stream: null,
}),
);
const { result } = renderHook(() => useChatSession());
- expect(result.current.forwardPaginated).toBe(false);
+ expect(result.current.hasMoreMessages).toBe(true);
});
});
diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/__tests__/useCopilotPage.test.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/__tests__/useCopilotPage.test.ts
index cd23a51195..d9519dda0c 100644
--- a/autogpt_platform/frontend/src/app/(platform)/copilot/__tests__/useCopilotPage.test.ts
+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/__tests__/useCopilotPage.test.ts
@@ -1,4 +1,4 @@
-import { act, renderHook, waitFor } from "@testing-library/react";
+import { renderHook } from "@testing-library/react";
import { beforeEach, describe, expect, it, vi } from "vitest";
import { useCopilotPage } from "../useCopilotPage";
@@ -70,8 +70,6 @@ function makeBaseChatSession(overrides: Record<string, unknown> = {}) {
hasActiveStream: false,
hasMoreMessages: false,
oldestSequence: null,
- newestSequence: null,
- forwardPaginated: false,
isLoadingSession: false,
isSessionError: false,
createSession: vi.fn(),
@@ -104,22 +102,19 @@ function makeBaseLoadMore(overrides: Record<string, unknown> = {}) {
hasMore: false,
isLoadingMore: false,
loadMore: vi.fn(),
- resetPaged: vi.fn(),
...overrides,
};
}
-describe("useCopilotPage — forwardPaginated message ordering", () => {
+describe("useCopilotPage — backward pagination message ordering", () => {
beforeEach(() => {
vi.clearAllMocks();
});
- it("prepends pagedMessages before currentMessages when forwardPaginated=false", () => {
+ it("prepends pagedMessages before currentMessages", () => {
const pagedMsg = { id: "paged", role: "user" };
const currentMsg = { id: "current", role: "assistant" };
- mockUseChatSession.mockReturnValue(
- makeBaseChatSession({ forwardPaginated: false }),
- );
+ mockUseChatSession.mockReturnValue(makeBaseChatSession());
mockUseCopilotStream.mockReturnValue(
makeBaseCopilotStream({ messages: [currentMsg] }),
);
@@ -133,70 +128,4 @@ describe("useCopilotPage — forwardPaginated message ordering", () => {
expect(result.current.messages[0]).toEqual(pagedMsg);
expect(result.current.messages[1]).toEqual(currentMsg);
});
-
- it("appends pagedMessages after currentMessages when forwardPaginated=true", () => {
- const pagedMsg = { id: "paged", role: "assistant" };
- const currentMsg = { id: "current", role: "user" };
- mockUseChatSession.mockReturnValue(
- makeBaseChatSession({ forwardPaginated: true }),
- );
- mockUseCopilotStream.mockReturnValue(
- makeBaseCopilotStream({ messages: [currentMsg] }),
- );
- mockUseLoadMoreMessages.mockReturnValue(
- makeBaseLoadMore({ pagedMessages: [pagedMsg] }),
- );
-
- const { result } = renderHook(() => useCopilotPage());
-
- // Forward: currentMessages (beginning of session) come first
- expect(result.current.messages[0]).toEqual(currentMsg);
- expect(result.current.messages[1]).toEqual(pagedMsg);
- });
-
- it("calls resetPaged when forwardPaginated transitions false→true with paged messages", async () => {
- const mockResetPaged = vi.fn();
- const pagedMsg = { id: "paged", role: "user" };
-
- mockUseChatSession.mockReturnValue(
- makeBaseChatSession({ forwardPaginated: false }),
- );
- mockUseCopilotStream.mockReturnValue(makeBaseCopilotStream());
- mockUseLoadMoreMessages.mockReturnValue(
- makeBaseLoadMore({
- pagedMessages: [pagedMsg],
- resetPaged: mockResetPaged,
- }),
- );
-
- const { rerender } = renderHook(() => useCopilotPage());
-
- // Simulate session completing — forwardPaginated flips to true
- mockUseChatSession.mockReturnValue(
- makeBaseChatSession({ forwardPaginated: true }),
- );
-
- act(() => {
- rerender();
- });
-
- await waitFor(() => {
- expect(mockResetPaged).toHaveBeenCalled();
- });
- });
-
- it("does not call resetPaged when forwardPaginated is already true on mount", () => {
- const mockResetPaged = vi.fn();
- mockUseChatSession.mockReturnValue(
- makeBaseChatSession({ forwardPaginated: true }),
- );
- mockUseCopilotStream.mockReturnValue(makeBaseCopilotStream());
- mockUseLoadMoreMessages.mockReturnValue(
- makeBaseLoadMore({ pagedMessages: [], resetPaged: mockResetPaged }),
- );
-
- renderHook(() => useCopilotPage());
-
- expect(mockResetPaged).not.toHaveBeenCalled();
- });
});
diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/__tests__/useLoadMoreMessages.test.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/__tests__/useLoadMoreMessages.test.ts
index 8f781e5f46..35c6939f8a 100644
--- a/autogpt_platform/frontend/src/app/(platform)/copilot/__tests__/useLoadMoreMessages.test.ts
+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/__tests__/useLoadMoreMessages.test.ts
@@ -15,10 +15,8 @@ vi.mock("../helpers/convertChatSessionToUiMessages", () => ({
const BASE_ARGS = {
sessionId: "sess-1",
- initialOldestSequence: 0,
- initialNewestSequence: 49,
+ initialOldestSequence: 50,
initialHasMore: true,
- forwardPaginated: true,
initialPageRawMessages: [],
};
@@ -26,7 +24,6 @@ function makeSuccessResponse(overrides: {
messages?: unknown[];
has_more_messages?: boolean;
oldest_sequence?: number;
- newest_sequence?: number;
}) {
return {
status: 200,
@@ -34,7 +31,6 @@ function makeSuccessResponse(overrides: {
messages: overrides.messages ?? [],
has_more_messages: overrides.has_more_messages ?? false,
oldest_sequence: overrides.oldest_sequence ?? 0,
- newest_sequence: overrides.newest_sequence ?? 49,
},
};
}
@@ -51,30 +47,6 @@ describe("useLoadMoreMessages", () => {
expect(result.current.isLoadingMore).toBe(false);
});
- it("resetPaged clears paged state and sets hasMore=false during transition", () => {
- const { result } = renderHook(() => useLoadMoreMessages(BASE_ARGS));
-
- act(() => {
- result.current.resetPaged();
- });
-
- expect(result.current.pagedMessages).toHaveLength(0);
- // hasMore must be false during transition to prevent forward loadMore
- // from firing on the now-active session before forwardPaginated updates.
- expect(result.current.hasMore).toBe(false);
- expect(result.current.isLoadingMore).toBe(false);
- });
-
- it("resetPaged exposes a fresh loadMore via incremented epoch", () => {
- const { result } = renderHook(() => useLoadMoreMessages(BASE_ARGS));
- // Just verify resetPaged is callable and doesn't throw.
- expect(() => {
- act(() => {
- result.current.resetPaged();
- });
- }).not.toThrow();
- });
-
it("resets all state on sessionId change", () => {
const { result, rerender } = renderHook(
(props) => useLoadMoreMessages(props),
@@ -85,7 +57,6 @@ describe("useLoadMoreMessages", () => {
...BASE_ARGS,
sessionId: "sess-2",
initialOldestSequence: 10,
- initialNewestSequence: 59,
initialHasMore: false,
});
@@ -94,20 +65,17 @@ describe("useLoadMoreMessages", () => {
expect(result.current.isLoadingMore).toBe(false);
});
- describe("loadMore — forward pagination", () => {
- it("calls getV2GetSession with after_sequence and updates newestSequence", async () => {
- const rawMsg = { role: "user", content: "hi", sequence: 50 };
+ describe("loadMore — backward pagination", () => {
+ it("calls getV2GetSession with before_sequence", async () => {
mockGetV2GetSession.mockResolvedValueOnce(
makeSuccessResponse({
- messages: [rawMsg],
- has_more_messages: true,
- newest_sequence: 99,
+ messages: [{ role: "user", content: "old", sequence: 0 }],
+ has_more_messages: false,
+ oldest_sequence: 0,
}),
);
- const { result } = renderHook(() =>
- useLoadMoreMessages({ ...BASE_ARGS, forwardPaginated: true }),
- );
+ const { result } = renderHook(() => useLoadMoreMessages(BASE_ARGS));
await act(async () => {
await result.current.loadMore();
@@ -115,35 +83,14 @@ describe("useLoadMoreMessages", () => {
expect(mockGetV2GetSession).toHaveBeenCalledWith(
"sess-1",
- expect.objectContaining({ after_sequence: 49 }),
- );
- expect(result.current.hasMore).toBe(true);
- expect(result.current.isLoadingMore).toBe(false);
- });
-
- it("sets hasMore=false when response has no more messages", async () => {
- mockGetV2GetSession.mockResolvedValueOnce(
- makeSuccessResponse({ has_more_messages: false }),
- );
-
- const { result } = renderHook(() =>
- useLoadMoreMessages({ ...BASE_ARGS, forwardPaginated: true }),
+ expect.objectContaining({ before_sequence: 50 }),
);
-
- await act(async () => {
- await result.current.loadMore();
- });
-
expect(result.current.hasMore).toBe(false);
});
it("is a no-op when hasMore is false", async () => {
const { result } = renderHook(() =>
- useLoadMoreMessages({
- ...BASE_ARGS,
- initialHasMore: false,
- forwardPaginated: true,
- }),
+ useLoadMoreMessages({ ...BASE_ARGS, initialHasMore: false }),
);
await act(async () => {
@@ -152,35 +99,17 @@ describe("useLoadMoreMessages", () => {
expect(mockGetV2GetSession).not.toHaveBeenCalled();
});
- });
-
- describe("loadMore — backward pagination", () => {
- it("calls getV2GetSession with before_sequence", async () => {
- mockGetV2GetSession.mockResolvedValueOnce(
- makeSuccessResponse({
- messages: [{ role: "user", content: "old", sequence: 0 }],
- has_more_messages: false,
- oldest_sequence: 0,
- }),
- );
+ it("is a no-op when oldestSequence is null", async () => {
const { result } = renderHook(() =>
- useLoadMoreMessages({
- ...BASE_ARGS,
- forwardPaginated: false,
- initialOldestSequence: 50,
- }),
+ useLoadMoreMessages({ ...BASE_ARGS, initialOldestSequence: null }),
);
await act(async () => {
await result.current.loadMore();
});
- expect(mockGetV2GetSession).toHaveBeenCalledWith(
- "sess-1",
- expect.objectContaining({ before_sequence: 50 }),
- );
- expect(result.current.hasMore).toBe(false);
+ expect(mockGetV2GetSession).not.toHaveBeenCalled();
});
});
@@ -194,7 +123,6 @@ describe("useLoadMoreMessages", () => {
await result.current.loadMore();
});
- // First error — hasMore still true
expect(result.current.hasMore).toBe(true);
expect(result.current.isLoadingMore).toBe(false);
});
@@ -208,7 +136,6 @@ describe("useLoadMoreMessages", () => {
await act(async () => {
await result.current.loadMore();
});
- // Reset the in-flight guard between calls
await waitFor(() => expect(result.current.isLoadingMore).toBe(false));
}
@@ -224,138 +151,13 @@ describe("useLoadMoreMessages", () => {
await result.current.loadMore();
});
- // One error, not yet at threshold — hasMore still true
expect(result.current.hasMore).toBe(true);
expect(result.current.isLoadingMore).toBe(false);
});
-
- it("sets hasMore=false after MAX_CONSECUTIVE_ERRORS (3) non-200 responses", async () => {
- mockGetV2GetSession.mockResolvedValue({ status: 503, data: {} });
-
- const { result } = renderHook(() => useLoadMoreMessages(BASE_ARGS));
-
- for (let i = 0; i < 3; i++) {
- await act(async () => {
- await result.current.loadMore();
- });
- await waitFor(() => expect(result.current.isLoadingMore).toBe(false));
- }
-
- expect(result.current.hasMore).toBe(false);
- });
-
- it("discards in-flight error when epoch changes mid-flight (resetPaged called)", async () => {
- let rejectRequest!: (e: Error) => void;
- mockGetV2GetSession.mockReturnValueOnce(
- new Promise((_, rej) => {
- rejectRequest = rej;
- }),
- );
-
- const { result } = renderHook(() => useLoadMoreMessages(BASE_ARGS));
-
- act(() => {
- result.current.loadMore();
- });
-
- // Reset epoch mid-flight
- act(() => {
- result.current.resetPaged();
- });
-
- // Reject the in-flight request — stale error should be discarded
- await act(async () => {
- rejectRequest(new Error("network error"));
- });
-
- // State unchanged: no hasMore=false, no errorCount, isLoadingMore cleared
- expect(result.current.hasMore).toBe(false); // false from resetPaged
- expect(result.current.isLoadingMore).toBe(false);
- });
- });
-
- describe("loadMore — forward pagination cursor advancement", () => {
- it("advances newestSequence after a successful forward load", async () => {
- mockGetV2GetSession.mockResolvedValueOnce(
- makeSuccessResponse({
- messages: [{ role: "user", content: "hi", sequence: 50 }],
- has_more_messages: true,
- newest_sequence: 99,
- }),
- );
-
- const { result } = renderHook(() =>
- useLoadMoreMessages({ ...BASE_ARGS, forwardPaginated: true }),
- );
-
- await act(async () => {
- await result.current.loadMore();
- });
-
- // A second loadMore should use after_sequence: 99 (advanced cursor)
- mockGetV2GetSession.mockResolvedValueOnce(
- makeSuccessResponse({ has_more_messages: false, newest_sequence: 149 }),
- );
-
- await act(async () => {
- await result.current.loadMore();
- });
-
- expect(mockGetV2GetSession).toHaveBeenLastCalledWith(
- "sess-1",
- expect.objectContaining({ after_sequence: 99 }),
- );
- });
-
- it("does not regress newestSequence when parent refetches after pages loaded", async () => {
- mockGetV2GetSession.mockResolvedValueOnce(
- makeSuccessResponse({
- messages: [{ role: "user", content: "msg", sequence: 50 }],
- has_more_messages: true,
- newest_sequence: 99,
- }),
- );
-
- const { result, rerender } = renderHook(
- (props) => useLoadMoreMessages(props),
- { initialProps: { ...BASE_ARGS, forwardPaginated: true } },
- );
-
- // Load one page — newestSequence advances to 99
- await act(async () => {
- await result.current.loadMore();
- });
-
- // Parent refetches with a lower newest_sequence (49) — should NOT regress cursor
- rerender({
- ...BASE_ARGS,
- forwardPaginated: true,
- initialNewestSequence: 49,
- });
-
- // Next loadMore should still use the advanced cursor (99)
- mockGetV2GetSession.mockResolvedValueOnce(
- makeSuccessResponse({ has_more_messages: false, newest_sequence: 149 }),
- );
-
- await act(async () => {
- await result.current.loadMore();
- });
-
- expect(mockGetV2GetSession).toHaveBeenLastCalledWith(
- "sess-1",
- expect.objectContaining({ after_sequence: 99 }),
- );
- });
});
describe("loadMore — MAX_OLDER_MESSAGES truncation", () => {
it("truncates accumulated messages at MAX_OLDER_MESSAGES (2000)", async () => {
- // Single load of 2001 messages exceeds the limit in one shot.
- // This avoids relying on cross-render closure staleness: estimatedTotal =
- // pagedRawMessages.length (0, fresh) + 2001 = 2001 >= 2000 → hasMore=false.
- const args = { ...BASE_ARGS, forwardPaginated: false };
-
mockGetV2GetSession.mockResolvedValueOnce(
makeSuccessResponse({
messages: Array.from({ length: 2001 }, (_, i) => ({
@@ -368,7 +170,7 @@ describe("useLoadMoreMessages", () => {
}),
);
- const { result } = renderHook(() => useLoadMoreMessages(args));
+ const { result } = renderHook(() => useLoadMoreMessages(BASE_ARGS));
await act(async () => {
await result.current.loadMore();
@@ -376,103 +178,10 @@ describe("useLoadMoreMessages", () => {
expect(result.current.hasMore).toBe(false);
});
-
- it("forward truncation keeps first MAX_OLDER_MESSAGES items (not last)", async () => {
- // 1990 messages already paged; load 20 more forward — total 2010 > 2000.
- // Forward truncation must keep slice(0, 2000), not slice(-2000),
- // to preserve the beginning of the conversation.
- const forwardNearLimitArgs = {
- ...BASE_ARGS,
- forwardPaginated: true,
- initialNewestSequence: 49,
- initialOldestSequence: 0,
- initialHasMore: true,
- };
-
- const { result } = renderHook((props) => useLoadMoreMessages(props), {
- initialProps: forwardNearLimitArgs,
- });
-
- // First load: 1990 messages — advances newestSequence to 2039
- mockGetV2GetSession.mockResolvedValueOnce(
- makeSuccessResponse({
- messages: Array.from({ length: 1990 }, (_, i) => ({
- role: "assistant",
- content: `msg ${i + 50}`,
- sequence: i + 50,
- })),
- has_more_messages: true,
- newest_sequence: 2039,
- }),
- );
-
- await act(async () => {
- await result.current.loadMore();
- });
-
- // Second load: 20 more messages pushes total to 2010 > 2000.
- // Truncation keeps seq 50..2049 (2000 items); discards seq 2050..2059 (10 items).
- // Even though the server says has_more_messages=false, hasMore stays true
- // because there are discarded items that need to be re-fetched.
- // The cursor (newestSequence) advances to 2049 — the last kept item's sequence.
- mockGetV2GetSession.mockResolvedValueOnce(
- makeSuccessResponse({
- messages: Array.from({ length: 20 }, (_, i) => ({
- role: "assistant",
- content: `msg ${i + 2040}`,
- sequence: i + 2040,
- })),
- has_more_messages: false,
- newest_sequence: 2059,
- }),
- );
-
- await act(async () => {
- await result.current.loadMore();
- });
-
- // Truncation occurred (2010 > 2000): hasMore=true so discarded items can be fetched.
- // Cursor advances to last kept item (seq 2049), not the server's newest (2059).
- await waitFor(() => expect(result.current.hasMore).toBe(true));
- });
- });
-
- describe("loadMore — null cursor guard", () => {
- it("is a no-op when newestSequence is null (forwardPaginated=true)", async () => {
- const { result } = renderHook(() =>
- useLoadMoreMessages({
- ...BASE_ARGS,
- forwardPaginated: true,
- initialNewestSequence: null,
- }),
- );
-
- await act(async () => {
- await result.current.loadMore();
- });
-
- expect(mockGetV2GetSession).not.toHaveBeenCalled();
- });
-
- it("is a no-op when oldestSequence is null (forwardPaginated=false)", async () => {
- const { result } = renderHook(() =>
- useLoadMoreMessages({
- ...BASE_ARGS,
- forwardPaginated: false,
- initialOldestSequence: null,
- }),
- );
-
- await act(async () => {
- await result.current.loadMore();
- });
-
- expect(mockGetV2GetSession).not.toHaveBeenCalled();
- });
});
describe("pagedMessages — initialPageRawMessages extraToolOutputs", () => {
- it("calls extractToolOutputsFromRaw for backward pagination with non-empty initialPageRawMessages", async () => {
+ it("calls extractToolOutputsFromRaw with non-empty initialPageRawMessages", async () => {
const { extractToolOutputsFromRaw } = await import(
"../helpers/convertChatSessionToUiMessages"
);
@@ -489,8 +198,6 @@ describe("useLoadMoreMessages", () => {
const { result } = renderHook(() =>
useLoadMoreMessages({
...BASE_ARGS,
- forwardPaginated: false,
- initialOldestSequence: 50,
initialPageRawMessages: [{ role: "assistant", content: "response" }],
}),
);
@@ -501,68 +208,5 @@ describe("useLoadMoreMessages", () => {
expect(extractToolOutputsFromRaw).toHaveBeenCalled();
});
-
- it("does NOT call extractToolOutputsFromRaw for forward pagination", async () => {
- const { extractToolOutputsFromRaw } = await import(
- "../helpers/convertChatSessionToUiMessages"
- );
-
- const rawMsg = { role: "assistant", content: "hi", sequence: 50 };
- mockGetV2GetSession.mockResolvedValueOnce(
- makeSuccessResponse({
- messages: [rawMsg],
- has_more_messages: false,
- newest_sequence: 99,
- }),
- );
-
- const { result } = renderHook(() =>
- useLoadMoreMessages({
- ...BASE_ARGS,
- forwardPaginated: true,
- initialPageRawMessages: [{ role: "user", content: "hello" }],
- }),
- );
-
- await act(async () => {
- await result.current.loadMore();
- });
-
- expect(extractToolOutputsFromRaw).not.toHaveBeenCalled();
- });
- });
-
- describe("loadMore — epoch / stale-response guard", () => {
- it("discards response when epoch changes during flight (resetPaged called)", async () => {
- let resolveRequest!: (v: unknown) => void;
- mockGetV2GetSession.mockReturnValueOnce(
- new Promise((res) => {
- resolveRequest = res;
- }),
- );
-
- const { result } = renderHook(() => useLoadMoreMessages(BASE_ARGS));
-
- // Start the request without awaiting
- act(() => {
- result.current.loadMore();
- });
-
- // Reset epoch mid-flight
- act(() => {
- result.current.resetPaged();
- });
-
- // Now resolve the in-flight request
- await act(async () => {
- resolveRequest(
- makeSuccessResponse({ messages: [{ role: "user", content: "hi" }] }),
- );
- });
-
- // Response discarded — pagedMessages stays empty, isLoadingMore stays false
- expect(result.current.pagedMessages).toHaveLength(0);
- expect(result.current.isLoadingMore).toBe(false);
- });
});
});
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.tsx
index 6731057658..7f3c1d0328 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
@@ -30,7 +30,6 @@ export interface ChatContainerProps {
hasMoreMessages?: boolean;
isLoadingMore?: boolean;
onLoadMore?: () => void;
- forwardPaginated?: boolean;
/** Files dropped onto the chat window. */
droppedFiles?: File[];
/** Called after droppedFiles have been consumed by ChatInput. */
@@ -55,7 +54,6 @@ export const ChatContainer = ({
hasMoreMessages,
isLoadingMore,
onLoadMore,
- forwardPaginated,
droppedFiles,
onDroppedFilesConsumed,
historicalDurations,
@@ -110,7 +108,6 @@ export const ChatContainer = ({
hasMoreMessages={hasMoreMessages}
isLoadingMore={isLoadingMore}
onLoadMore={onLoadMore}
- forwardPaginated={forwardPaginated}
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.tsx
index d7f3123f9c..d12f97106b 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
@@ -43,10 +43,6 @@ interface Props {
hasMoreMessages?: boolean;
isLoadingMore?: boolean;
onLoadMore?: () => void;
- /** When true the load-more sentinel is placed at the bottom (forward
- * pagination for completed sessions). When false it is at the top
- * (backward pagination for active sessions). */
- forwardPaginated?: boolean;
onRetry?: () => void;
historicalDurations?: Map<string, number>;
}
@@ -140,25 +136,11 @@ export function LoadMoreSentinel({
isLoading,
messageCount,
onLoadMore,
- rootMargin = "200px 0px 0px 0px",
- adjustScroll = true,
- forwardPaginated = false,
}: {
hasMore: boolean;
isLoading: boolean;
messageCount: number;
onLoadMore: () => void;
- /** IntersectionObserver rootMargin. Top sentinel uses "200px 0px 0px 0px"
- * (pre-trigger when approaching from above); bottom sentinel should use
- * "0px 0px 200px 0px" (pre-trigger when approaching from below). */
- rootMargin?: string;
- /** Whether to adjust scrollTop after load to preserve visual position.
- * True for backward pagination (prepend above); false for forward
- * pagination (append below) where no adjustment is needed. */
- adjustScroll?: boolean;
- /** When true the button reads "Load newer messages" (forward pagination).
- * When false (default) it reads "Load older messages". */
- forwardPaginated?: boolean;
}) {
const sentinelRef = useRef<HTMLDivElement>(null);
const onLoadMoreRef = useRef(onLoadMore);
@@ -203,11 +185,11 @@ export function LoadMoreSentinel({
if (autoFillRoundsRef.current >= MAX_AUTO_FILL_ROUNDS) return;
captureAndLoad(true);
},
- { rootMargin },
+ { rootMargin: "200px 0px 0px 0px" },
);
observer.observe(sentinelRef.current);
return () => observer.disconnect();
- }, [hasMore, isLoading, rootMargin, scrollRef]);
+ }, [hasMore, isLoading, scrollRef]);
// After React commits new DOM nodes (prepended messages), adjust
// scrollTop so the user stays at the same visual position.
@@ -220,9 +202,7 @@ export function LoadMoreSentinel({
scrollSnapshotRef.current;
if (!el || prevHeight === 0) return;
const delta = el.scrollHeight - prevHeight;
- // Only restore scroll position for backward pagination (content prepended
- // above). Forward pagination appends below — no adjustment needed.
- if (adjustScroll && delta > 0) {
+ if (delta > 0) {
el.scrollTop = prevTop + delta;
}
// Reset the auto-fill backoff whenever the container becomes
@@ -236,7 +216,7 @@ export function LoadMoreSentinel({
}
scrollSnapshotRef.current = { scrollHeight: 0, scrollTop: 0 };
autoTriggeredRef.current = false;
- }, [adjustScroll, messageCount, scrollRef]);
+ }, [messageCount, scrollRef]);
return (
<div
@@ -255,7 +235,7 @@ export function LoadMoreSentinel({
size="small"
onClick={() => captureAndLoad(false)}
>
- {forwardPaginated ? "Load newer messages" : "Load older messages"}
+ Load older messages
</Button>
)
)}
@@ -272,7 +252,6 @@ export function ChatMessagesContainer({
hasMoreMessages,
isLoadingMore,
onLoadMore,
- forwardPaginated,
onRetry,
historicalDurations,
}: Props) {
@@ -351,7 +330,7 @@ export function ChatMessagesContainer({
}
>
<ConversationContent className="flex min-h-full flex-1 flex-col gap-6 px-3 py-6">
- {hasMoreMessages && onLoadMore && !forwardPaginated && (
+ {hasMoreMessages && onLoadMore && (
<LoadMoreSentinel
hasMore={hasMoreMessages}
isLoading={!!isLoadingMore}
@@ -510,17 +489,6 @@ export function ChatMessagesContainer({
</pre>
</details>
)}
- {hasMoreMessages && onLoadMore && forwardPaginated && (
- <LoadMoreSentinel
- hasMore={hasMoreMessages}
- isLoading={!!isLoadingMore}
- messageCount={messages.length}
- onLoadMore={onLoadMore}
- rootMargin="0px 0px 200px 0px"
- adjustScroll={false}
- forwardPaginated
- />
- )}
</ConversationContent>
<ConversationScrollButton />
</Conversation>
diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatMessagesContainer/__tests__/ChatMessagesContainer.test.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatMessagesContainer/__tests__/ChatMessagesContainer.test.tsx
index ca7ee0d181..333896ec07 100644
--- a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatMessagesContainer/__tests__/ChatMessagesContainer.test.tsx
+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatMessagesContainer/__tests__/ChatMessagesContainer.test.tsx
@@ -124,48 +124,22 @@ describe("ChatMessagesContainer", () => {
vi.unstubAllGlobals();
});
- it("renders top sentinel when forwardPaginated is false (backward pagination)", () => {
- render(<ChatMessagesContainer {...BASE_PROPS} forwardPaginated={false} />);
- expect(
- screen.getByRole("button", { name: /load older messages/i }),
- ).toBeDefined();
- });
-
- it("renders top sentinel when forwardPaginated is undefined (default, backward)", () => {
+ it("renders top sentinel for backward pagination", () => {
render(<ChatMessagesContainer {...BASE_PROPS} />);
expect(
screen.getByRole("button", { name: /load older messages/i }),
).toBeDefined();
});
- it("renders bottom sentinel when forwardPaginated is true (forward pagination)", () => {
- render(<ChatMessagesContainer {...BASE_PROPS} forwardPaginated={true} />);
- expect(
- screen.getByRole("button", { name: /load newer messages/i }),
- ).toBeDefined();
- });
-
it("hides sentinel when hasMoreMessages is false", () => {
- render(
- <ChatMessagesContainer
- {...BASE_PROPS}
- hasMoreMessages={false}
- forwardPaginated={true}
- />,
- );
+ render(<ChatMessagesContainer {...BASE_PROPS} hasMoreMessages={false} />);
expect(
screen.queryByRole("button", { name: /load older messages/i }),
).toBeNull();
});
it("hides sentinel when onLoadMore is not provided", () => {
- render(
- <ChatMessagesContainer
- {...BASE_PROPS}
- onLoadMore={undefined}
- forwardPaginated={true}
- />,
- );
+ render(<ChatMessagesContainer {...BASE_PROPS} onLoadMore={undefined} />);
expect(
screen.queryByRole("button", { name: /load older messages/i }),
).toBeNull();
diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatMessagesContainer/__tests__/LoadMoreSentinel.test.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatMessagesContainer/__tests__/LoadMoreSentinel.test.tsx
index d3f4f08c9e..3cbf4cbe48 100644
--- a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatMessagesContainer/__tests__/LoadMoreSentinel.test.tsx
+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatMessagesContainer/__tests__/LoadMoreSentinel.test.tsx
@@ -172,36 +172,6 @@ describe("LoadMoreSentinel", () => {
expect(mockScrollEl.scrollTop).toBe(200);
});
- it("does NOT adjust scroll when adjustScroll=false (forward pagination)", () => {
- mockScrollEl.scrollHeight = 100;
- mockScrollEl.scrollTop = 50;
- const onLoadMore = vi.fn();
- const { rerender } = render(
- <LoadMoreSentinel
- hasMore={true}
- isLoading={false}
- messageCount={5}
- onLoadMore={onLoadMore}
- adjustScroll={false}
- />,
- );
- // Fire observer to capture snapshot.
- MockIntersectionObserver.lastCallback?.([{ isIntersecting: true }]);
- // Simulate DOM growing from appended newer messages (forward load-more).
- mockScrollEl.scrollHeight = 300;
- rerender(
- <LoadMoreSentinel
- hasMore={true}
- isLoading={false}
- messageCount={10}
- onLoadMore={onLoadMore}
- adjustScroll={false}
- />,
- );
- // scrollTop should remain unchanged — no jump for forward pagination.
- expect(mockScrollEl.scrollTop).toBe(50);
- });
-
it("ignores same-frame duplicate triggers until isLoading transitions", () => {
const onLoadMore = vi.fn();
const { rerender } = render(
diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/useChatSession.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/useChatSession.ts
index 8357ee8af9..b5a02620c2 100644
--- a/autogpt_platform/frontend/src/app/(platform)/copilot/useChatSession.ts
+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/useChatSession.ts
@@ -86,16 +86,6 @@ export function useChatSession({ dryRun = false }: UseChatSessionOptions = {}) {
return sessionQuery.data.data.oldest_sequence ?? null;
}, [sessionQuery.data]);
- const newestSequence = useMemo(() => {
- if (sessionQuery.data?.status !== 200) return null;
- return sessionQuery.data.data.newest_sequence ?? null;
- }, [sessionQuery.data]);
-
- const forwardPaginated = useMemo(() => {
- if (sessionQuery.data?.status !== 200) return false;
- return !!sessionQuery.data.data.forward_paginated;
- }, [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
@@ -195,8 +185,6 @@ export function useChatSession({ dryRun = false }: UseChatSessionOptions = {}) {
hasActiveStream,
hasMoreMessages,
oldestSequence,
- newestSequence,
- forwardPaginated,
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.ts
index 3e9be079db..2d56b27303 100644
--- a/autogpt_platform/frontend/src/app/(platform)/copilot/useCopilotPage.ts
+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/useCopilotPage.ts
@@ -56,8 +56,6 @@ export function useCopilotPage() {
hasActiveStream,
hasMoreMessages,
oldestSequence,
- newestSequence,
- forwardPaginated,
isLoadingSession,
isSessionError,
createSession,
@@ -86,26 +84,19 @@ export function useCopilotPage() {
copilotModel: isModeToggleEnabled ? copilotLlmModel : undefined,
});
- const { pagedMessages, hasMore, isLoadingMore, loadMore, resetPaged } =
+ const { pagedMessages, hasMore, isLoadingMore, loadMore } =
useLoadMoreMessages({
sessionId,
initialOldestSequence: oldestSequence,
- initialNewestSequence: newestSequence,
initialHasMore: hasMoreMessages,
- forwardPaginated,
initialPageRawMessages: rawSessionMessages,
});
// Combine paginated messages with current page messages, merging consecutive
// assistant UIMessages at the page boundary so reasoning + response parts
- // stay in a single bubble.
- // Forward pagination (completed sessions): current page is the beginning,
- // paged messages are newer pages appended after.
- // Backward pagination (active sessions): paged messages are older history
- // prepended before the current page.
- const messages = forwardPaginated
- ? concatWithAssistantMerge(currentMessages, pagedMessages)
- : concatWithAssistantMerge(pagedMessages, currentMessages);
+ // stay in a single bubble. Paged messages are older history prepended before
+ // the current page.
+ const messages = concatWithAssistantMerge(pagedMessages, currentMessages);
useCopilotNotifications(sessionId);
@@ -180,23 +171,6 @@ export function useCopilotPage() {
}
}, [sessionId, pendingMessage, sendMessage]);
- // --- Clear backward-paginated messages when session completes ---
- // When a session transitions from active (forwardPaginated=false) to complete
- // (forwardPaginated=true), any backward-paginated older messages would be
- // appended after currentMessages instead of before, causing chronological
- // disorder. Reset paged state so the completed session renders cleanly.
- const prevForwardPaginatedRef = useRef(forwardPaginated);
- useEffect(() => {
- if (
- !prevForwardPaginatedRef.current &&
- forwardPaginated &&
- pagedMessages.length > 0
- ) {
- resetPaged();
- }
- prevForwardPaginatedRef.current = forwardPaginated;
- }, [forwardPaginated, pagedMessages.length, resetPaged]);
-
// --- Extract prompt from URL hash on mount (e.g. /copilot#prompt=Hello) ---
useWorkflowImportAutoSubmit({
createSession,
@@ -278,15 +252,6 @@ export function useCopilotPage() {
isUserStoppingRef.current = false;
if (sessionId) {
- // When continuing a completed session that had forward-paginated history
- // loaded, the paged messages would appear in wrong position relative to
- // the new streaming turn (pagedMessages are newer pages, so they'd end
- // up after the streaming turn). Reset paged state so ordering is correct
- // during streaming; the user can reload history afterward if needed.
- if (forwardPaginated && pagedMessages.length > 0) {
- resetPaged();
- }
-
if (files && files.length > 0) {
setIsUploadingFiles(true);
try {
@@ -433,7 +398,6 @@ export function useCopilotPage() {
hasMoreMessages: hasMore,
isLoadingMore,
loadMore,
- forwardPaginated,
// Mobile drawer
isMobile,
isDrawerOpen,
diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/useLoadMoreMessages.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/useLoadMoreMessages.ts
index 7c3f1b7c24..2957070c0f 100644
--- a/autogpt_platform/frontend/src/app/(platform)/copilot/useLoadMoreMessages.ts
+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/useLoadMoreMessages.ts
@@ -9,11 +9,7 @@ import {
interface UseLoadMoreMessagesArgs {
sessionId: string | null;
initialOldestSequence: number | null;
- initialNewestSequence: number | null;
initialHasMore: boolean;
- /** True when the initial page was loaded from sequence 0 forward (completed
- * sessions). False when loaded newest-first (active sessions). */
- forwardPaginated: boolean;
/** Raw messages from the initial page, used for cross-page tool output matching. */
initialPageRawMessages: unknown[];
}
@@ -24,9 +20,7 @@ const MAX_OLDER_MESSAGES = 2000;
export function useLoadMoreMessages({
sessionId,
initialOldestSequence,
- initialNewestSequence,
initialHasMore,
- forwardPaginated,
initialPageRawMessages,
}: UseLoadMoreMessagesArgs) {
// Accumulated raw messages from all extra pages (ascending order).
@@ -36,9 +30,6 @@ export function useLoadMoreMessages({
const [oldestSequence, setOldestSequence] = useState<number | null>(
initialOldestSequence,
);
- const [newestSequence, setNewestSequence] = useState<number | null>(
- initialNewestSequence,
- );
const [hasMore, setHasMore] = useState(initialHasMore);
const [isLoadingMore, setIsLoadingMore] = useState(false);
const isLoadingMoreRef = useRef(false);
@@ -46,9 +37,7 @@ export function useLoadMoreMessages({
// 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.
//
@@ -71,10 +60,8 @@ export function useLoadMoreMessages({
if (prevSessionIdRef.current !== sessionId) {
// Session changed — full reset
prevSessionIdRef.current = sessionId;
- prevInitialOldestRef.current = initialOldestSequence;
setPagedRawMessages([]);
setOldestSequence(initialOldestSequence);
- setNewestSequence(initialNewestSequence);
setHasMore(initialHasMore);
setIsLoadingMore(false);
isLoadingMoreRef.current = false;
@@ -83,43 +70,23 @@ export function useLoadMoreMessages({
return;
}
- prevInitialOldestRef.current = initialOldestSequence;
-
// If we haven't paged yet, mirror the parent so the first
// `loadMore` starts from the correct cursor.
- //
- // When paged messages exist (pagedRawMessages.length > 0) we intentionally
- // do NOT update `hasMore` or `newestSequence` from the parent. A parent
- // refetch (e.g. after a new turn completes) may carry a fresh
- // `initialHasMore=true` or a larger `initialNewestSequence`, but those
- // reflect the *initial* page window, not the forward-paged window we have
- // already advanced into. Overwriting the local cursor here would cause the
- // next `loadMore` to re-fetch pages we already have. The local cursor is
- // advanced correctly inside `loadMore` itself via `setNewestSequence`.
if (pagedRawMessages.length === 0) {
setOldestSequence(initialOldestSequence);
- // Only regress the forward cursor if we haven't paged ahead yet —
- // otherwise a parent refetch would reset a cursor we already advanced.
- setNewestSequence((prev) =>
- prev !== null && prev > (initialNewestSequence ?? -1)
- ? prev
- : initialNewestSequence,
- );
setHasMore(initialHasMore);
}
- }, [sessionId, initialOldestSequence, initialNewestSequence, initialHasMore]);
+ }, [sessionId, initialOldestSequence, initialHasMore]);
// Convert all accumulated raw messages in one pass so tool outputs
// are matched across inter-page boundaries.
- // For backward pagination only: include initial page tool outputs so older
- // paged pages can match tool calls whose outputs landed in the initial page.
- // For forward pagination this is unnecessary — tool calls in newer paged
- // pages cannot have their outputs in the older initial page.
+ // Include initial page tool outputs so older paged pages can match
+ // tool calls whose outputs landed in the initial page.
const pagedMessages: UIMessage<unknown, UIDataTypes, UITools>[] =
useMemo(() => {
if (!sessionId || pagedRawMessages.length === 0) return [];
const extraToolOutputs =
- !forwardPaginated && initialPageRawMessages.length > 0
+ initialPageRawMessages.length > 0
? extractToolOutputsFromRaw(initialPageRawMessages)
: undefined;
return convertChatSessionMessagesToUiMessages(
@@ -127,22 +94,20 @@ export function useLoadMoreMessages({
pagedRawMessages,
{ isComplete: true, extraToolOutputs },
).messages;
- }, [sessionId, pagedRawMessages, initialPageRawMessages, forwardPaginated]);
+ }, [sessionId, pagedRawMessages, initialPageRawMessages]);
async function loadMore() {
if (!sessionId || !hasMore || isLoadingMoreRef.current) return;
-
- const cursor = forwardPaginated ? newestSequence : oldestSequence;
- if (cursor === null) return;
+ if (oldestSequence === null) return;
const requestEpoch = epochRef.current;
isLoadingMoreRef.current = true;
setIsLoadingMore(true);
try {
- const params = forwardPaginated
- ? { limit: 50, after_sequence: cursor }
- : { limit: 50, before_sequence: cursor };
- const response = await getV2GetSession(sessionId, params);
+ const response = await getV2GetSession(sessionId, {
+ limit: 50,
+ before_sequence: oldestSequence,
+ });
// Discard response if session/pagination was reset while awaiting
if (epochRef.current !== requestEpoch) return;
@@ -161,66 +126,23 @@ export function useLoadMoreMessages({
consecutiveErrorsRef.current = 0;
const newRaw = (response.data.messages ?? []) as unknown[];
- // Estimate total after merge using the closure-captured pagedRawMessages.length.
- // This is a safe approximation: worst case it's one page stale (one extra load
- // allowed), but it avoids the React-18-batching pitfall where a functional
- // updater's mutations are not visible until the next render.
const estimatedTotal = pagedRawMessages.length + newRaw.length;
setPagedRawMessages((prev) => {
- // Forward: append to end. Backward: prepend to start.
- const merged = forwardPaginated
- ? [...prev, ...newRaw]
- : [...newRaw, ...prev];
+ const merged = [...newRaw, ...prev];
if (merged.length > MAX_OLDER_MESSAGES) {
- // Backward: discard the oldest (front) items — user has scrolled far
- // back and we shed the furthest history.
- // Forward: discard the newest (tail) items — we only ever fetch
- // forward, so the tail is the most recently appended page; shedding
- // it means the sentinel stalls, which is safer than discarding the
- // beginning of the conversation the user is here to read.
- return forwardPaginated
- ? merged.slice(0, MAX_OLDER_MESSAGES)
- : merged.slice(merged.length - MAX_OLDER_MESSAGES);
+ return merged.slice(merged.length - MAX_OLDER_MESSAGES);
}
return merged;
});
- if (forwardPaginated) {
- const willTruncateForward = estimatedTotal > MAX_OLDER_MESSAGES;
- if (willTruncateForward) {
- // Truncation shed the newest tail. Advance the cursor to the last KEPT
- // item's sequence so the sentinel re-fetches the discarded items next
- // time rather than jumping past them.
- // lastKeptIdx: index within newRaw of the last item that survives.
- // prev contributes pagedRawMessages.length items; total kept = MAX.
- const lastKeptIdx = MAX_OLDER_MESSAGES - 1 - pagedRawMessages.length;
- if (lastKeptIdx >= 0 && lastKeptIdx < newRaw.length) {
- const lastKeptMsg = newRaw[lastKeptIdx] as { sequence?: number };
- if (typeof lastKeptMsg?.sequence === "number") {
- setNewestSequence(lastKeptMsg.sequence);
- setHasMore(true); // Discarded items still exist — keep sentinel active
- } else {
- // Sequence unavailable — fall back; truncated items will be lost
- setNewestSequence(response.data.newest_sequence ?? null);
- setHasMore(!!response.data.has_more_messages);
- }
- } else {
- // All of newRaw was dropped (already at MAX_OLDER_MESSAGES cap).
- // Stop to avoid an infinite re-fetch loop at the display cap.
- setHasMore(false);
- }
- } else {
- setNewestSequence(response.data.newest_sequence ?? null);
- setHasMore(!!response.data.has_more_messages);
- }
+ // Note: after truncation, oldest_sequence may reference a dropped
+ // message. This is safe because we also set hasMore=false below,
+ // preventing further loads with the stale cursor.
+ setOldestSequence(response.data.oldest_sequence ?? null);
+ if (estimatedTotal >= MAX_OLDER_MESSAGES) {
+ setHasMore(false);
} else {
- setOldestSequence(response.data.oldest_sequence ?? null);
- if (estimatedTotal >= MAX_OLDER_MESSAGES) {
- // Backward: accumulated MAX_OLDER_MESSAGES — stop to avoid unbounded memory.
- setHasMore(false);
- } else {
- setHasMore(!!response.data.has_more_messages);
- }
+ setHasMore(!!response.data.has_more_messages);
}
} catch (error) {
if (epochRef.current !== requestEpoch) return;
@@ -237,22 +159,5 @@ export function useLoadMoreMessages({
}
}
- function resetPaged() {
- setPagedRawMessages([]);
- setOldestSequence(initialOldestSequence);
- setNewestSequence(initialNewestSequence);
- // Set hasMore=false during the session-transition window so no loadMore
- // fires with forward pagination (after_sequence) on the now-active session.
- // The useEffect will restore hasMore from the parent after the refetch
- // completes and forwardPaginated switches to false.
- setHasMore(false);
- // Clear the loading state so the spinner doesn't stay stuck if a loadMore
- // was in flight when resetPaged was called.
- setIsLoadingMore(false);
- isLoadingMoreRef.current = false;
- consecutiveErrorsRef.current = 0;
- epochRef.current += 1;
- }
-
- return { pagedMessages, hasMore, isLoadingMore, loadMore, resetPaged };
+ return { pagedMessages, hasMore, isLoadingMore, loadMore };
}
diff --git a/autogpt_platform/frontend/src/app/api/openapi.json b/autogpt_platform/frontend/src/app/api/openapi.json
index bba1c867fb..24ec485dbc 100644
--- a/autogpt_platform/frontend/src/app/api/openapi.json
+++ b/autogpt_platform/frontend/src/app/api/openapi.json
@@ -1498,7 +1498,7 @@
"get": {
"tags": ["v2", "chat", "chat"],
"summary": "Get Session",
- "description": "Retrieve the details of a specific chat session.\n\nSupports cursor-based pagination via ``limit``, ``before_sequence``, and\n``after_sequence``. The two cursor parameters are mutually exclusive.\n\nOn the initial load (no cursor provided) of a completed session, messages\nare returned in forward order starting from sequence 0 so the user always\nsees their initial prompt. Active sessions use the legacy newest-first\norder so streaming context is preserved.",
+ "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.",
"operationId": "getV2GetSession",
"security": [{ "HTTPBearerJWT": [] }],
"parameters": [
@@ -1516,11 +1516,9 @@
"type": "integer",
"maximum": 200,
"minimum": 1,
- "description": "Maximum number of messages to return.",
"default": 50,
"title": "Limit"
- },
- "description": "Maximum number of messages to return."
+ }
},
{
"name": "before_sequence",
@@ -1531,24 +1529,8 @@
{ "type": "integer", "minimum": 0 },
{ "type": "null" }
],
- "description": "Backward pagination cursor. Return messages with sequence number strictly less than this value. Used by active-session load-more. Mutually exclusive with after_sequence.",
"title": "Before Sequence"
- },
- "description": "Backward pagination cursor. Return messages with sequence number strictly less than this value. Used by active-session load-more. Mutually exclusive with after_sequence."
- },
- {
- "name": "after_sequence",
- "in": "query",
- "required": false,
- "schema": {
- "anyOf": [
- { "type": "integer", "minimum": 0 },
- { "type": "null" }
- ],
- "description": "Forward pagination cursor. Return messages with sequence number strictly greater than this value. Used by completed-session load-more. Mutually exclusive with before_sequence.",
- "title": "After Sequence"
- },
- "description": "Forward pagination cursor. Return messages with sequence number strictly greater than this value. Used by completed-session load-more. Mutually exclusive with before_sequence."
+ }
}
],
"responses": {
@@ -13302,15 +13284,6 @@
"anyOf": [{ "type": "integer" }, { "type": "null" }],
"title": "Oldest Sequence"
},
- "newest_sequence": {
- "anyOf": [{ "type": "integer" }, { "type": "null" }],
- "title": "Newest Sequence"
- },
- "forward_paginated": {
- "type": "boolean",
- "title": "Forward Paginated",
- "default": false
- },
"total_prompt_tokens": {
"type": "integer",
"title": "Total Prompt Tokens",