RAGFlow is an agent-native database: a Retrieval-Augmented Generation (RAG) engine that grew into context infrastructure.
Go agent-harnessagent-native-databaseagentic-aiagentic-retrievalagentic-searchaiai-agentscontext-enginecontext-engineeringcontext-managementharness-engineeringknowledge-compilationragretrieval-augmented-generationretrieval-harnesssearch-harness
fix(wiki): version history always empty on Go API due to page-slug key mismatch (#19305)
euvreb19a10fb70c6
diff --git a/internal/dao/file_commit.go b/internal/dao/file_commit.goindex 62fc6e15c9..4ebf3276ae 100644--- a/internal/dao/file_commit.go+++ b/internal/dao/file_commit.go@@ -181,7 +181,7 @@ func (dao *FileCommitItemDAO) ListByCommitID(ctx context.Context, db *gorm.DB, c// ListByFileID lists all commit items for a specific file (for version history)func (dao *FileCommitItemDAO) ListByFileID(ctx context.Context, db *gorm.DB, fileID string) ([]*entity.FileCommitItem, error) {var items []*entity.FileCommitItem- err := db.WithContext(ctx).Where("file_id = ?", fileID).Order("create_time DESC").Find(&items).Error+ err := db.WithContext(ctx).Where("file_id = ?", fileID).Order("create_time DESC, seq DESC").Find(&items).Errorreturn items, err}diff --git a/internal/dao/user.go b/internal/dao/user.goindex 7e9b647503..c87bf95635 100644--- a/internal/dao/user.go+++ b/internal/dao/user.go@@ -66,6 +66,31 @@ func (dao *UserDAO) GetNicknameByID(ctx context.Context, db *gorm.DB, id string)return nickname, err}+// GetNicknamesByIDs resolves nicknames for many users in one batched+// lookup, keyed by user id; ids without a matching user row are absent.+func (dao *UserDAO) GetNicknamesByIDs(ctx context.Context, db *gorm.DB, ids []string) (map[string]string, error) {+ nicknames := make(map[string]string, len(ids))+ if len(ids) == 0 {+ return nicknames, nil+ }+ var rows []struct {+ ID string+ Nickname string+ }+ err := db.WithContext(ctx).+ Model(&entity.User{}).+ Select("id, nickname").+ Where("id IN ?", ids).+ Find(&rows).Error+ if err != nil {+ return nil, err+ }+ for _, r := range rows {+ nicknames[r.ID] = r.Nickname+ }+ return nicknames, nil+}+// GetByEmail get user by emailfunc (dao *UserDAO) GetByEmail(ctx context.Context, db *gorm.DB, email string) (*entity.User, error) {var user entity.Userdiff --git a/internal/entity/file_commit.go b/internal/entity/file_commit.goindex a2a7c1bd91..585ce50ab7 100644--- a/internal/entity/file_commit.go+++ b/internal/entity/file_commit.go@@ -16,6 +16,8 @@package entity+import "time"+// FileCommit represents a snapshot commit for a workspace folder (like git commit).type FileCommit struct {ID string `gorm:"column:id;primaryKey;size:32" json:"id"`@@ -115,3 +117,16 @@ type VersionEntry struct {CreateTime *int64 `json:"create_time,omitempty"`Message string `json:"message"`}++// WikiPageCommit is one artifact-page history entry served by+// /datasets/{dataset_id}/commits?slug=<page_type>/<slug>. It mirrors the+// Python list_page_commits row shape consumed by the wiki version-history UI.+type WikiPageCommit struct {+ ID string `json:"id"`+ Title string `json:"title"`+ Comments string `json:"comments"`+ UserID string `json:"user_id"`+ CreateTime *int64 `json:"create_time,omitempty"`+ CreateDate *time.Time `json:"create_date,omitempty"`+ UserNickname string `json:"user_nickname"`+}diff --git a/internal/handler/dataset_artifact.go b/internal/handler/dataset_artifact.goindex c4b2064ab9..125a50bb80 100644--- a/internal/handler/dataset_artifact.go+++ b/internal/handler/dataset_artifact.go@@ -140,6 +140,7 @@ func (h *DatasetArtifactHandler) UpdateArtifact(c *gin.Context) {var req struct {ContentMd string `json:"content_md"`Title string `json:"title"`+ Comments string `json:"comments"`Outlinks []string `json:"outlinks"`}if err := c.ShouldBindJSON(&req); err != nil {@@ -187,6 +188,7 @@ func (h *DatasetArtifactHandler) UpdateArtifact(c *gin.Context) {Slug: slug,PageType: pageType,Title: title,+ Comments: req.Comments,AuthorID: user.ID,OldContent: oldContent,NewContent: req.ContentMd,diff --git a/internal/handler/file_commit.go b/internal/handler/file_commit.goindex 447de804fd..9249b4a62e 100644--- a/internal/handler/file_commit.go+++ b/internal/handler/file_commit.go@@ -24,6 +24,7 @@ import ("ragflow/internal/entity""ragflow/internal/service""strconv"+ "strings""github.com/gin-gonic/gin")@@ -39,7 +40,7 @@ type fileCommitService interface {GetCommitTree(ctx context.Context, commitID string) (map[string]interface{}, error)GetCommitFileContent(ctx context.Context, folderID, commitID, fileID string) ([]byte, error)GetFileVersionHistory(ctx context.Context, fileID string) ([]entity.VersionEntry, error)- ListPageCommits(ctx context.Context, datasetID, pageType, slug string, page, pageSize int) ([]*entity.FileCommit, int64, error)+ ListPageCommits(ctx context.Context, datasetID, pageType, slug string, page, pageSize int) ([]*entity.WikiPageCommit, int64, error)}// FileCommitHandler file commit handler@@ -257,11 +258,13 @@ func (h *FileCommitHandler) ListCommits(c *gin.Context) {ctx := c.Request.Context()- // Python's list_commits supports ?slug=<page_slug> to filter audit commits- // for a specific wiki/skill page (written by record_page_edit). These page- // commits are scoped to the dataset and page file key, so route them through- // the page-commit path instead of the folder-based ListCommits. This only- // applies to the /datasets/{dataset_id}/commits route.+ // Python's list_commits supports ?slug=<page_type>/<slug> to filter audit+ // commits for a specific wiki/skill page (written by record_page_edit).+ // The slug carries the full "<page_type>/<slug>" form shared with the+ // Python API and the frontend, while RecordPageEdit scopes the stored file+ // key by page type plus the bare slug — split the prefix so both sides+ // agree on the same key. This only applies to the+ // /datasets/{dataset_id}/commits route.if slug := c.Query("slug"); slug != "" {datasetID := c.Param("dataset_id")if datasetID == "" {@@ -269,32 +272,23 @@ func (h *FileCommitHandler) ListCommits(c *gin.Context) {return}pageType := c.Query("page_type")+ if prefix := pageType + "/"; pageType != "" && strings.HasPrefix(slug, prefix) {+ slug = strings.TrimPrefix(slug, prefix)+ } else if pageType == "" {+ if idx := strings.Index(slug, "/"); idx >= 0 {+ pageType, slug = slug[:idx], slug[idx+1:]+ }+ }commits, total, err := h.commitService.ListPageCommits(ctx, datasetID, pageType, slug, page, pageSize)if err != nil {jsonInternalError(c, err)return}- var commitList []entity.CommitResponse- for _, commit := range commits {- var ct int64- if commit.CreateTime != nil {- ct = *commit.CreateTime- }- commitList = append(commitList, entity.CommitResponse{- ID: commit.ID,- FolderID: commit.FolderID,- ParentID: commit.ParentID,- Message: commit.Message,- AuthorID: commit.AuthorID,- FileCount: commit.FileCount,- CreateTime: &ct,- })- }common.SuccessWithData(c, gin.H{"total": total,"page": page,"page_size": pageSize,- "commits": commitList,+ "commits": commits,}, common.CodeSuccess.Message())return}diff --git a/internal/handler/file_commit_test.go b/internal/handler/file_commit_test.goindex 4230c156fe..6de965c252 100644--- a/internal/handler/file_commit_test.go+++ b/internal/handler/file_commit_test.go@@ -44,7 +44,7 @@ type mockFileCommitSvc struct {getCommitTreeFn func(ctx context.Context, commitID string) (map[string]interface{}, error)getCommitFileContentFn func(ctx context.Context, folderID, commitID, fileID string) ([]byte, error)getFileVersionHistoryFn func(ctx context.Context, fileID string) ([]entity.VersionEntry, error)- listPageCommitsFn func(ctx context.Context, datasetID, pageType, slug string, page, pageSize int) ([]*entity.FileCommit, int64, error)+ listPageCommitsFn func(ctx context.Context, datasetID, pageType, slug string, page, pageSize int) ([]*entity.WikiPageCommit, int64, error)}func (m *mockFileCommitSvc) CreateCommit(ctx context.Context, folderID, authorID, message string, changes []entity.FileChange) (*entity.FileCommit, error) {@@ -132,11 +132,11 @@ func (m *mockFileCommitSvc) GetFileVersionHistory(ctx context.Context, fileID st}, nil}-func (m *mockFileCommitSvc) ListPageCommits(ctx context.Context, datasetID, pageType, slug string, page, pageSize int) ([]*entity.FileCommit, int64, error) {+func (m *mockFileCommitSvc) ListPageCommits(ctx context.Context, datasetID, pageType, slug string, page, pageSize int) ([]*entity.WikiPageCommit, int64, error) {if m.listPageCommitsFn != nil {return m.listPageCommitsFn(ctx, datasetID, pageType, slug, page, pageSize)}- return []*entity.FileCommit{}, 0, nil+ return []*entity.WikiPageCommit{}, 0, nil}func setupFileCommitTest(userID string) (*gin.Engine, *mockFileCommitSvc) {@@ -158,9 +158,19 @@ func setupFileCommitTestWithHandler(userID string) (*gin.Engine, *mockFileCommitdao.DB = db// Seed the workspace folder and file the tests reference, owned by the// calling user so the tenant authorization passes for them and fails for- // anyone else.- db.Create(&entity.File{ID: "folder-1", TenantID: userID, Name: "workspace", Type: "folder"})- db.Create(&entity.File{ID: "f1", TenantID: userID, Name: "test.txt", Type: "file"})+ // anyone else. Panic on seed failures so a broken fixture reports its+ // real cause instead of surfacing as a spurious CodeNotFound.+ seed := func(f *entity.File) {+ if err := db.Create(f).Error; err != nil {+ panic(err)+ }+ }+ seed(&entity.File{ID: "folder-1", TenantID: userID, Name: "workspace", Type: "folder"})+ seed(&entity.File{ID: "f1", TenantID: userID, Name: "test.txt", Type: "file"})+ // The mirrored /datasets/{dataset_id}/commits test route maps dataset_id+ // straight onto folder_id, so seed kb-1 as a folder the user owns to pass+ // the folder authorization main added.+ seed(&entity.File{ID: "kb-1", TenantID: userID, Name: "kb-1", Type: "folder"})gin.SetMode(gin.TestMode)r := fileCommitRouter(h, userID)@@ -181,6 +191,12 @@ func fileCommitRouter(h *FileCommitHandler, userID string) *gin.Engine {r.GET("/api/v1/folders/:folder_id/commits/:commit_id/tree", h.GetCommitTree)r.GET("/api/v1/folders/:folder_id/commits/:commit_id/files/:file_id/content", h.GetCommitFileContent)r.GET("/api/v1/files/:id/versions", h.GetFileVersionHistory)+ // Mirrors the CommitFolderResolver middleware used on the production+ // /datasets/{dataset_id}/commits route: dataset_id resolves to folder_id.+ r.GET("/api/v1/datasets/:dataset_id/commits", func(c *gin.Context) {+ c.Params = append(c.Params, gin.Param{Key: "folder_id", Value: c.Param("dataset_id")})+ c.Next()+ }, h.ListCommits)return r}@@ -309,6 +325,134 @@ func TestFileCommit_ListCommits_Success(t *testing.T) {}}+func TestFileCommit_ListCommits_PageSlugFilter(t *testing.T) {+ r, mock := setupFileCommitTest("user-1")+ var gotPageType, gotSlug string+ mock.listPageCommitsFn = func(ctx context.Context, datasetID, pageType, slug string, page, pageSize int) ([]*entity.WikiPageCommit, int64, error) {+ if datasetID != "kb-1" {+ t.Errorf("expected dataset kb-1, got %s", datasetID)+ }+ gotPageType, gotSlug = pageType, slug+ return []*entity.WikiPageCommit{+ {ID: "c2", Title: "second edit", UserID: "user-1", UserNickname: "Tester"},+ {ID: "c1", Title: "first edit", UserID: "user-1", UserNickname: "Tester"},+ }, 2, nil+ }++ // The frontend sends the full "<page_type>/<slug>" form, exactly like the+ // Python API contract (?slug=<page_type>/<name>).+ w := httptest.NewRecorder()+ req, _ := http.NewRequest("GET", "/api/v1/datasets/kb-1/commits?slug=topic%2Ffireworks+display", nil)+ r.ServeHTTP(w, req)++ if w.Code != http.StatusOK {+ t.Fatalf("expected 200, got %d: %s", w.Code, w.Body.String())+ }+ if gotPageType != "topic" {+ t.Errorf("expected page type topic, got %q", gotPageType)+ }+ if gotSlug != "fireworks display" {+ t.Errorf("expected bare slug \"fireworks display\", got %q", gotSlug)+ }+ var resp struct {+ Code int `json:"code"`+ Data struct {+ Total int `json:"total"`+ Commits []struct {+ ID string `json:"id"`+ Title string `json:"title"`+ UserID string `json:"user_id"`+ UserNickname string `json:"user_nickname"`+ } `json:"commits"`+ } `json:"data"`+ }+ if err := json.Unmarshal(w.Body.Bytes(), &resp); err != nil {+ t.Fatalf("unmarshal response: %v", err)+ }+ if resp.Data.Total != 2 || len(resp.Data.Commits) != 2 {+ t.Fatalf("expected 2 commits, got total=%d len=%d", resp.Data.Total, len(resp.Data.Commits))+ }+ if resp.Data.Commits[0].Title != "second edit" || resp.Data.Commits[0].UserNickname != "Tester" {+ t.Errorf("unexpected first commit: %+v", resp.Data.Commits[0])+ }+}++func TestFileCommit_ListCommits_PageSlugWithExplicitPageType(t *testing.T) {+ r, mock := setupFileCommitTest("user-1")+ var gotPageType, gotSlug string+ mock.listPageCommitsFn = func(ctx context.Context, datasetID, pageType, slug string, page, pageSize int) ([]*entity.WikiPageCommit, int64, error) {+ gotPageType, gotSlug = pageType, slug+ return []*entity.WikiPageCommit{}, 0, nil+ }++ // Explicit page_type plus a bare slug must also work.+ w := httptest.NewRecorder()+ req, _ := http.NewRequest("GET", "/api/v1/datasets/kb-1/commits?page_type=topic&slug=fireworks+display", nil)+ r.ServeHTTP(w, req)++ if w.Code != http.StatusOK {+ t.Fatalf("expected 200, got %d: %s", w.Code, w.Body.String())+ }+ if gotPageType != "topic" || gotSlug != "fireworks display" {+ t.Errorf("expected topic / fireworks display, got %q / %q", gotPageType, gotSlug)+ }+}++func TestFileCommit_ListCommits_PageSlugNestedTopicPath(t *testing.T) {+ r, mock := setupFileCommitTest("user-1")+ var gotPageType, gotSlug string+ mock.listPageCommitsFn = func(ctx context.Context, datasetID, pageType, slug string, page, pageSize int) ([]*entity.WikiPageCommit, int64, error) {+ gotPageType, gotSlug = pageType, slug+ return []*entity.WikiPageCommit{}, 0, nil+ }++ // Nested page paths (PUT /artifacts/topic/People/Writers) arrive as+ // ?slug=topic/People/Writers: only the first segment is the page type and+ // the remainder stays part of the slug, mirroring UpdateArtifact's split+ // when it derives the page file key on the write side.+ w := httptest.NewRecorder()+ req, _ := http.NewRequest("GET", "/api/v1/datasets/kb-1/commits?slug=topic%2FPeople%2FWriters", nil)+ r.ServeHTTP(w, req)++ if w.Code != http.StatusOK {+ t.Fatalf("expected 200, got %d: %s", w.Code, w.Body.String())+ }+ if gotPageType != "topic" || gotSlug != "People/Writers" {+ t.Errorf("expected topic / People/Writers, got %q / %q", gotPageType, gotSlug)+ }++ // With an explicit page_type the matching prefix is trimmed once and the+ // nested remainder is preserved verbatim.+ gotPageType, gotSlug = "", ""+ w = httptest.NewRecorder()+ req, _ = http.NewRequest("GET", "/api/v1/datasets/kb-1/commits?page_type=topic&slug=topic%2FPeople%2FWriters", nil)+ r.ServeHTTP(w, req)++ if w.Code != http.StatusOK {+ t.Fatalf("expected 200, got %d: %s", w.Code, w.Body.String())+ }+ if gotPageType != "topic" || gotSlug != "People/Writers" {+ t.Errorf("expected topic / People/Writers, got %q / %q", gotPageType, gotSlug)+ }+}++func TestFileCommit_ListCommits_PageSlugWithoutDatasetScope(t *testing.T) {+ r, _ := setupFileCommitTest("user-1")++ // ?slug= scopes the history to a dataset's page key; on a folder route+ // there is no dataset scope to resolve it against.+ w := httptest.NewRecorder()+ req, _ := http.NewRequest("GET", "/api/v1/folders/folder-1/commits?slug=topic%2Fname", nil)+ r.ServeHTTP(w, req)++ if w.Code != http.StatusOK {+ t.Fatalf("expected 200, got %d: %s", w.Code, w.Body.String())+ }+ if code := decodeCode(t, w); code != float64(common.CodeArgumentError) {+ t.Errorf("expected code %d, got %v", common.CodeArgumentError, code)+ }+}+func TestFileCommit_GetCommit_Success(t *testing.T) {r, _ := setupFileCommitTest("user-1")diff --git a/internal/service/file/file_commit.go b/internal/service/file/file_commit.goindex 09096b0cb6..180cb70958 100644--- a/internal/service/file/file_commit.go+++ b/internal/service/file/file_commit.go@@ -244,6 +244,7 @@ type PageEditCommitInput struct {Slug stringPageType stringTitle string+ Comments string // version note typed by the user in the commit dialogAuthorID stringOldContent stringNewContent string@@ -315,6 +316,7 @@ func (s *FileCommitService) RecordPageEdit(ctx context.Context, in PageEditCommiMessage: in.Title,AuthorID: in.AuthorID,Title: &in.Title,+ Comments: &in.Comments,FileCount: 1,}if parentID != "" {@@ -346,8 +348,10 @@ func pageCommitLock(fileID string) *sync.Mutex {return v.(*sync.Mutex)}-// ListPageCommits lists audit commits for a specific wiki/skill page.-func (s *FileCommitService) ListPageCommits(ctx context.Context, datasetID, pageType, slug string, page, pageSize int) ([]*entity.FileCommit, int64, error) {+// ListPageCommits lists audit commits for a specific wiki/skill page and+// returns them in the row shape the wiki version-history UI consumes+// (Python list_page_commits parity), including author nicknames.+func (s *FileCommitService) ListPageCommits(ctx context.Context, datasetID, pageType, slug string, page, pageSize int) ([]*entity.WikiPageCommit, int64, error) {items, err := s.commitItemDAO.ListByFileID(ctx, dao.DB, wikiFileID(datasetID, pageType, slug))if err != nil {return nil, 0, err@@ -357,14 +361,54 @@ func (s *FileCommitService) ListPageCommits(ctx context.Context, datasetID, pagecommitIDs = append(commitIDs, it.CommitID)}if len(commitIDs) == 0 {- return []*entity.FileCommit{}, 0, nil+ return []*entity.WikiPageCommit{}, 0, nil}commits, total, err := s.commitDAO.ListByIDs(ctx, dao.DB, commitIDs, page, pageSize)if err != nil {return nil, 0, err}- return commits, total, nil++ // Resolve author nicknames for all distinct authors in one batched+ // lookup (Python list_page_commits parity: a single IN query); a failed+ // lookup degrades to empty nicknames instead of failing the listing.+ authorIDs := make([]string, 0, len(commits))+ seenAuthors := make(map[string]struct{}, len(commits))+ for _, c := range commits {+ if c.AuthorID == "" {+ continue+ }+ if _, ok := seenAuthors[c.AuthorID]; ok {+ continue+ }+ seenAuthors[c.AuthorID] = struct{}{}+ authorIDs = append(authorIDs, c.AuthorID)+ }+ nicknames := make(map[string]string, len(authorIDs))+ if len(authorIDs) > 0 {+ if resolved, uerr := dao.NewUserDAO().GetNicknamesByIDs(ctx, dao.DB, authorIDs); uerr == nil {+ nicknames = resolved+ }+ }++ rows := make([]*entity.WikiPageCommit, 0, len(commits))+ for _, c := range commits {+ row := &entity.WikiPageCommit{+ ID: c.ID,+ UserID: c.AuthorID,+ CreateTime: c.CreateTime,+ CreateDate: c.CreateDate,+ UserNickname: nicknames[c.AuthorID],+ }+ if c.Title != nil {+ row.Title = *c.Title+ }+ if c.Comments != nil {+ row.Comments = *c.Comments+ }+ rows = append(rows, row)+ }+ return rows, total, nil}// unifiedDiff produces a simple line-based unified diff between two texts.diff --git a/internal/service/file/file_commit_page_test.go b/internal/service/file/file_commit_page_test.goindex ac68062463..06bf37f760 100644--- a/internal/service/file/file_commit_page_test.go+++ b/internal/service/file/file_commit_page_test.go@@ -1,6 +1,7 @@package fileimport (+ "context""strconv""strings""sync"@@ -278,3 +279,240 @@ func TestUnifiedDiff_TruncatesLongDiff(t *testing.T) {t.Fatalf("expected long diff to be truncated, got %q", d)}}++func TestListPageCommits_ReturnsRecordedEdits(t *testing.T) {+ db := newPageCommitTestDB(t)+ if err := db.AutoMigrate(&entity.User{}); err != nil {+ t.Fatalf("migrate user: %v", err)+ }+ if err := db.Create(&entity.User{+ ID: "u1",+ Nickname: "Tester",+ Email: "[email protected]",+ IsAuthenticated: "1",+ IsActive: "1",+ IsAnonymous: "0",+ }).Error; err != nil {+ t.Fatalf("seed user: %v", err)+ }+ svc := NewFileCommitService()+ ctx := context.Background()++ base := PageEditCommitInput{+ DatasetID: "kb1",+ DocID: "topic/fireworks display",+ Slug: "fireworks display",+ PageType: "topic",+ AuthorID: "u1",+ OldContent: "one",+ NewContent: "two",+ }+ first := base+ first.Title = "first edit"+ first.Comments = "first note"+ firstCommit, err := svc.RecordPageEdit(ctx, first)+ if err != nil {+ t.Fatalf("first RecordPageEdit: %v", err)+ }+ second := base+ second.Title = "second edit"+ second.Comments = "second note"+ second.OldContent = "two"+ second.NewContent = "three"+ secondCommit, err := svc.RecordPageEdit(ctx, second)+ if err != nil {+ t.Fatalf("second RecordPageEdit: %v", err)+ }++ // Pin both commit items to one timestamp so the newest-first assertions+ // below can only hold through the seq DESC tie-break, mirroring+ // same-millisecond edits in production.+ var firstItem entity.FileCommitItem+ if err := db.Where("commit_id = ?", firstCommit.ID).First(&firstItem).Error; err != nil {+ t.Fatalf("load first commit item: %v", err)+ }+ if firstItem.CreateTime == nil {+ t.Fatal("expected commit item create_time to be set")+ }+ if err := db.Model(&entity.FileCommitItem{}).+ Where("commit_id IN ?", []string{firstCommit.ID, secondCommit.ID}).+ UpdateColumn("create_time", *firstItem.CreateTime).Error; err != nil {+ t.Fatalf("pin equal create_time: %v", err)+ }++ rows, total, err := svc.ListPageCommits(ctx, "kb1", "topic", "fireworks display", 1, 15)+ if err != nil {+ t.Fatalf("ListPageCommits: %v", err)+ }+ if total != 2 || len(rows) != 2 {+ t.Fatalf("expected 2 commits, got total=%d len=%d", total, len(rows))+ }+ if rows[0].ID != secondCommit.ID {+ t.Errorf("expected newest commit %s first, got %s", secondCommit.ID, rows[0].ID)+ }+ if rows[1].ID != firstCommit.ID {+ t.Errorf("expected oldest commit %s second, got %s", firstCommit.ID, rows[1].ID)+ }+ if rows[0].Title != "second edit" || rows[1].Title != "first edit" {+ t.Errorf("unexpected titles: %q / %q", rows[0].Title, rows[1].Title)+ }+ if rows[0].Comments != "second note" {+ t.Errorf("expected commit comments \"second note\", got %q", rows[0].Comments)+ }+ if rows[0].UserID != "u1" || rows[0].UserNickname != "Tester" {+ t.Errorf("expected user u1/Tester, got %q/%q", rows[0].UserID, rows[0].UserNickname)+ }+ if rows[0].CreateTime == nil {+ t.Error("expected create_time to be set")+ }+}++func TestListPageCommits_NestedSlugMatchesRecordPageEditKey(t *testing.T) {+ db := newPageCommitTestDB(t)+ if err := db.AutoMigrate(&entity.User{}); err != nil {+ t.Fatalf("migrate user: %v", err)+ }+ if err := db.Create(&entity.User{+ ID: "u1",+ Nickname: "Tester",+ Email: "[email protected]",+ IsAuthenticated: "1",+ IsActive: "1",+ IsAnonymous: "0",+ }).Error; err != nil {+ t.Fatalf("seed user: %v", err)+ }+ svc := NewFileCommitService()+ ctx := context.Background()++ // UpdateArtifact routes PUT /artifacts/topic/People/Writers with+ // pageType="topic" and the full nested tail as the slug.+ nested := PageEditCommitInput{+ DatasetID: "kb1",+ DocID: "topic/People/Writers",+ Slug: "People/Writers",+ PageType: "topic",+ AuthorID: "u1",+ OldContent: "one",+ NewContent: "two",+ }+ first := nested+ first.Title = "nested first"+ firstCommit, err := svc.RecordPageEdit(ctx, first)+ if err != nil {+ t.Fatalf("first RecordPageEdit: %v", err)+ }+ second := nested+ second.Title = "nested second"+ second.OldContent = "two"+ second.NewContent = "three"+ secondCommit, err := svc.RecordPageEdit(ctx, second)+ if err != nil {+ t.Fatalf("second RecordPageEdit: %v", err)+ }+ if secondCommit.ParentID == nil || *secondCommit.ParentID != firstCommit.ID {+ t.Fatalf("expected nested page edits to chain via the same file key, got parent %v", secondCommit.ParentID)+ }++ // The write side must scope the page file key exactly as the read side+ // recomputes it after the handler's first-segment split.+ var items []entity.FileCommitItem+ if err := dao.DB.Where("commit_id = ?", secondCommit.ID).Find(&items).Error; err != nil {+ t.Fatalf("load nested items: %v", err)+ }+ if len(items) != 1 || items[0].FileID != "kb1/topic/People/Writers" {+ t.Fatalf("expected file_id kb1/topic/People/Writers, got %+v", items)+ }++ // A page that only shares the first nested segment has its own history.+ sibling := nested+ sibling.DocID = "topic/People/Editors"+ sibling.Slug = "People/Editors"+ sibling.Title = "sibling page"+ siblingCommit, err := svc.RecordPageEdit(ctx, sibling)+ if err != nil {+ t.Fatalf("sibling RecordPageEdit: %v", err)+ }++ rows, total, err := svc.ListPageCommits(ctx, "kb1", "topic", "People/Writers", 1, 15)+ if err != nil {+ t.Fatalf("ListPageCommits: %v", err)+ }+ if total != 2 || len(rows) != 2 {+ t.Fatalf("expected 2 commits, got total=%d len=%d", total, len(rows))+ }+ if rows[0].ID != secondCommit.ID || rows[1].ID != firstCommit.ID {+ t.Errorf("expected newest-first %s, %s; got %s, %s", secondCommit.ID, firstCommit.ID, rows[0].ID, rows[1].ID)+ }+ for _, row := range rows {+ if row.ID == siblingCommit.ID {+ t.Errorf("sibling page history leaked into nested slug listing: %s", row.ID)+ }+ }+}++func TestListPageCommits_ResolvesNicknamesInSingleBatchedLookup(t *testing.T) {+ db := newPageCommitTestDB(t)+ if err := db.AutoMigrate(&entity.User{}); err != nil {+ t.Fatalf("migrate user: %v", err)+ }+ for _, u := range []entity.User{+ {ID: "u1", Nickname: "Tester", Email: "[email protected]", IsAuthenticated: "1", IsActive: "1", IsAnonymous: "0"},+ {ID: "u2", Nickname: "Reviewer", Email: "[email protected]", IsAuthenticated: "1", IsActive: "1", IsAnonymous: "0"},+ } {+ if err := db.Create(&u).Error; err != nil {+ t.Fatalf("seed user %s: %v", u.ID, err)+ }+ }++ var queries []string+ if err := db.Callback().Query().After("gorm:query").Register("count_user_lookups", func(tx *gorm.DB) {+ queries = append(queries, tx.Statement.SQL.String())+ }); err != nil {+ t.Fatalf("register query callback: %v", err)+ }++ svc := NewFileCommitService()+ ctx := context.Background()+ base := PageEditCommitInput{+ DatasetID: "kb1",+ DocID: "topic/fireworks display",+ Slug: "fireworks display",+ PageType: "topic",+ OldContent: "one",+ }+ for i, author := range []string{"u1", "u2", "u3"} {+ in := base+ in.AuthorID = author+ in.NewContent = strconv.Itoa(i + 2)+ if _, err := svc.RecordPageEdit(ctx, in); err != nil {+ t.Fatalf("RecordPageEdit by %s: %v", author, err)+ }+ }++ queries = nil+ rows, total, err := svc.ListPageCommits(ctx, "kb1", "topic", "fireworks display", 1, 15)+ if err != nil {+ t.Fatalf("ListPageCommits: %v", err)+ }+ if total != 3 || len(rows) != 3 {+ t.Fatalf("expected 3 commits, got total=%d len=%d", total, len(rows))+ }+ // Three distinct authors must be resolved by exactly one query against+ // the user table (u3 has no user row and degrades to an empty nickname).+ userQueries := 0+ for _, q := range queries {+ if strings.Contains(q, "FROM `user`") {+ userQueries+++ }+ }+ if userQueries != 1 {+ t.Errorf("expected exactly 1 batched user lookup for 3 distinct authors, got %d (queries: %v)", userQueries, queries)+ }+ wantNicknames := map[string]string{"u1": "Tester", "u2": "Reviewer", "u3": ""}+ for _, row := range rows {+ if row.UserNickname != wantNicknames[row.UserID] {+ t.Errorf("author %s: expected nickname %q, got %q", row.UserID, wantNicknames[row.UserID], row.UserNickname)+ }+ }+}