Skip to content

RAGFlow is an agent-native database: a Retrieval-Augmented Generation (RAG) engine that grew into context infrastructure.

Fix list chat/agent session paging (#21604)

Wang Qi0f6d0e9bd48f
diff --git a/internal/dao/chat_session.go b/internal/dao/chat_session.go
index 2e5f629714..db5d5c4f44 100644
--- a/internal/dao/chat_session.go
+++ b/internal/dao/chat_session.go
@@ -147,20 +147,30 @@ func (dao *ChatSessionDAO) DeleteByID(ctx context.Context, db *gorm.DB, id strin
})
}
-// ListByResourceIDs lists only sessions authorized by the permission layer.
-func (dao *ChatSessionDAO) ListByResourceIDs(ctx context.Context, db *gorm.DB, chatID string, sessionIDs []string, sessionID, name string, terms []OrderTerm, page, pageSize int, includeHistory ...bool) ([]*entity.ChatSession, error) {
- if len(sessionIDs) == 0 {
- return []*entity.ChatSession{}, nil
+// ListByResourceIDs lists sessions for a chat, optionally restricted to sessionIDs.
+func (dao *ChatSessionDAO) ListByResourceIDs(ctx context.Context, db *gorm.DB, chatID string, sessionIDs []string, sessionID, name string, terms []OrderTerm, page, pageSize int, includeHistory ...bool) ([]*entity.ChatSession, int64, error) {
+ if sessionIDs != nil && len(sessionIDs) == 0 {
+ return []*entity.ChatSession{}, 0, nil
}
var chatSessions []*entity.ChatSession
- query := db.WithContext(ctx).Session(&gorm.Session{QueryFields: true}).Where("dialog_id = ? AND id IN ?", chatID, sessionIDs)
+ query := db.WithContext(ctx).Session(&gorm.Session{QueryFields: true}).Model(&entity.ChatSession{}).Where("dialog_id = ?", chatID)
+ if sessionIDs != nil {
+ query = query.Where("id IN ?", sessionIDs)
+ }
if sessionID != "" {
query = query.Where("id = ?", sessionID)
}
if name != "" {
query = query.Where("name = ?", name)
}
- query = query.Order(chatSessionOrderClause(terms))
+ var total int64
+ if err := query.Count(&total).Error; err != nil {
+ return nil, 0, err
+ }
+ if pageSize == 0 {
+ return []*entity.ChatSession{}, total, nil
+ }
+ query = query.Order(chatSessionOrderClause(terms)).Order("id DESC")
if pageSize > 0 {
if page < 1 {
page = 1
@@ -169,14 +179,14 @@ func (dao *ChatSessionDAO) ListByResourceIDs(ctx context.Context, db *gorm.DB, c
}
err := query.Find(&chatSessions).Error
if err != nil {
- return nil, err
+ return nil, 0, err
}
if len(includeHistory) == 0 || includeHistory[0] {
if err = hydrateChatSessions(ctx, db, chatSessions); err != nil {
- return nil, err
+ return nil, 0, err
}
}
- return chatSessions, nil
+ return chatSessions, total, nil
}
// GetDialogByID gets dialog by ID
@@ -210,14 +220,28 @@ func (dao *ChatSessionDAO) DeleteByDialogIDs(ctx context.Context, db *gorm.DB, d
return rowsAffected, err
}
-func (dao *ChatSessionDAO) ListAgentSessionNames(ctx context.Context, db *gorm.DB, agentID, expUserID string) ([]map[string]interface{}, error) {
+func (dao *ChatSessionDAO) ListAgentSessionNames(ctx context.Context, db *gorm.DB, agentID, expUserID string, page, pageSize int) (int64, []map[string]interface{}, error) {
+ query := db.WithContext(ctx).Model(&entity.API4Conversation{}).Where("dialog_id = ? AND exp_user_id = ?", agentID, expUserID)
+ var total int64
+ if err := query.Count(&total).Error; err != nil {
+ return 0, nil, err
+ }
+
+ if page <= 0 {
+ page = 1
+ }
+ if pageSize <= 0 {
+ pageSize = 30
+ }
+
var rows []map[string]interface{}
- err := db.WithContext(ctx).Model(&entity.API4Conversation{}).
+ err := query.
Select("id", "name").
- Where("dialog_id = ? AND exp_user_id = ?", agentID, expUserID).
- Order("create_date DESC").
+ Order("create_date DESC, id DESC").
+ Offset((page - 1) * pageSize).
+ Limit(pageSize).
Find(&rows).Error
- return rows, err
+ return total, rows, err
}
func normalizeAgentSessionOrderBy(orderBy string) string {
diff --git a/internal/handler/agent.go b/internal/handler/agent.go
index f764dec694..95fbd47de4 100644
--- a/internal/handler/agent.go
+++ b/internal/handler/agent.go
@@ -967,8 +967,8 @@ func (h *AgentHandler) ListAgentSessions(c *gin.Context) {
return
}
canvasID := c.Param("canvas_id")
- page, _ := strconv.Atoi(c.DefaultQuery("page", "0"))
- pageSize, _ := strconv.Atoi(c.DefaultQuery("page_size", "0"))
+ page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
+ pageSize, _ := strconv.Atoi(c.DefaultQuery("page_size", "30"))
keywords := c.Query("keywords")
fromDate := c.Query("from_date")
toDate := c.Query("to_date")
diff --git a/internal/handler/chat_session.go b/internal/handler/chat_session.go
index ca968177f5..88dd6383cf 100644
--- a/internal/handler/chat_session.go
+++ b/internal/handler/chat_session.go
@@ -119,7 +119,7 @@ func (h *ChatSessionHandler) ListChatSessions(c *gin.Context) {
return
}
- common.SuccessWithData(c, result.Sessions, "success")
+ common.SuccessWithDataAndTotal(c, result.Sessions, result.Total, "success")
}
type ChatCompletionsRequest struct {
diff --git a/internal/service/agent_sessions.go b/internal/service/agent_sessions.go
index 6b1ef11b14..9969b1589f 100644
--- a/internal/service/agent_sessions.go
+++ b/internal/service/agent_sessions.go
@@ -325,11 +325,11 @@ func (s *AgentService) ListAgentSessions(ctx context.Context, userID, _ string,
sessionDAO := dao.NewChatSessionDAO()
if req.ExpUserID != "" {
- rows, err := sessionDAO.ListAgentSessionNames(ctx, dao.DB, agentID, req.ExpUserID)
+ total, rows, err := sessionDAO.ListAgentSessionNames(ctx, dao.DB, agentID, req.ExpUserID, req.Page, req.PageSize)
if err != nil {
return nil, common.CodeServerError, err
}
- return &ListAgentSessionsResponse{Data: rows, Total: int64(len(rows))}, common.CodeSuccess, nil
+ return &ListAgentSessionsResponse{Data: rows, Total: total}, common.CodeSuccess, nil
}
fromDate, err := parseAgentSessionDate(req.FromDate, false)
diff --git a/internal/service/agent_test.go b/internal/service/agent_test.go
index d9569121bb..3827ed8d27 100644
--- a/internal/service/agent_test.go
+++ b/internal/service/agent_test.go
@@ -20,6 +20,7 @@ import (
"context"
"encoding/json"
"errors"
+ "fmt"
"net/netip"
"reflect"
"strings"
@@ -1005,6 +1006,34 @@ func TestListAgentSessionsServiceSuccess(t *testing.T) {
if _, ok := messages[0]["prompt"]; ok {
t.Fatal("expected prompt to be removed from normalized session message")
}
+
+ createdAt := time.Unix(1, 0)
+ for i := 0; i < 41; i++ {
+ id := fmt.Sprintf("exp-session-%02d", i)
+ if err := dao.DB.Create(&entity.API4Conversation{
+ ID: id, Name: sptr(id), DialogID: "canvas-1", UserID: "user-1", ExpUserID: sptr("exp-user"),
+ BaseModel: entity.BaseModel{CreateDate: &createdAt},
+ }).Error; err != nil {
+ t.Fatalf("failed to create explore session: %v", err)
+ }
+ }
+ for _, page := range []struct{ number, size, count int }{{1, 30, 30}, {4, 10, 10}, {5, 10, 1}, {6, 10, 0}} {
+ resp, code, err := NewAgentService().ListAgentSessions(ctx, "user-1", "user-1", "canvas-1", ListAgentSessionsRequest{
+ Page: page.number, PageSize: page.size, ExpUserID: "exp-user",
+ })
+ if err != nil || code != common.CodeSuccess {
+ t.Fatalf("explore page %d: code=%d err=%v", page.number, code, err)
+ }
+ if resp.Total != 41 || len(resp.Data) != page.count {
+ t.Fatalf("explore page %d: total=%d rows=%d, want total=41 rows=%d", page.number, resp.Total, len(resp.Data), page.count)
+ }
+ for i, row := range resp.Data {
+ wantID := fmt.Sprintf("exp-session-%02d", 40-(page.number-1)*page.size-i)
+ if len(row) != 2 || row["id"] != wantID {
+ t.Fatalf("explore page %d row %d: got %v, want id/name for %s", page.number, i, row, wantID)
+ }
+ }
+ }
}
func TestListAgentSessionsServiceDenied(t *testing.T) {
diff --git a/internal/service/chat_session.go b/internal/service/chat_session.go
index 42a4055d5c..d4472bf7b6 100644
--- a/internal/service/chat_session.go
+++ b/internal/service/chat_session.go
@@ -49,10 +49,15 @@ type chatSessionStore interface {
Create(ctx context.Context, db *gorm.DB, conv *entity.ChatSession) error
UpdateByID(ctx context.Context, db *gorm.DB, id string, updates map[string]interface{}) error
DeleteByID(ctx context.Context, db *gorm.DB, id string) error
- ListByResourceIDs(ctx context.Context, db *gorm.DB, chatID string, sessionIDs []string, sessionID, name string, terms []dao.OrderTerm, page, pageSize int, includeHistory ...bool) ([]*entity.ChatSession, error)
+ ListByResourceIDs(ctx context.Context, db *gorm.DB, chatID string, sessionIDs []string, sessionID, name string, terms []dao.OrderTerm, page, pageSize int, includeHistory ...bool) ([]*entity.ChatSession, int64, error)
GetDialogByID(ctx context.Context, db *gorm.DB, chatID string) (*entity.Chat, error)
}
+type chatSessionPermissionChecker interface {
+ resourceScopeChecker
+ FilterResources(context.Context, permission.Subject, []permission.ResourceRef, permission.Operation) ([]permission.ResourceRef, error)
+}
+
type chatPipelineRunner interface {
AsyncChat(ctx context.Context, userID string, chat *entity.Chat, messages []map[string]interface{}, stream bool, kwargs map[string]interface{}) (<-chan AsyncChatResult, error)
}
@@ -83,7 +88,7 @@ type chunkPagerankAdjuster interface {
// The RAG pipeline is delegated to ChatPipelineService.
type ChatSessionService struct {
chatSessionDAO chatSessionStore
- permissionChecker resourceScopeChecker
+ permissionChecker chatSessionPermissionChecker
pipeline chatPipelineRunner
modelFactory chatModelInfoResolver
chunkFeedbackApplier chunkFeedbackApplier
@@ -108,6 +113,7 @@ type ListChatSessionsRequest struct {
// ListChatSessionsResponse list chat sessions response
type ListChatSessionsResponse struct {
Sessions []*entity.ChatSession
+ Total int64
}
type ChatSessionPayload struct {
@@ -126,24 +132,45 @@ type ChatSessionPayload struct {
// ListChatSessions lists chat sessions for a dialog
func (s *ChatSessionService) ListChatSessions(ctx context.Context, userID, chatID, sessionID, name string, terms []dao.OrderTerm, page, pageSize int, includeHistory ...bool) (*ListChatSessionsResponse, error) {
- sessionIDs, err := accessibleChatSessionIDs(ctx, s.permissionChecker, userID, chatID, permission.OperationRead)
- if err != nil {
+ if err := checkChatPermission(ctx, s.permissionChecker, userID, chatID, permission.OperationRead); err != nil {
_, normalizedErr := normalizeChatPermissionError(err)
return nil, normalizedErr
}
- // items_per_page == 0 returns an empty list (mirrors Python's list_sessions).
- if pageSize == 0 {
- return &ListChatSessionsResponse{Sessions: []*entity.ChatSession{}}, nil
- }
-
// List chat sessions
- sessions, err := s.chatSessionDAO.ListByResourceIDs(ctx, dao.DB, chatID, sessionIDs, sessionID, name, terms, page, pageSize, includeHistory...)
+ sessions, total, err := s.chatSessionDAO.ListByResourceIDs(ctx, dao.DB, chatID, nil, sessionID, name, terms, page, pageSize, includeHistory...)
if err != nil {
return nil, err
}
+ if len(sessions) == 0 {
+ return &ListChatSessionsResponse{Sessions: sessions, Total: total}, nil
+ }
+
+ checker := s.permissionChecker
+ if checker == nil {
+ checker = permission.NewDatabaseChecker(dao.DB)
+ }
+ refs := make([]permission.ResourceRef, 0, len(sessions))
+ for _, session := range sessions {
+ refs = append(refs, permission.ResourceRef{Kind: permission.ResourceKindChatSession, ID: session.ID})
+ }
+ accessible, err := checker.FilterResources(ctx, permission.Subject{UserID: userID}, refs, permission.OperationRead)
+ if err != nil {
+ _, normalizedErr := normalizeChatPermissionError(err)
+ return nil, normalizedErr
+ }
+ allowedIDs := make(map[string]bool, len(accessible))
+ for _, ref := range accessible {
+ allowedIDs[ref.ID] = true
+ }
+ filtered := make([]*entity.ChatSession, 0, len(accessible))
+ for _, session := range sessions {
+ if allowedIDs[session.ID] {
+ filtered = append(filtered, session)
+ }
+ }
- return &ListChatSessionsResponse{Sessions: sessions}, nil
+ return &ListChatSessionsResponse{Sessions: filtered, Total: total}, nil
}
// GetSession returns one chat session after ownership validation.
@@ -264,7 +291,7 @@ func (s *ChatSessionService) DeleteSessions(ctx context.Context, userID, chatID
if len(sessionIDs) == 0 {
return map[string]interface{}{}, "success", common.CodeSuccess, nil
}
- sessions, err := s.chatSessionDAO.ListByResourceIDs(ctx, dao.DB, chatID, sessionIDs, "", "", []dao.OrderTerm{{Column: "create_time", Desc: true}}, 0, -1, false)
+ sessions, _, err := s.chatSessionDAO.ListByResourceIDs(ctx, dao.DB, chatID, sessionIDs, "", "", []dao.OrderTerm{{Column: "create_time", Desc: true}}, 0, -1, false)
if err != nil {
return nil, "", common.CodeServerError, err
}
diff --git a/internal/service/chat_session_contract_test.go b/internal/service/chat_session_contract_test.go
index e0aaeed78d..1b293cb018 100644
--- a/internal/service/chat_session_contract_test.go
+++ b/internal/service/chat_session_contract_test.go
@@ -38,6 +38,10 @@ func (emptyChatSessionScopeChecker) Scope(context.Context, permission.Subject, p
return permission.Scope{Mode: permission.ScopeNone}, nil
}
+func (c emptyChatSessionScopeChecker) FilterResources(context.Context, permission.Subject, []permission.ResourceRef, permission.Operation) ([]permission.ResourceRef, error) {
+ return nil, c.checkErr
+}
+
// ---------------------------------------------------------------------------
// CreateSession contract — mirrors the assertions in
// test_session_create_validation_and_deleted_chat_contract that exercise the
diff --git a/internal/service/chat_session_test.go b/internal/service/chat_session_test.go
index e017499f00..ed0707ce2e 100644
--- a/internal/service/chat_session_test.go
+++ b/internal/service/chat_session_test.go
@@ -4,6 +4,7 @@ import (
"context"
"encoding/json"
"errors"
+ "fmt"
"math"
"reflect"
"strings"
@@ -33,6 +34,8 @@ type fakeSessionStore struct {
createErr error
updateByIDErr error
getDialogErr error
+ scopeCalls int
+ filteredRefs []permission.ResourceRef
// record calls
createCalled []*entity.ChatSession
updateCalled []struct {
@@ -164,7 +167,7 @@ func (f *fakeSessionStore) DeleteByID(ctx context.Context, db *gorm.DB, id strin
return nil
}
-func (f *fakeSessionStore) ListByResourceIDs(_ context.Context, _ *gorm.DB, chatID string, sessionIDs []string, sessionID, name string, _ []dao.OrderTerm, _, _ int, _ ...bool) ([]*entity.ChatSession, error) {
+func (f *fakeSessionStore) ListByResourceIDs(_ context.Context, _ *gorm.DB, chatID string, sessionIDs []string, sessionID, name string, _ []dao.OrderTerm, _, pageSize int, _ ...bool) ([]*entity.ChatSession, int64, error) {
allowedIDs := make(map[string]struct{}, len(sessionIDs))
for _, id := range sessionIDs {
allowedIDs[id] = struct{}{}
@@ -174,7 +177,7 @@ func (f *fakeSessionStore) ListByResourceIDs(_ context.Context, _ *gorm.DB, chat
if s.DialogID != chatID {
continue
}
- if _, ok := allowedIDs[s.ID]; !ok {
+ if _, ok := allowedIDs[s.ID]; sessionIDs != nil && !ok {
continue
}
if sessionID != "" && s.ID != sessionID {
@@ -191,7 +194,11 @@ func (f *fakeSessionStore) ListByResourceIDs(_ context.Context, _ *gorm.DB, chat
}
result = append(result, s)
}
- return result, nil
+ total := int64(len(result))
+ if pageSize == 0 {
+ result = []*entity.ChatSession{}
+ }
+ return result, total, nil
}
func (f *fakeSessionStore) GetDialogByID(ctx context.Context, db *gorm.DB, chatID string) (*entity.Chat, error) {
@@ -261,6 +268,7 @@ func (f *fakeSessionStore) CheckResource(_ context.Context, subject permission.S
}
func (f *fakeSessionStore) Scope(ctx context.Context, subject permission.Subject, query permission.ScopeQuery) (permission.Scope, error) {
+ f.scopeCalls++
if query.Kind != permission.ResourceKindChatSession || query.Parent.Kind != permission.ResourceKindChat {
return permission.Scope{}, permission.ErrInvalidPermission
}
@@ -292,6 +300,21 @@ func (f *fakeSessionStore) Scope(ctx context.Context, subject permission.Subject
return scope, nil
}
+func (f *fakeSessionStore) FilterResources(ctx context.Context, subject permission.Subject, refs []permission.ResourceRef, operation permission.Operation) ([]permission.ResourceRef, error) {
+ f.filteredRefs = append(f.filteredRefs, refs...)
+ var accessible []permission.ResourceRef
+ for _, ref := range refs {
+ if err := f.CheckResource(ctx, subject, ref, operation); err != nil {
+ if errors.Is(err, permission.ErrPermissionDenied) || errors.Is(err, permission.ErrResourceNotFound) {
+ continue
+ }
+ return nil, err
+ }
+ accessible = append(accessible, ref)
+ }
+ return accessible, nil
+}
+
// ---------------------------------------------------------------------------
type fakePipeline struct {
@@ -430,24 +453,60 @@ func requireFloatClose(t *testing.T, got, want float64) {
// ===================================================================
func TestListChatSessions_Success(t *testing.T) {
+ db := setupChatListTestDB(t)
+ if err := db.AutoMigrate(&entity.ChatSession{}); err != nil {
+ t.Fatalf("failed to migrate sessions: %v", err)
+ }
store := newFakeSessionStore()
- store.sessions["s1"] = &entity.ChatSession{ID: "s1", DialogID: "chat-1"}
- store.sessions["s2"] = &entity.ChatSession{ID: "s2", DialogID: "chat-1"}
+ createdAt := int64(1000)
+ for i := 0; i < 41; i++ {
+ session := &entity.ChatSession{ID: fmt.Sprintf("session-%02d", i), DialogID: "chat-1", BaseModel: entity.BaseModel{CreateTime: &createdAt}}
+ store.sessions[session.ID] = session
+ if err := db.Create(session).Error; err != nil {
+ t.Fatalf("failed to create session: %v", err)
+ }
+ }
+ if err := db.Create(&entity.ChatSession{ID: "other-chat-session", DialogID: "chat-2"}).Error; err != nil {
+ t.Fatalf("failed to create other chat session: %v", err)
+ }
store.dialogExists["tenant-1|chat-1"] = true
svc := &ChatSessionService{
- chatSessionDAO: store,
+ chatSessionDAO: dao.NewChatSessionDAO(),
permissionChecker: store,
pipeline: &fakePipeline{},
}
ctx := t.Context()
- resp, err := svc.ListChatSessions(ctx, "user-1", "chat-1", "", "", []dao.OrderTerm{{Column: "create_time", Desc: true}}, 1, 30)
+ terms := []dao.OrderTerm{{Column: "create_time", Desc: true}}
+ resp, err := svc.ListChatSessions(ctx, "user-1", "chat-1", "", "", terms, 1, 30, false)
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
- if len(resp.Sessions) != 2 {
- t.Fatalf("expected 2 sessions, got %d", len(resp.Sessions))
+ if resp.Total != 41 || len(resp.Sessions) != 30 || len(store.filteredRefs) != 30 || store.scopeCalls != 0 {
+ t.Fatalf("expected total=41 and 30 sessions checked without a full scope scan, got total=%d sessions=%d checked=%d scope=%d", resp.Total, len(resp.Sessions), len(store.filteredRefs), store.scopeCalls)
+ }
+ for i, session := range resp.Sessions {
+ if want := fmt.Sprintf("session-%02d", 40-i); session.ID != want || store.filteredRefs[i].ID != want {
+ t.Fatalf("session %d: got %s, checked %s, want %s", i, session.ID, store.filteredRefs[i].ID, want)
+ }
+ }
+ for page, wantCount := range map[int]int{4: 10, 5: 1, 6: 0} {
+ resp, err := svc.ListChatSessions(ctx, "user-1", "chat-1", "", "", terms, page, 10, false)
+ if err != nil {
+ t.Fatalf("page %d: %v", page, err)
+ }
+ if resp.Total != 41 || len(resp.Sessions) != wantCount {
+ t.Fatalf("page %d: got total=%d and %d sessions, want total=41 and %d sessions", page, resp.Total, len(resp.Sessions), wantCount)
+ }
+ }
+ resp, err = svc.ListChatSessions(ctx, "user-1", "chat-1", "", "", terms, 1, 0, false)
+ if err != nil || resp.Total != 41 || len(resp.Sessions) != 0 {
+ t.Fatalf("zero page size: got response=%+v err=%v, want total=41 and no sessions", resp, err)
+ }
+ resp, err = svc.ListChatSessions(ctx, "user-1", "chat-1", "session-01", "", terms, 1, 30, false)
+ if err != nil || resp.Total != 1 || len(resp.Sessions) != 1 {
+ t.Fatalf("ID filter: got response=%+v err=%v, want total=1 and one session", resp, err)
}
}
diff --git a/web/src/hooks/use-agent-request.ts b/web/src/hooks/use-agent-request.ts
index 036f32be31..9a20be698f 100644
--- a/web/src/hooks/use-agent-request.ts
+++ b/web/src/hooks/use-agent-request.ts
@@ -68,6 +68,7 @@ import {
useGetPaginationWithRouter,
useHandleSearchChange,
} from './logic-hooks';
+import { useSessionList } from './use-session-list';
export const enum AgentApiAction {
FetchAgentListByPage = 'fetchAgentListByPage',
@@ -1004,35 +1005,28 @@ export const useFetchAgentLog = (searchParams: IAgentLogsRequest) => {
return { data, loading, refetch };
};
+export const AgentSessionKeys = {
+ all: [AgentApiAction.FetchSessionsByCanvasId] as const,
+ list: (canvasId?: string, tenantId?: string) =>
+ [...AgentSessionKeys.all, canvasId, tenantId] as const,
+};
+
export const useFetchSessionsByCanvasId = () => {
const { id: canvasId } = useParams();
const { data: tenantInfo } = useFetchTenantInfo();
- const { data, isFetching: loading } = useQuery<IAgentLogsResponse>({
- queryKey: [AgentApiAction.FetchSessionsByCanvasId, canvasId],
- initialData: { total: 0, sessions: [] } as IAgentLogsResponse,
- gcTime: 0,
+ return useSessionList<IAgentLogResponse>({
+ queryKey: AgentSessionKeys.list(canvasId, tenantInfo.tenant_id),
enabled: !!canvasId && !isEmpty(tenantInfo),
- queryFn: async () => {
- if (!canvasId) {
- return { total: 0, sessions: [] };
- }
-
- const { data } = await fetchAgentLogsByCanvasId(canvasId, {
- page: 1,
- page_size: 100,
+ fetchPage: async (params) => {
+ const { data } = await fetchAgentLogsByCanvasId(canvasId!, {
+ ...params,
exp_user_id: tenantInfo.tenant_id,
});
- return { total: data?.total ?? 0, sessions: data?.data ?? [] };
+ return { total: data?.total ?? 0, items: data?.data ?? [] };
},
});
-
- return {
- data: data?.sessions ?? [],
- loading,
- total: data?.total ?? 0,
- };
};
export const useFetchExternalAgentInputs = () => {
@@ -1382,7 +1376,7 @@ export function useCreateAgentSession() {
if (data.code === 0) {
queryClient.invalidateQueries({
- queryKey: [AgentApiAction.FetchSessionsByCanvasId],
+ queryKey: AgentSessionKeys.all,
});
return data.data;
}
@@ -1414,7 +1408,7 @@ export function useDeleteAgentSession() {
if (data.code === 0) {
queryClient.invalidateQueries({
- queryKey: [AgentApiAction.FetchSessionsByCanvasId],
+ queryKey: AgentSessionKeys.all,
});
}
diff --git a/web/src/hooks/use-chat-request.ts b/web/src/hooks/use-chat-request.ts
index a4807ff59a..a9f5cc92ab 100644
--- a/web/src/hooks/use-chat-request.ts
+++ b/web/src/hooks/use-chat-request.ts
@@ -39,7 +39,7 @@ import { markListItemsDeleted } from '@/utils/list-deletion-util';
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
import { useDebounce } from 'ahooks';
import { has } from 'lodash';
-import { useCallback, useRef } from 'react';
+import { useCallback, useMemo, useRef } from 'react';
import { useTranslation } from 'react-i18next';
import { useParams, useSearchParams } from 'react-router';
import {
@@ -47,6 +47,7 @@ import {
useHandleSearchChange,
} from './logic-hooks';
import { useHandleSearchStrChange } from './logic-hooks/use-change-search';
+import { useSessionList } from './use-session-list';
export const enum ChatApiAction {
FetchChatList = 'fetchChatList',
@@ -76,6 +77,11 @@ export const AgenticRagKeys = {
[...AgenticRagKeys.all, 'config', chatId] as const,
};
+export const ChatSessionKeys = {
+ all: [ChatApiAction.FetchSessionList] as const,
+ list: (chatId?: string) => [...ChatSessionKeys.all, chatId] as const,
+};
+
export const useGetChatSearchParams = () => {
const [currentQueryParameters] = useSearchParams();
@@ -323,34 +329,29 @@ export const useFetchSessionList = () => {
const { searchString, handleInputChange, setSearchString } =
useHandleSearchStrChange();
- const {
- data,
- isFetching: loading,
- refetch,
- } = useQuery<IConversation[]>({
- queryKey: [ChatApiAction.FetchSessionList, id],
- initialData: [],
- gcTime: 0,
- refetchOnWindowFocus: false,
+ const result = useSessionList<IConversation>({
+ queryKey: ChatSessionKeys.list(id),
enabled: !!id,
- select(data) {
- return searchString
- ? data.filter((x) => x.name.includes(searchString))
- : data;
- },
- queryFn: async () => {
+ fetchPage: async (params) => {
const { data } = await chatService.listSessions(
- { url: api.listSessions(id!) },
+ { chatId: id, params: { ...params, include_history: false } },
true,
);
- return data?.data;
+ return { items: data?.data ?? [], total: data?.total ?? 0 };
},
});
+ const data = useMemo(
+ () =>
+ searchString
+ ? result.data.filter((session) => session.name.includes(searchString))
+ : result.data,
+ [result.data, searchString],
+ );
+
return {
+ ...result,
data,
- loading,
- refetch,
searchString,
handleInputChange,
setSearchString,
@@ -397,7 +398,7 @@ export const useCreateSession = () => {
);
if (data.code === 0) {
queryClient.invalidateQueries({
- queryKey: [ChatApiAction.FetchSessionList],
+ queryKey: ChatSessionKeys.all,
});
}
return data;
@@ -431,7 +432,7 @@ export const useUpdateSession = () => {
);
if (data.code === 0) {
queryClient.invalidateQueries({
- queryKey: [ChatApiAction.FetchSessionList],
+ queryKey: ChatSessionKeys.all,
});
message.success(t(`message.modified`));
}
@@ -459,7 +460,7 @@ export const useRemoveSessions = () => {
);
if (data.code === 0) {
queryClient.invalidateQueries({
- queryKey: [ChatApiAction.FetchSessionList],
+ queryKey: ChatSessionKeys.all,
});
}
return data.code;
diff --git a/web/src/hooks/use-session-list.ts b/web/src/hooks/use-session-list.ts
new file mode 100644
index 0000000000..26ec150662
--- /dev/null
+++ b/web/src/hooks/use-session-list.ts
@@ -0,0 +1,81 @@
+import { useInfiniteQuery } from '@tanstack/react-query';
+import { uniqBy } from 'lodash';
+import { UIEvent, useCallback, useMemo } from 'react';
+
+type SessionPage<T> = {
+ items: T[];
+ total: number;
+};
+
+export function useSessionList<T extends { id: string }>({
+ queryKey,
+ enabled,
+ fetchPage,
+}: {
+ queryKey: readonly unknown[];
+ enabled: boolean;
+ fetchPage: (params: {
+ page: number;
+ page_size: number;
+ }) => Promise<SessionPage<T>>;
+}) {
+ const {
+ data,
+ isFetching,
+ isFetchingNextPage,
+ hasNextPage,
+ fetchNextPage,
+ refetch,
+ } = useInfiniteQuery({
+ queryKey,
+ enabled,
+ gcTime: 0,
+ refetchOnWindowFocus: false,
+ initialPageParam: 0,
+ queryFn: ({ pageParam: offset }) => {
+ // Keep offsets continuous when switching from 30 initial rows to 10-row pages.
+ const pageSize = offset === 0 ? 30 : 10;
+ return fetchPage({ page: offset / pageSize + 1, page_size: pageSize });
+ },
+ getNextPageParam: (lastPage, pages, offset) => {
+ const pageSize = offset === 0 ? 30 : 10;
+ const loadedCount = pages.reduce(
+ (count, page) => count + page.items.length,
+ 0,
+ );
+ if (lastPage.items.length < pageSize || loadedCount >= lastPage.total) {
+ return undefined;
+ }
+ return offset + pageSize;
+ },
+ });
+
+ const sessions = useMemo(
+ () => uniqBy(data?.pages.flatMap((page) => page.items) ?? [], 'id'),
+ [data],
+ );
+
+ const handleScroll = useCallback(
+ (event: UIEvent<HTMLDivElement>) => {
+ const { scrollTop, scrollHeight, clientHeight } = event.currentTarget;
+ if (
+ scrollHeight - scrollTop - clientHeight <= 50 &&
+ hasNextPage &&
+ !isFetching
+ ) {
+ void fetchNextPage({ cancelRefetch: false });
+ }
+ },
+ [fetchNextPage, hasNextPage, isFetching],
+ );
+
+ return {
+ data: sessions,
+ total: data?.pages.at(-1)?.total ?? 0,
+ loading: isFetching,
+ loadingMore: isFetchingNextPage,
+ hasMore: !!hasNextPage,
+ handleScroll,
+ refetch,
+ };
+}
diff --git a/web/src/pages/agent/explore/components/session-list.tsx b/web/src/pages/agent/explore/components/session-list.tsx
index 9b1a3796c2..36a4b8a1ee 100644
--- a/web/src/pages/agent/explore/components/session-list.tsx
+++ b/web/src/pages/agent/explore/components/session-list.tsx
@@ -2,7 +2,7 @@ import { Button } from '@/components/ui/button';
import { SearchInput } from '@/components/ui/input';
import { useClientSearch } from '@/hooks/use-client-search';
import { IAgentLogResponse } from '@/interfaces/database/agent';
-import { Plus } from 'lucide-react';
+import { Loader2, Plus } from 'lucide-react';
import { useTranslation } from 'react-i18next';
import { useSelectDerivedSessionList } from '../hooks/use-select-derived-session-list';
import { SessionCard } from './session-card';
@@ -18,8 +18,15 @@ export function SessionList({
}: SessionListProps) {
const { t } = useTranslation();
- const { sessions, loading, addTemporarySession, removeTemporarySession } =
- useSelectDerivedSessionList();
+ const {
+ sessions,
+ total,
+ loading,
+ loadingMore,
+ handleScroll,
+ addTemporarySession,
+ removeTemporarySession,
+ } = useSelectDerivedSessionList();
const { filteredData, handleSearchChange, searchKeyword } =
useClientSearch<IAgentLogResponse>({
@@ -32,9 +39,7 @@ export function SessionList({
<div className="flex items-center justify-between mb-4">
<div className="flex items-center gap-2">
<h2 className="text-base font-bold">{t('explore.sessions')}</h2>
- <span className="text-xs text-text-secondary">
- {filteredData.length}
- </span>
+ <span className="text-xs text-text-secondary">{total}</span>
</div>
<Button variant="ghost" size="icon" onClick={addTemporarySession}>
<Plus className="h-4 w-4" />
@@ -47,7 +52,7 @@ export function SessionList({
value={searchKeyword}
/>
</div>
- <div className="flex-1 overflow-auto space-y-3">
+ <div className="flex-1 overflow-auto space-y-3" onScroll={handleScroll}>
{filteredData.map((session) => (
<SessionCard
key={session.id}
@@ -57,6 +62,13 @@ export function SessionList({
removeTemporarySession={removeTemporarySession}
/>
))}
+ {loadingMore && (
+ <Loader2
+ className="mx-auto size-4 animate-spin"
+ role="status"
+ aria-label={t('common.loading')}
+ />
+ )}
{!loading && filteredData.length === 0 && (
<div className="text-center text-text-secondary py-8">
{searchKeyword
diff --git a/web/src/pages/agent/explore/hooks/use-select-derived-session-list.ts b/web/src/pages/agent/explore/hooks/use-select-derived-session-list.ts
index 6125249866..333553a274 100644
--- a/web/src/pages/agent/explore/hooks/use-select-derived-session-list.ts
+++ b/web/src/pages/agent/explore/hooks/use-select-derived-session-list.ts
@@ -8,9 +8,15 @@ export const useSelectDerivedSessionList = () => {
Array<IAgentLogResponse & { is_new?: boolean }>
>([]);
- const { data: sessions = [], loading } = useFetchSessionsByCanvasId();
+ const {
+ data: sessions,
+ total,
+ loading,
+ loadingMore,
+ handleScroll,
+ } = useFetchSessionsByCanvasId();
- const { setSessionId } = useExploreUrlParams();
+ const { setSessionId, isNew, canvasId } = useExploreUrlParams();
const addTemporarySession = useCallback(() => {
const now = Date.now() / 1000;
@@ -47,12 +53,18 @@ export const useSelectDerivedSessionList = () => {
// Sync server data to local state
useEffect(() => {
- setList(sessions);
- }, [sessions]);
+ setList((previous) => [
+ ...previous.filter((session) => session.is_new && isNew === 'true'),
+ ...sessions,
+ ]);
+ }, [sessions, isNew, canvasId]);
return {
sessions: list,
+ total,
loading,
+ loadingMore,
+ handleScroll,
addTemporarySession,
removeTemporarySession,
};
diff --git a/web/src/pages/next-chats/chat/sessions.tsx b/web/src/pages/next-chats/chat/sessions.tsx
index e0430b87a5..7e8d34f47f 100644
--- a/web/src/pages/next-chats/chat/sessions.tsx
+++ b/web/src/pages/next-chats/chat/sessions.tsx
@@ -21,6 +21,7 @@ import {
import {
LucideCopyX,
LucideListChecks,
+ LucideLoader2,
LucidePanelLeftClose,
LucidePlus,
LucideSend,
@@ -44,10 +45,13 @@ export function Sessions({ handleConversationCardClick }: SessionProps) {
const { t } = useTranslation();
const {
list: conversationList,
+ total,
addTemporaryConversation,
removeTemporaryConversation,
handleInputChange,
searchString,
+ loadingMore,
+ handleScroll,
} = useSelectDerivedConversationList();
const { data } = useFetchChat();
const { visible, switchVisible } = useSetModalState(true);
@@ -244,11 +248,8 @@ export function Sessions({ handleConversationCardClick }: SessionProps) {
<div className="flex justify-between items-center mb-4 pt-10">
<div className="flex items-center gap-3">
<span className="text-base font-bold">{t('chat.conversations')}</span>
- <data
- className="text-text-secondary text-xs"
- value={conversationList.length}
- >
- {conversationList.length}
+ <data className="text-text-secondary text-xs" value={total}>
+ {total}
</data>
</div>
@@ -322,7 +323,7 @@ export function Sessions({ handleConversationCardClick }: SessionProps) {
></SearchInput>
</div>
- <div className="flex-1 overflow-auto">
+ <div className="flex-1 overflow-auto" onScroll={handleScroll}>
{selectionMode ? (
<ul className="space-y-2" role="listbox" aria-multiselectable>
{conversationList.map((x) => (
@@ -382,6 +383,13 @@ export function Sessions({ handleConversationCardClick }: SessionProps) {
</ul>
</nav>
)}
+ {loadingMore && (
+ <LucideLoader2
+ className="mx-auto size-4 animate-spin"
+ role="status"
+ aria-label={t('common.loading')}
+ />
+ )}
</div>
</aside>
);
diff --git a/web/src/pages/next-chats/hooks/use-select-conversation-list.ts b/web/src/pages/next-chats/hooks/use-select-conversation-list.ts
index 624deeacc2..c625e7dbed 100644
--- a/web/src/pages/next-chats/hooks/use-select-conversation-list.ts
+++ b/web/src/pages/next-chats/hooks/use-select-conversation-list.ts
@@ -3,6 +3,7 @@ import { useTranslate } from '@/hooks/common-hooks';
import {
useFetchChatList,
useFetchSessionList,
+ useGetChatSearchParams,
} from '@/hooks/use-chat-request';
import { IConversation } from '@/interfaces/database/chat';
import { generateConversationId } from '@/utils/chat';
@@ -27,7 +28,10 @@ export const useSelectDerivedConversationList = () => {
const [list, setList] = useState<Array<IConversation>>([]);
const {
data: conversationList,
+ total,
loading,
+ loadingMore,
+ handleScroll,
handleInputChange,
searchString,
setSearchString,
@@ -36,6 +40,7 @@ export const useSelectDerivedConversationList = () => {
const { id: dialogId } = useParams();
const prologue = useFindPrologueFromDialogList();
const { setConversationBoth } = useChatUrlParams();
+ const { isNew } = useGetChatSearchParams();
const addTemporaryConversation = useCallback(() => {
const conversationId = generateConversationId();
@@ -82,28 +87,24 @@ export const useSelectDerivedConversationList = () => {
});
}, []);
- // When you first enter the page, select the top conversation card
-
- // useEffect(() => {
- // setList((prevList) => {
- // const tempItems = prevList.filter((item) => item.is_new);
- // const existingTempIds = new Set(tempItems.map((t) => t.id));
- // const newItems = conversationList.filter(
- // (item) => !existingTempIds.has(item.id),
- // );
- // return [...tempItems, ...newItems];
- // });
- // }, [conversationList]);
-
useEffect(() => {
- setList([...conversationList]);
- }, [conversationList]);
+ setList((previous) => [
+ ...previous.filter(
+ (session) =>
+ session.is_new && session.chat_id === dialogId && isNew === 'true',
+ ),
+ ...conversationList,
+ ]);
+ }, [conversationList, dialogId, isNew]);
return {
list,
+ total,
addTemporaryConversation,
removeTemporaryConversation,
loading,
+ loadingMore,
+ handleScroll,
handleInputChange,
searchString,
};
diff --git a/web/src/services/next-chat-service.ts b/web/src/services/next-chat-service.ts
index 6b62b756e3..d437a46ac2 100644
--- a/web/src/services/next-chat-service.ts
+++ b/web/src/services/next-chat-service.ts
@@ -78,7 +78,7 @@ const methods = {
method: 'post',
},
listSessions: {
- url: listSessions,
+ url: ({ chatId }: { chatId: string }) => listSessions(chatId),
method: 'get',
},
getSession: {