feat: add chat history pagination and reasoning blocks - #9667
Open
wcqqq1214 wants to merge 6 commits into
Open
Conversation
Restore the thread panel to pre-AstrBotDevs#9652 behavior: full history without pagination and inline reasoning content. Reverts the out-of-scope thread additions while keeping main-session pagination and reasoning lazy-loading.
wcqqq1214
force-pushed
the
feat/9652-chat-history-pagination
branch
from
August 14, 2026 13:23
319708e to
837b115
Compare
wcqqq1214
marked this pull request as ready for review
August 14, 2026 14:40
Contributor
There was a problem hiding this comment.
Hey - I've found 2 issues
Prompt for AI Agents
Please address the comments from this code review:
## Individual Comments
### Comment 1
<location path="dashboard/src/components/chat/Chat.vue" line_range="1739-1748" />
<code_context>
+ const sessionId = currSessionId.value;
+ if (!sessionId || activeSessionPagination.value?.loading) return;
+ const container = messagesContainer.value;
+ const firstMessage = activeMessages.value[0];
+ const firstId = firstMessage?.id == null ? "" : String(firstMessage.id);
+ const beforeTop = firstId
+ ? container?.querySelector<HTMLElement>(
+ `[data-message-id="${CSS.escape(firstId)}"]`,
+ )?.getBoundingClientRect().top
+ : undefined;
+ suppressAutoScroll.value = true;
+ try {
+ await loadEarlierMessages(sessionId);
+ if (currSessionId.value !== sessionId) return;
+ await nextTick();
+ if (beforeTop == null || !container || !firstId) return;
+ const row = container.querySelector<HTMLElement>(
+ `[data-message-id="${CSS.escape(firstId)}"]`,
+ );
</code_context>
<issue_to_address>
**suggestion:** Anchoring scroll to the first message can fail silently when the first row has no stable ID.
In `loadEarlierWithAnchor`, anchoring relies on `activeMessages.value[0].id`. If that message has `id == null` or its DOM row is missing, `beforeTop` remains undefined and the function exits after loading without restoring scroll, causing a jump when paging. You could instead fall back to the current `scrollTop` when `firstId` is falsy, or anchor on the first message in `activeMessages.value` with a non-null `id`.
Suggested implementation:
```
async function loadEarlierWithAnchor() {
const sessionId = currSessionId.value;
if (!sessionId || activeSessionPagination.value?.loading) return;
const container = messagesContainer.value;
const firstMessage = activeMessages.value[0];
const anchorMessage =
activeMessages.value.find((message) => message.id != null) ?? firstMessage;
const firstId =
anchorMessage?.id == null ? "" : String(anchorMessage.id);
let beforeTop: number | undefined;
if (firstId) {
const row = container?.querySelector<HTMLElement>(
`[data-message-id="${CSS.escape(firstId)}"]`,
);
beforeTop = row?.getBoundingClientRect().top;
} else if (container) {
// Fall back to the current scrollTop when the first row has no stable id
beforeTop = container.scrollTop;
}
suppressAutoScroll.value = true;
const target = activeReasoningTarget.value;
```
The existing logic after this snippet that:
1. Calls `await loadEarlierMessages(sessionId);`
2. Awaits `nextTick();`
3. Reads the DOM row for `firstId` and adjusts scroll based on the change in `getBoundingClientRect().top`
needs to be updated to:
- Use the `beforeTop` computed above (which may come from `scrollTop` when `firstId` is falsy).
- If `firstId` is truthy, continue to anchor using the corresponding `[data-message-id="..."]` row and adjust `scrollTop` by the delta in `top`.
- If `firstId` is falsy, skip querying by `data-message-id` and instead restore `container.scrollTop` to `beforeTop` after paging, ensuring scroll doesn’t jump when the first row has no stable id.
</issue_to_address>
### Comment 2
<location path="astrbot/dashboard/api/chat.py" line_range="157" />
<code_context>
+ )
+
+
+@router.get(
+ "/chat/messages/{message_id}",
+ openapi_extra={"x-astrbot-sensitive-scopes": [CHAT_ADMIN_SCOPE]},
</code_context>
<issue_to_address>
**issue (complexity):** Consider extracting the username resolution and admin-id filtering logic into dedicated helper functions to simplify the route’s control flow.
You can reduce the route’s complexity by extracting the username resolution and admin-id rejection into small helpers. This keeps behavior identical but makes the control flow easier to follow and test.
For example:
```python
def _resolve_effective_username(
auth: AuthContext,
username: str | None,
service: ChatService,
) -> str:
if auth.via != "api_key":
return auth.username
effective_username = str(username or "").strip()
if not effective_username:
raise ApiError("Message not found", status_code=404)
if "*" in auth.scopes or CHAT_ADMIN_SCOPE in auth.scopes:
return effective_username
if _is_reserved_admin_id(effective_username, service):
raise ApiError("Message not found", status_code=404)
return effective_username
def _is_reserved_admin_id(effective_username: str, service: ChatService) -> bool:
configs = getattr(
getattr(service, "core_lifecycle", None),
"astrbot_config_mgr",
None,
)
for config in getattr(configs, "confs", {}).values():
admin_ids = config.get("admins_id", []) if isinstance(config, dict) else []
if any(str(admin_id) == effective_username for admin_id in admin_ids):
return True
return False
```
Then the route becomes a straight-line flow:
```python
@router.get(
"/chat/messages/{message_id}",
openapi_extra={"x-astrbot-sensitive-scopes": [CHAT_ADMIN_SCOPE]},
)
async def get_chat_message(
message_id: int = Path(..., gt=0),
username: str | None = Query(default=None),
auth: AuthContext = Depends(require_chat_scope),
service: ChatService = Depends(get_service),
):
effective_username = _resolve_effective_username(auth, username, service)
try:
return ok(await service.get_message(effective_username, message_id))
except ChatServiceError as exc:
raise ApiError("Message not found", status_code=404) from exc
```
This keeps all current semantics (including the 404-on-any-failure behavior and admin ID restriction) but moves the nested logic out of the route, making it easier to understand and maintain.
</issue_to_address>Help me be more useful! Please click 👍 or 👎 on each comment and I'll use the feedback to improve your reviews.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Fixes #9652
This PR adds paginated loading for chat session history and lazy-loads reasoning/thinking content so long conversations stay responsive. Older messages load page-by-page as you scroll up instead of one large initial fetch, and the collapsed reasoning block only downloads its body when opened.
Modifications / 改动点
Backend: paginate session history (
page/page_size/has_more) with boundary validation (default 1000; dashboard uses 50).Strip reasoning bodies from the history payload; expose
has_reasoning/reasoning_lenmarkers plus a lazy reasoning-content endpoint.Add a
countinterface to the DB layer for pagination totals.Dashboard: infinite scroll-up loading for earlier messages in the main session.
Render collapsed reasoning entries (think / legacy
reasoningpart / top-levelreasoning) with lazy load and multi-block support.Sync OpenAPI spec, regenerate the TS client, and update scope docs (en / zh).
This is NOT a breaking change. / 这不是一个破坏性变更。
Screenshots or Test Results / 运行截图或测试结果
Automated
uv run pytest -q tests/test_chat_route.py tests/unit/test_chat_history_pagination.py tests/unit/test_openapi_scope_docs.py— 23 passeduv run ruff format ./uv run ruff check .— cleancd dashboard && npx vue-tsc --noEmit— cleanManual (real SQLite DB, deployed with Docker on an ECS server)
page/page_size/total/has_moremetadata is accurate at the boundaries (a page beyond the last returns empty,has_moreflips to false).reasoning) are stripped from list responses intohas_reasoning/reasoning_lenmarkers; the full body is fetched only on expand viaGET /chat/messages/{id}, which returns the unstripped record;deepcopyleaves the stored ORM object untouched (unit-tested).GET /chat/messages/{id}returns a uniform 404 for missing or unauthorized records without leaking existence.page=0/-1andpage_size=0/1001are rejected with 422; omitting the parameters keeps the legacy defaultpage_size=1000.Checklist / 检查清单
😊 If there are new features added in the PR, I have discussed it with the authors through issues/emails, etc.
/ 如果 PR 中有新加入的功能,已经通过 Issue / 邮件等方式和作者讨论过。
👀 My changes have been well-tested, and "Verification Steps" and "Screenshots" have been provided above.
/ 我的更改经过了良好的测试,并已在上方提供了“验证步骤”和“运行截图”。
🤓 I have ensured that no new dependencies are introduced, OR if new dependencies are introduced, they have been added to the appropriate locations in
requirements.txtandpyproject.toml./ 我确保没有引入新依赖库,或者引入了新依赖库的同时将其添加到
requirements.txt和pyproject.toml文件相应位置。😮 My changes do not introduce malicious code.
/ 我的更改没有引入恶意代码。
Summary by Sourcery
Add paginated chat history loading and lazy reasoning retrieval for sessions and threads in the dashboard and API, keeping long conversations responsive while preserving ownership and scope guarantees.
New Features:
Enhancements:
Tests:
Summary by Sourcery
Add paginated chat history loading and lazy reasoning retrieval for dashboard sessions, along with a secure message detail endpoint and updated OpenAPI/docs.
New Features:
Enhancements:
Tests: