Skip to content

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

fix(chat): honor the exact id and name filters when listing chats (#19962)

MarMar Labse73aa1dacada
diff --git a/internal/dao/chat.go b/internal/dao/chat.go
index 744dc4aaf2..095e2e54a5 100644
--- a/internal/dao/chat.go
+++ b/internal/dao/chat.go
@@ -55,7 +55,7 @@ func (dao *ChatDAO) ListByTenantID(ctx context.Context, db *gorm.DB, tenantID st
}
// ListByTenantIDs list chats by tenant IDs with pagination and filtering
-func (dao *ChatDAO) ListByTenantIDs(ctx context.Context, db *gorm.DB, tenantIDs []string, userID string, page, pageSize int, terms []OrderTerm, keywords string) ([]*entity.ChatListItem, int64, error) {
+func (dao *ChatDAO) ListByTenantIDs(ctx context.Context, db *gorm.DB, tenantIDs []string, userID string, page, pageSize int, terms []OrderTerm, keywords, id, name string) ([]*entity.ChatListItem, int64, error) {
var chats []*entity.ChatListItem
var total int64
@@ -79,6 +79,14 @@ func (dao *ChatDAO) ListByTenantIDs(ctx context.Context, db *gorm.DB, tenantIDs
query = query.Where("LOWER(dialog.name) LIKE ?", "%"+strings.ToLower(keywords)+"%")
}
+ // Apply the exact filters. An empty value means absent, like keywords.
+ if id != "" {
+ query = query.Where("dialog.id = ?", id)
+ }
+ if name != "" {
+ query = query.Where("dialog.name = ?", name)
+ }
+
// Apply ordering. Route the requested terms through chatOrderClause so a user-supplied
// query param can never reach Order() verbatim: the helper validates
// against chatOrderableColumns (a closed allowlist) and falls back to
@@ -107,7 +115,7 @@ func (dao *ChatDAO) ListByTenantIDs(ctx context.Context, db *gorm.DB, tenantIDs
}
// ListByOwnerIDs list chats by owner IDs with pagination and filtering
-func (dao *ChatDAO) ListByOwnerIDs(ctx context.Context, db *gorm.DB, ownerIDs []string, userID string, page, pageSize int, terms []OrderTerm, keywords string) ([]*entity.ChatListItem, int64, error) {
+func (dao *ChatDAO) ListByOwnerIDs(ctx context.Context, db *gorm.DB, ownerIDs []string, userID string, page, pageSize int, terms []OrderTerm, keywords, id, name string) ([]*entity.ChatListItem, int64, error) {
var chats []*entity.ChatListItem
var total int64
@@ -126,6 +134,14 @@ func (dao *ChatDAO) ListByOwnerIDs(ctx context.Context, db *gorm.DB, ownerIDs []
query = query.Where("LOWER(dialog.name) LIKE ?", "%"+strings.ToLower(keywords)+"%")
}
+ // Apply the exact filters. An empty value means absent, like keywords.
+ if id != "" {
+ query = query.Where("dialog.id = ?", id)
+ }
+ if name != "" {
+ query = query.Where("dialog.name = ?", name)
+ }
+
// Filter by owner IDs (additional filter to ensure tenant_id is in ownerIDs)
query = query.Where("dialog.tenant_id IN ?", ownerIDs)
diff --git a/internal/dao/chat_test.go b/internal/dao/chat_test.go
index e95ee0a248..84ecede3b3 100644
--- a/internal/dao/chat_test.go
+++ b/internal/dao/chat_test.go
@@ -102,7 +102,7 @@ func TestChatDAOListByTenantIDsOrderByExpressionFallsBack(t *testing.T) {
for _, orderby := range chatOrderExpressions {
t.Run(orderby, func(t *testing.T) {
- rows, _, err := d.ListByTenantIDs(ctx, db, []string{"t1"}, "t1", 1, 10, []OrderTerm{{Column: orderby}}, "")
+ rows, _, err := d.ListByTenantIDs(ctx, db, []string{"t1"}, "t1", 1, 10, []OrderTerm{{Column: orderby}}, "", "", "")
if err != nil {
t.Fatalf("ListByTenantIDs with orderby %q: %v", orderby, err)
}
@@ -122,7 +122,7 @@ func TestChatDAOListByOwnerIDsOrderByExpressionFallsBack(t *testing.T) {
for _, orderby := range chatOrderExpressions {
t.Run(orderby, func(t *testing.T) {
- rows, _, err := d.ListByOwnerIDs(ctx, db, []string{"t1"}, "t1", 1, 10, []OrderTerm{{Column: orderby}}, "")
+ rows, _, err := d.ListByOwnerIDs(ctx, db, []string{"t1"}, "t1", 1, 10, []OrderTerm{{Column: orderby}}, "", "", "")
if err != nil {
t.Fatalf("ListByOwnerIDs with orderby %q: %v", orderby, err)
}
@@ -140,19 +140,35 @@ func TestChatDAOListOrderByAllowedColumn(t *testing.T) {
ctx := t.Context()
d := NewChatDAO()
- rows, _, err := d.ListByTenantIDs(ctx, db, []string{"t1"}, "t1", 1, 10, []OrderTerm{{Column: "name"}}, "")
+ rows, _, err := d.ListByTenantIDs(ctx, db, []string{"t1"}, "t1", 1, 10, []OrderTerm{{Column: "name"}}, "", "", "")
if err != nil {
t.Fatalf("ListByTenantIDs ascending by name: %v", err)
}
assertChatOrder(t, rows, []string{"c-3", "c-2", "c-1"}, "name")
- rows, _, err = d.ListByTenantIDs(ctx, db, []string{"t1"}, "t1", 1, 10, []OrderTerm{{Column: "name", Desc: true}}, "")
+ rows, _, err = d.ListByTenantIDs(ctx, db, []string{"t1"}, "t1", 1, 10, []OrderTerm{{Column: "name", Desc: true}}, "", "", "")
if err != nil {
t.Fatalf("ListByTenantIDs descending by name: %v", err)
}
assertChatOrder(t, rows, []string{"c-1", "c-2", "c-3"}, "name")
}
+func assertChatRows(t *testing.T, rows []*entity.ChatListItem, total int64, want []string) {
+ t.Helper()
+ got := make([]string, 0, len(rows))
+ for _, row := range rows {
+ got = append(got, row.ID)
+ }
+ if len(got) != len(want) || total != int64(len(want)) {
+ t.Fatalf("rows %v total %d, want rows %v total %d", got, total, want, len(want))
+ }
+ for i := range want {
+ if got[i] != want[i] {
+ t.Fatalf("rows %v, want %v", got, want)
+ }
+ }
+}
+
// assertChatIDs compares the returned row IDs against wantIDs, naming the call
// under test in the failure message. assertChatOrder is for the ORDER BY
// allowlist tests, whose failure message talks about expressions reaching the
@@ -173,6 +189,57 @@ func assertChatIDs(t *testing.T, rows []*entity.ChatListItem, wantIDs []string,
}
}
+// TestChatDAOListExactIDAndNameFilters checks that the exact id and name
+// predicates narrow both list branches and that the reported total follows
+// the filtered rows.
+func TestChatDAOListExactIDAndNameFilters(t *testing.T) {
+ db := setupChatTestDB(t)
+ pushDB(t, db)
+ seedOrderableChats(t, db)
+ // A fourth chat whose name contains "alpha", so the name case only passes
+ // with an exact predicate and not with a substring match.
+ alphaTwo := entity.Chat{ID: "c-4", TenantID: "t1", Name: stringPtr("alpha two"), BaseModel: entity.BaseModel{CreateTime: int64Ptr(400)}}
+ alphaTwo.LLMID = "llm-1"
+ alphaTwo.LLMSetting = entity.JSONMap{}
+ alphaTwo.PromptType = "simple"
+ alphaTwo.PromptConfig = entity.JSONMap{}
+ alphaTwo.DoRefer = "1"
+ alphaTwo.KBIDs = entity.JSONSlice{}
+ alphaTwo.Status = stringPtr("1")
+ if err := db.Create(&alphaTwo).Error; err != nil {
+ t.Fatalf("failed to create chat c-4: %v", err)
+ }
+ ctx := t.Context()
+ d := NewChatDAO()
+ terms := []OrderTerm{{Column: "create_time"}}
+
+ for _, tc := range []struct {
+ label string
+ id string
+ name string
+ want []string
+ }{
+ {label: "id", id: "c-2", want: []string{"c-2"}},
+ {label: "name", name: "alpha", want: []string{"c-3"}},
+ {label: "unknown id", id: "unknown", want: []string{}},
+ } {
+ t.Run("tenant "+tc.label, func(t *testing.T) {
+ rows, total, err := d.ListByTenantIDs(ctx, db, []string{"t1"}, "t1", 1, 10, terms, "", tc.id, tc.name)
+ if err != nil {
+ t.Fatalf("ListByTenantIDs: %v", err)
+ }
+ assertChatRows(t, rows, total, tc.want)
+ })
+ t.Run("owner "+tc.label, func(t *testing.T) {
+ rows, total, err := d.ListByOwnerIDs(ctx, db, []string{"t1"}, "t1", 1, 10, terms, "", tc.id, tc.name)
+ if err != nil {
+ t.Fatalf("ListByOwnerIDs: %v", err)
+ }
+ assertChatRows(t, rows, total, tc.want)
+ })
+ }
+}
+
// seedChatRowsWithCreateTime creates count chats owned by tenantID whose
// create_time grows with their index, so page boundaries are deterministic.
func seedChatRowsWithCreateTime(t *testing.T, db *gorm.DB, tenantID string, count int) {
@@ -225,7 +292,7 @@ func TestChatDAOListByOwnerIDsPaginatesInSQL(t *testing.T) {
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
- rows, total, err := d.ListByOwnerIDs(ctx, db, []string{"t1"}, "t1", tt.page, tt.pageSize, terms, "")
+ rows, total, err := d.ListByOwnerIDs(ctx, db, []string{"t1"}, "t1", tt.page, tt.pageSize, terms, "", "", "")
if err != nil {
t.Fatalf("ListByOwnerIDs(page=%d, pageSize=%d): %v", tt.page, tt.pageSize, err)
}
@@ -250,7 +317,7 @@ func TestChatDAOListByOwnerIDsKeepsJoinedOwnerColumnsWhenPaginated(t *testing.T)
t.Fatalf("failed to create user: %v", err)
}
- rows, total, err := NewChatDAO().ListByOwnerIDs(ctx, db, []string{"t1"}, "t1", 1, 2, []OrderTerm{{Column: "create_time", Desc: true}}, "")
+ rows, total, err := NewChatDAO().ListByOwnerIDs(ctx, db, []string{"t1"}, "t1", 1, 2, []OrderTerm{{Column: "create_time", Desc: true}}, "", "", "")
if err != nil {
t.Fatalf("ListByOwnerIDs: %v", err)
}
diff --git a/internal/handler/chat.go b/internal/handler/chat.go
index 089b1b3478..35c668d05b 100644
--- a/internal/handler/chat.go
+++ b/internal/handler/chat.go
@@ -82,6 +82,13 @@ func (h *ChatHandler) ListChats(c *gin.Context) {
// Parse query parameters
keywords := c.Query("keywords")
+ // Exact id and name filters take precedence over the fuzzy keyword
+ // search, as in the Python route and the API reference.
+ id := c.Query("id")
+ name := c.Query("name")
+ if id != "" || name != "" {
+ keywords = ""
+ }
page := 0
if pageStr := c.Query("page"); pageStr != "" {
@@ -120,7 +127,7 @@ func (h *ChatHandler) ListChats(c *gin.Context) {
ctx := c.Request.Context()
// List chats - default to valid status "1" (same as Python StatusEnum.VALID.value)
- result, err := h.chatService.ListChats(ctx, userID, "1", keywords, page, pageSize, terms, ownerIDs)
+ result, err := h.chatService.ListChats(ctx, userID, "1", keywords, id, name, page, pageSize, terms, ownerIDs)
if err != nil {
common.ResponseWithHttpCodeData(c, http.StatusInternalServerError, 500, nil, err.Error())
return
diff --git a/internal/handler/mcp_server.go b/internal/handler/mcp_server.go
index 818db68755..7e42e7bf02 100644
--- a/internal/handler/mcp_server.go
+++ b/internal/handler/mcp_server.go
@@ -127,7 +127,7 @@ func mcpListDatasets(ctx context.Context, ds *dataset.DatasetService, userID str
// mcpListChats wraps ChatService.ListChats for the MCP tool handler,
// converting the typed response into a generic []map[string]interface{}.
func mcpListChats(ctx context.Context, chatService *service.ChatService, userID string, page, pageSize int, orderby string, desc bool) ([]map[string]interface{}, int64, error) {
- resp, err := chatService.ListChats(ctx, userID, "1", "", page, pageSize, []dao.OrderTerm{{Column: orderby, Desc: desc}}, nil)
+ resp, err := chatService.ListChats(ctx, userID, "1", "", "", "", page, pageSize, []dao.OrderTerm{{Column: orderby, Desc: desc}}, nil)
if err != nil {
return nil, 0, err
}
diff --git a/internal/service/chat.go b/internal/service/chat.go
index 46d6005a62..13096a44ac 100644
--- a/internal/service/chat.go
+++ b/internal/service/chat.go
@@ -97,7 +97,7 @@ type ListChatsResponse struct {
}
// ListChats list chats for a user
-func (s *ChatService) ListChats(ctx context.Context, userID, status, keywords string, page, pageSize int, terms []dao.OrderTerm, ownerIDs []string) (*ListChatsResponse, error) {
+func (s *ChatService) ListChats(ctx context.Context, userID, status, keywords, id, name string, page, pageSize int, terms []dao.OrderTerm, ownerIDs []string) (*ListChatsResponse, error) {
var chats []*entity.ChatListItem
var total int64
var err error
@@ -112,6 +112,8 @@ func (s *ChatService) ListChats(ctx context.Context, userID, status, keywords st
pageSize,
terms,
keywords,
+ id,
+ name,
)
if err != nil {
return nil, err
@@ -129,7 +131,7 @@ func (s *ChatService) ListChats(ctx context.Context, userID, status, keywords st
}, nil
}
- chats, total, err = s.chatDAO.ListByOwnerIDs(ctx, dao.DB, filterOwnerIDs, userID, page, pageSize, terms, keywords)
+ chats, total, err = s.chatDAO.ListByOwnerIDs(ctx, dao.DB, filterOwnerIDs, userID, page, pageSize, terms, keywords, id, name)
if err != nil {
return nil, err
}
diff --git a/internal/service/chat_list_test.go b/internal/service/chat_list_test.go
index 0e278a71c2..49b283ffcf 100644
--- a/internal/service/chat_list_test.go
+++ b/internal/service/chat_list_test.go
@@ -84,7 +84,7 @@ func TestChatServiceListChatsDefaultReturnsAllWithCorrectTotal(t *testing.T) {
svc := NewChatService()
ctx := t.Context()
- result, err := svc.ListChats(ctx, "user-1", "1", "", 0, 0, []dao.OrderTerm{{Column: "create_time", Desc: true}}, nil)
+ result, err := svc.ListChats(ctx, "user-1", "1", "", "", "", 0, 0, []dao.OrderTerm{{Column: "create_time", Desc: true}}, nil)
if err != nil {
t.Fatalf("ListChats failed: %v", err)
}
@@ -126,7 +126,7 @@ func TestChatServiceListChatsFiltersByOwnerIDs(t *testing.T) {
svc := NewChatService()
ctx := t.Context()
- result, err := svc.ListChats(ctx, "user-1", "1", "", 0, 0, []dao.OrderTerm{{Column: "create_time", Desc: true}}, []string{"tenant-2"})
+ result, err := svc.ListChats(ctx, "user-1", "1", "", "", "", 0, 0, []dao.OrderTerm{{Column: "create_time", Desc: true}}, []string{"tenant-2"})
if err != nil {
t.Fatalf("ListChats failed: %v", err)
}
@@ -150,7 +150,7 @@ func TestChatServiceListChatsKeywordFiltersCorrectly(t *testing.T) {
svc := NewChatService()
ctx := t.Context()
- exactResult, err := svc.ListChats(ctx, "user-1", "1", "list_keyword_1", 0, 0, []dao.OrderTerm{{Column: "create_time", Desc: true}}, nil)
+ exactResult, err := svc.ListChats(ctx, "user-1", "1", "list_keyword_1", "", "", 0, 0, []dao.OrderTerm{{Column: "create_time", Desc: true}}, nil)
if err != nil {
t.Fatalf("ListChats keyword exact failed: %v", err)
}
@@ -161,7 +161,7 @@ func TestChatServiceListChatsKeywordFiltersCorrectly(t *testing.T) {
t.Fatalf("expected chat name 'list_keyword_1', got %+v", exactResult.Chats[0].Name)
}
- unknownResult, err := svc.ListChats(ctx, "user-1", "1", "unknown_keyword", 0, 0, []dao.OrderTerm{{Column: "create_time", Desc: true}}, nil)
+ unknownResult, err := svc.ListChats(ctx, "user-1", "1", "unknown_keyword", "", "", 0, 0, []dao.OrderTerm{{Column: "create_time", Desc: true}}, nil)
if err != nil {
t.Fatalf("ListChats unknown keyword failed: %v", err)
}
@@ -169,7 +169,7 @@ func TestChatServiceListChatsKeywordFiltersCorrectly(t *testing.T) {
t.Fatalf("expected 0 chats for unknown keyword, got %d", len(unknownResult.Chats))
}
- partialResult, err := svc.ListChats(ctx, "user-1", "1", "list_keyword", 0, 0, []dao.OrderTerm{{Column: "create_time", Desc: true}}, nil)
+ partialResult, err := svc.ListChats(ctx, "user-1", "1", "list_keyword", "", "", 0, 0, []dao.OrderTerm{{Column: "create_time", Desc: true}}, nil)
if err != nil {
t.Fatalf("ListChats partial keyword failed: %v", err)
}
@@ -187,7 +187,7 @@ func TestChatServiceListChatsPagination(t *testing.T) {
svc := NewChatService()
ctx := t.Context()
- page1, err := svc.ListChats(ctx, "user-1", "1", "", 1, 2, []dao.OrderTerm{{Column: "create_time", Desc: true}}, nil)
+ page1, err := svc.ListChats(ctx, "user-1", "1", "", "", "", 1, 2, []dao.OrderTerm{{Column: "create_time", Desc: true}}, nil)
if err != nil {
t.Fatalf("ListChats page 1 failed: %v", err)
}
@@ -198,7 +198,7 @@ func TestChatServiceListChatsPagination(t *testing.T) {
t.Fatalf("expected total=5, got %d", page1.Total)
}
- page3, err := svc.ListChats(ctx, "user-1", "1", "", 3, 2, []dao.OrderTerm{{Column: "create_time", Desc: true}}, nil)
+ page3, err := svc.ListChats(ctx, "user-1", "1", "", "", "", 3, 2, []dao.OrderTerm{{Column: "create_time", Desc: true}}, nil)
if err != nil {
t.Fatalf("ListChats page 3 failed: %v", err)
}
@@ -217,7 +217,7 @@ func TestChatServiceListChatsExcludesDeletedChats(t *testing.T) {
svc := NewChatService()
ctx := t.Context()
- result, err := svc.ListChats(ctx, "user-1", "1", "", 0, 0, []dao.OrderTerm{{Column: "create_time", Desc: true}}, nil)
+ result, err := svc.ListChats(ctx, "user-1", "1", "", "", "", 0, 0, []dao.OrderTerm{{Column: "create_time", Desc: true}}, nil)
if err != nil {
t.Fatalf("ListChats failed: %v", err)
}
@@ -229,6 +229,40 @@ func TestChatServiceListChatsExcludesDeletedChats(t *testing.T) {
}
}
+func TestChatServiceListChatsExactFilters(t *testing.T) {
+ db := setupChatListTestDB(t)
+ createChatListTestChat(t, db, "chat-1", "user-1", "exact_alpha")
+ createChatListTestChat(t, db, "chat-2", "user-1", "exact_beta")
+
+ svc := NewChatService()
+ ctx := t.Context()
+ terms := []dao.OrderTerm{{Column: "create_time", Desc: true}}
+
+ byID, err := svc.ListChats(ctx, "user-1", "1", "", "chat-2", "", 0, 0, terms, nil)
+ if err != nil {
+ t.Fatalf("ListChats by id failed: %v", err)
+ }
+ if byID.Total != 1 || len(byID.Chats) != 1 || byID.Chats[0].ID != "chat-2" {
+ t.Fatalf("expected only chat-2 for id filter, got total=%d chats=%+v", byID.Total, byID.Chats)
+ }
+
+ byName, err := svc.ListChats(ctx, "user-1", "1", "", "", "exact_alpha", 0, 0, terms, nil)
+ if err != nil {
+ t.Fatalf("ListChats by name failed: %v", err)
+ }
+ if byName.Total != 1 || len(byName.Chats) != 1 || byName.Chats[0].ID != "chat-1" {
+ t.Fatalf("expected only chat-1 for name filter, got total=%d chats=%+v", byName.Total, byName.Chats)
+ }
+
+ withOwners, err := svc.ListChats(ctx, "user-1", "1", "", "chat-2", "", 0, 0, terms, []string{"user-1"})
+ if err != nil {
+ t.Fatalf("ListChats by id with owner_ids failed: %v", err)
+ }
+ if withOwners.Total != 1 || len(withOwners.Chats) != 1 || withOwners.Chats[0].ID != "chat-2" {
+ t.Fatalf("expected only chat-2 for id filter with owner_ids, got total=%d chats=%+v", withOwners.Total, withOwners.Chats)
+ }
+}
+
// TestChatServiceListChatsPaginatesOwnerBranch covers the owner_ids branch end
// to end: pagination happens in SQL now, so each page must carry only its own
// rows while total still reports every matching chat.
@@ -267,7 +301,7 @@ func TestChatServiceListChatsPaginatesOwnerBranch(t *testing.T) {
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
- result, err := NewChatService().ListChats(t.Context(), "user-1", "1", "", tt.page, tt.pageSize, []dao.OrderTerm{{Column: "create_time", Desc: true}}, []string{"user-1"})
+ result, err := NewChatService().ListChats(t.Context(), "user-1", "1", "", "", "", tt.page, tt.pageSize, []dao.OrderTerm{{Column: "create_time", Desc: true}}, []string{"user-1"})
if err != nil {
t.Fatalf("ListChats failed: %v", err)
}
diff --git a/test/testcases/restful_api/test_chats.py b/test/testcases/restful_api/test_chats.py
index 47cf7a1731..d0ac9314cc 100644
--- a/test/testcases/restful_api/test_chats.py
+++ b/test/testcases/restful_api/test_chats.py
@@ -88,6 +88,14 @@ def test_chat_crud_cycle(rest_client, clear_chats):
assert create_payload["code"] == 0, create_payload
chat_id = create_payload["data"]["id"]
+ # A second chat in the same tenant, so the exact id lookup below only
+ # passes when the filter is applied.
+ other_res = rest_client.post("/chats", json={"name": "restful_chat_crud_other", "dataset_ids": []})
+ assert other_res.status_code == 200
+ other_payload = other_res.json()
+ assert other_payload["code"] == 0, other_payload
+ assert other_payload["data"]["id"] != chat_id, other_payload
+
list_res = rest_client.get("/chats", params={"id": chat_id})
assert list_res.status_code == 200
list_payload = list_res.json()
@@ -95,6 +103,14 @@ def test_chat_crud_cycle(rest_client, clear_chats):
assert len(list_payload["data"]["chats"]) == 1, list_payload
assert list_payload["data"]["chats"][0]["id"] == chat_id, list_payload
+ # Exact filters take precedence over keywords, so the id wins even when the keyword names the other chat.
+ precedence_res = rest_client.get("/chats", params={"id": chat_id, "keywords": "restful_chat_crud_other"})
+ assert precedence_res.status_code == 200
+ precedence_payload = precedence_res.json()
+ assert precedence_payload["code"] == 0, precedence_payload
+ assert len(precedence_payload["data"]["chats"]) == 1, precedence_payload
+ assert precedence_payload["data"]["chats"][0]["id"] == chat_id, precedence_payload
+
get_res = rest_client.get(f"/chats/{chat_id}")
assert get_res.status_code == 200
get_payload = get_res.json()