WeKnora/internal/handler/knowledge_images_test.go

138 lines
3.7 KiB
Go
Raw Normal View History

feat(gallery): filter images by source document (#4159) * feat(gallery): filter images by source document Add a gallery toolbar button that opens a paginated, keyword-searchable document picker; confirming restricts the listing to images owned by the selected documents. The backend gallery endpoint accepts a knowledge_ids query param (capped at 50) narrowing chunk_images by the owning document before de-duplication, so the count query stays index served. * feat(gallery): lift knowledge_ids cap via POST body, sortable doc picker Add POST /knowledge-bases/:id/images accepting the gallery filter as a JSON body so knowledge_ids escapes the URL-length cap (50 -> 1000, an abuse guard rather than a transport limit); the GET variant keeps its cap and both share the contract-constrain logic. The source picker gains sortable column headers (file name / upload time, newest first by default), a header select-all that unions and removes whole hit lists across keyword searches, overflow guards capping the no-keyword view at the 500 most recent documents, and a wider dialog. * style(gallery): replace td-token fallbacks and font-size literals with design tokens styleGuard.test.mjs enforces ratchets: --td-* vars must not carry fallbacks (theme.css guarantees them) and font sizes must use --app-text-* tokens. GallerySourcePicker.vue added 4 of each, pushing the ratchets over baseline. * fix(gallery): keep shared images in source filter and align picker UI - Scope the de-duplication probe to the selected documents, so an image whose newer copy lives in an unselected document is no longer hidden. - Reset the source filter when the gallery switches knowledge bases. - Accept an empty POST /images body; drop pruned attribute maps to nil. - Keep the source filter out of the filter panel's count and clear action; the empty state's clear still resets it. - Rework the picker dialog to the BatchTagDialog shell: heading with subtitle, footer with selection count, clickable rows, debounced search, select-all toggling against every hit, stale select-all responses dropped. - Remove the unreachable GET knowledge_ids branch in the API client. --------- Co-authored-by: tayadwx <tayadwx@users.noreply.github.com> Co-authored-by: wizardchen <wizardchen@tencent.com>
2026-10-12 07:43:28 +00:00
package handler
import (
"context"
"encoding/json"
"fmt"
"net/http"
"net/http/httptest"
"strings"
"testing"
"github.com/gin-gonic/gin"
"github.com/Tencent/WeKnora/internal/middleware"
"github.com/Tencent/WeKnora/internal/types"
"github.com/Tencent/WeKnora/internal/types/interfaces"
)
// stubGalleryChunkService records the knowledge ids one images-listing call
// received, so tests can assert how the GET cap and the POST body cap differ.
type stubGalleryChunkService struct {
interfaces.ChunkService
gotIDs []string
}
func (s *stubGalleryChunkService) ListImagesByKnowledgeBaseID(
_ context.Context,
_ string,
page *types.Pagination,
filter *types.ImageListFilter,
) (*types.PageResult, error) {
s.gotIDs = filter.KnowledgeIDs
return types.NewPageResult(0, page, []types.ImageAssetRow{}), nil
}
func newImagesRouter(chunks interfaces.ChunkService) *gin.Engine {
gin.SetMode(gin.TestMode)
r := gin.New()
r.Use(middleware.ErrorHandler())
r.Use(func(c *gin.Context) {
c.Set(types.TenantIDContextKey.String(), uint64(1))
c.Set(types.UserIDContextKey.String(), "u-test")
c.Next()
})
h := &KnowledgeHandler{kbService: &stubFolderKBService{}, chunkService: chunks}
r.GET("/knowledge-bases/:id/images", h.ListImages)
r.POST("/knowledge-bases/:id/images", h.ListImagesPost)
return r
}
// commaIDs builds "id-0,id-1,..." of the requested size.
func commaIDs(n int) []string {
ids := make([]string, n)
for i := range ids {
ids[i] = fmt.Sprintf("0198c0de-0000-7000-8000-%012d", i)
}
return ids
}
func TestListImagesPost_KnowledgeIDBody(t *testing.T) {
tests := []struct {
name string
ids int
wantCap int
wantHTT int
}{
{
name: "60 ids pass the POST body although the GET cap is 50",
ids: 60,
wantCap: 60,
wantHTT: http.StatusOK,
},
{
name: "the body cap still guards abuse",
ids: maxKnowledgeIDFilterBody + 1,
wantCap: 0,
wantHTT: http.StatusBadRequest,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
svc := &stubGalleryChunkService{}
router := newImagesRouter(svc)
ids := commaIDs(tt.ids)
payload, _ := json.Marshal(map[string]any{"knowledge_ids": ids})
req := httptest.NewRequest(http.MethodPost, "/knowledge-bases/kb-1/images",
strings.NewReader(string(payload)))
req.Header.Set("Content-Type", "application/json")
w := httptest.NewRecorder()
router.ServeHTTP(w, req)
if w.Code != tt.wantHTT {
t.Fatalf("status = %d, want %d; body=%s", w.Code, tt.wantHTT, w.Body.String())
}
if len(svc.gotIDs) != tt.wantCap {
t.Fatalf("got %d knowledge ids, want %d", len(svc.gotIDs), tt.wantCap)
}
})
}
}
func TestListImagesPost_EmptyBody(t *testing.T) {
svc := &stubGalleryChunkService{}
router := newImagesRouter(svc)
req := httptest.NewRequest(http.MethodPost, "/knowledge-bases/kb-1/images", nil)
req.Header.Set("Content-Type", "application/json")
w := httptest.NewRecorder()
router.ServeHTTP(w, req)
if w.Code != http.StatusOK {
t.Fatalf("status = %d, want 200; body=%s", w.Code, w.Body.String())
}
if len(svc.gotIDs) != 0 {
t.Fatalf("got %d knowledge ids, want none", len(svc.gotIDs))
}
}
func TestListImagesGet_KnowledgeIDCap(t *testing.T) {
svc := &stubGalleryChunkService{}
router := newImagesRouter(svc)
// 60 ids on the URL: the GET cap of 50 truncates them.
url := "/knowledge-bases/kb-1/images?knowledge_ids=" + strings.Join(commaIDs(60), ",")
req := httptest.NewRequest(http.MethodGet, url, nil)
w := httptest.NewRecorder()
router.ServeHTTP(w, req)
if w.Code != http.StatusOK {
t.Fatalf("status = %d, want 200; body=%s", w.Code, w.Body.String())
}
if len(svc.gotIDs) != maxKnowledgeIDFilter {
t.Fatalf("got %d knowledge ids, want the GET cap %d", len(svc.gotIDs), maxKnowledgeIDFilter)
}
}