From 98362dd29698f4b78df5d8ecf3f5020517e50ddc Mon Sep 17 00:00:00 2001 From: tayadwx <42323260+tayadwx@users.noreply.github.com> Date: Mon, 12 Oct 2026 15:43:28 +0800 Subject: [PATCH] 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 Co-authored-by: wizardchen --- frontend/src/api/image-gallery/index.ts | 39 +- frontend/src/i18n/locales/en-US.ts | 13 + frontend/src/i18n/locales/ja-JP.ts | 13 + frontend/src/i18n/locales/ko-KR.ts | 13 + frontend/src/i18n/locales/ru-RU.ts | 13 + frontend/src/i18n/locales/zh-CN.ts | 13 + frontend/src/i18n/locales/zh-TW.ts | 13 + .../knowledge/gallery/GallerySourcePicker.vue | 599 ++++++++++++++++++ .../views/knowledge/gallery/ImageGallery.vue | 41 +- .../repository/chunk_image_assets.go | 20 +- .../repository/chunk_image_assets_test.go | 69 ++ internal/application/service/gallery_attrs.go | 3 + internal/handler/knowledge.go | 232 +++++-- internal/handler/knowledge_images_test.go | 137 ++++ internal/router/routes_knowledge.go | 4 + internal/types/image_gallery.go | 15 +- 16 files changed, 1178 insertions(+), 59 deletions(-) create mode 100644 frontend/src/views/knowledge/gallery/GallerySourcePicker.vue create mode 100644 internal/handler/knowledge_images_test.go diff --git a/frontend/src/api/image-gallery/index.ts b/frontend/src/api/image-gallery/index.ts index a7c0fc6f..9d31edbc 100644 --- a/frontend/src/api/image-gallery/index.ts +++ b/frontend/src/api/image-gallery/index.ts @@ -1,4 +1,4 @@ -import { get } from '@/utils/request'; +import { get, post } from '@/utils/request'; // --------------------------------------------------------------------------- // Image Gallery API @@ -65,6 +65,12 @@ export interface ImageListParams { sortOrder?: ImageSortOrder; /** Restrict to chunks with this enabled state. Omit to include both. */ isEnabled?: boolean; + /** + * Source-document restriction: only images owned by these knowledge items + * are listed. Sent in the POST body when present (the GET query-param + * variant keeps a lower URL-length-driven cap). + */ + knowledgeIds?: string[]; /** * Attribute filters keyed by namespaced attribute id. Values within one * attribute are OR-ed; attributes are AND-ed. Sent as one `attr_filters` @@ -93,11 +99,42 @@ export interface ImageListResult { * List image assets for a knowledge base. Attribute references use the * namespaced ids from the gallery contract; the backend validates them * against the contract and silently drops ineligible ones. + * + * Requests carrying knowledge_ids go through POST /images with the filter as + * a JSON body: URL length limits would otherwise cap the source picker's + * select-all to a handful of documents. */ export async function listGalleryImages( kbId: string, params: ImageListParams = {}, ): Promise { + if (params.knowledgeIds && params.knowledgeIds.length) { + const res = await post<{ + success: boolean; + data: ImageAsset[]; + total: number; + page: number; + page_size: number; + }>(`/api/v1/knowledge-bases/${kbId}/images`, { + keyword: params.keyword, + search_in: params.searchIn, + sort_by: params.sortBy, + sort_order: params.sortOrder, + is_enabled: params.isEnabled, + knowledge_ids: params.knowledgeIds, + attr_filters: params.attrFilters, + attr_rules: params.attrRules, + page: params.page, + page_size: params.pageSize, + }); + return { + items: res.data, + total: res.total, + page: res.page, + pageSize: res.page_size, + }; + } + const query = new URLSearchParams(); if (params.keyword) query.set('keyword', params.keyword); if (params.searchIn && params.searchIn.length) { diff --git a/frontend/src/i18n/locales/en-US.ts b/frontend/src/i18n/locales/en-US.ts index c40fc87f..32c7eeff 100755 --- a/frontend/src/i18n/locales/en-US.ts +++ b/frontend/src/i18n/locales/en-US.ts @@ -3527,6 +3527,19 @@ export default { viewerClose: 'Close (Esc)', prev: 'Previous (←)', next: 'Next (→)', + sourceFilter: 'By document', + sourceFilterTitle: 'Filter by source document', + sourceFilterSearch: 'Search document names', + sourceFilterEmpty: 'No matching documents', + sourceFilterSubtitle: 'The gallery shows only images from the selected documents, so captions and OCR can be checked one by one', + sourceFilterSelected: '{count} documents selected', + sourceFilterClear: 'Clear selection', + sourceFilterTooMany: 'At most 1000 documents can be selected', + sourceFilterColName: 'File name', + sourceFilterColTime: 'Uploaded', + sourceFilterSelectAll: 'Select all / none (across every hit)', + sourceFilterOverflowRecent: 'Many documents: showing only the most recent {cap}. Refine with a keyword.', + sourceFilterOverflowHits: '{total} documents hit; showing the first {cap}. Narrow the keyword before selecting all.', // Display names for the builtin attributes the gallery itself // declares. Attributes contributed by other sources fall back to the // pipeline's own wording (see the imageAttr namespace). diff --git a/frontend/src/i18n/locales/ja-JP.ts b/frontend/src/i18n/locales/ja-JP.ts index c4842a7c..abc559f5 100644 --- a/frontend/src/i18n/locales/ja-JP.ts +++ b/frontend/src/i18n/locales/ja-JP.ts @@ -3527,6 +3527,19 @@ export default { viewerClose: '閉じる (Esc)', prev: '前へ (←)', next: '次へ (→)', + sourceFilter: 'ドキュメントで絞り込み', + sourceFilterTitle: 'ソースドキュメントで絞り込み', + sourceFilterSearch: 'ドキュメント名を検索', + sourceFilterEmpty: '一致するドキュメントがありません', + sourceFilterSubtitle: '選択したドキュメントの画像のみを表示し、キャプションと OCR 結果を一つずつ確認できます', + sourceFilterSelected: '{count} 件のドキュメントを選択中', + sourceFilterClear: '選択をクリア', + sourceFilterTooMany: '選択できるのは最大 1000 件です', + sourceFilterColName: 'ファイル名', + sourceFilterColTime: 'アップロード日時', + sourceFilterSelectAll: 'すべて選択 / 選択解除(全ヒット対象)', + sourceFilterOverflowRecent: 'ドキュメントが多いため、最新 {cap} 件のみ表示しています。キーワードで絞り込んでください', + sourceFilterOverflowHits: '{total} 件がヒットしました。先頭 {cap} 件のみ表示中です。全選択前にキーワードを絞り込んでください', // Display names for the builtin attributes the gallery itself // declares. Attributes contributed by other sources fall back to the // pipeline's own wording (see the imageAttr namespace). diff --git a/frontend/src/i18n/locales/ko-KR.ts b/frontend/src/i18n/locales/ko-KR.ts index ccccf24f..d5b1c49a 100755 --- a/frontend/src/i18n/locales/ko-KR.ts +++ b/frontend/src/i18n/locales/ko-KR.ts @@ -4558,6 +4558,19 @@ export default { viewerClose: '닫기 (Esc)', prev: '이전 (←)', next: '다음 (→)', + sourceFilter: '문서별 필터', + sourceFilterTitle: '원본 문서로 필터', + sourceFilterSearch: '문서 이름 검색', + sourceFilterEmpty: '일치하는 문서가 없습니다', + sourceFilterSubtitle: '선택한 문서의 이미지만 표시하여 캡션과 OCR 결과를 하나씩 확인할 수 있습니다', + sourceFilterSelected: '{count}개 문서 선택됨', + sourceFilterClear: '선택 지우기', + sourceFilterTooMany: '최대 1000개 문서까지 선택할 수 있습니다', + sourceFilterColName: '파일 이름', + sourceFilterColTime: '업로드 시간', + sourceFilterSelectAll: '전체 선택 / 해제 (모든 검색 결과 대상)', + sourceFilterOverflowRecent: '문서가 많아 최근 {cap}개만 표시합니다. 키워드로 좁혀 주세요', + sourceFilterOverflowHits: '{total}개 문서가 일치했습니다. 처음 {cap}개만 표시 중입니다. 전체 선택 전 키워드를 좁혀 주세요', // Display names for the builtin attributes the gallery itself // declares. Attributes contributed by other sources fall back to the // pipeline's own wording (see the imageAttr namespace). diff --git a/frontend/src/i18n/locales/ru-RU.ts b/frontend/src/i18n/locales/ru-RU.ts index dc11022b..7c5ca99d 100755 --- a/frontend/src/i18n/locales/ru-RU.ts +++ b/frontend/src/i18n/locales/ru-RU.ts @@ -4558,6 +4558,19 @@ export default { viewerClose: 'Закрыть (Esc)', prev: 'Назад (←)', next: 'Вперёд (→)', + sourceFilter: 'По документу', + sourceFilterTitle: 'Фильтр по исходному документу', + sourceFilterSearch: 'Поиск по названию документа', + sourceFilterEmpty: 'Подходящих документов нет', + sourceFilterSubtitle: 'Галерея покажет только изображения из выбранных документов, чтобы проверить подписи и OCR по одному', + sourceFilterSelected: 'Выбрано документов: {count}', + sourceFilterClear: 'Сбросить выбор', + sourceFilterTooMany: 'Можно выбрать не более 1000 документов', + sourceFilterColName: 'Имя файла', + sourceFilterColTime: 'Время загрузки', + sourceFilterSelectAll: 'Выбрать все / снять выделение (по всем совпадениям)', + sourceFilterOverflowRecent: 'Документов много: показаны только последние {cap}. Уточните запрос ключевым словом', + sourceFilterOverflowHits: 'Найдено {total} документов; показаны первые {cap}. Сузьте ключевое слово перед выбором всех', // Display names for the builtin attributes the gallery itself // declares. Attributes contributed by other sources fall back to the // pipeline's own wording (see the imageAttr namespace). diff --git a/frontend/src/i18n/locales/zh-CN.ts b/frontend/src/i18n/locales/zh-CN.ts index 6db8910b..dd4f51b2 100755 --- a/frontend/src/i18n/locales/zh-CN.ts +++ b/frontend/src/i18n/locales/zh-CN.ts @@ -4560,6 +4560,19 @@ export default { viewerClose: '关闭 (Esc)', prev: '上一张 (←)', next: '下一张 (→)', + sourceFilter: '按文档', + sourceFilterTitle: '按来源文档筛选', + sourceFilterSearch: '搜索文档名称', + sourceFilterEmpty: '没有匹配的文档', + sourceFilterSubtitle: '画廊仅展示所选文档中的图片,便于逐个核对摘要与 OCR 结果', + sourceFilterSelected: '已选 {count} 个文档', + sourceFilterClear: '清空已选', + sourceFilterTooMany: '最多只能选择 1000 个文档', + sourceFilterColName: '文件名', + sourceFilterColTime: '上传时间', + sourceFilterSelectAll: '全选 / 全不选(含全部命中结果)', + sourceFilterOverflowRecent: '文档较多,仅显示最近 {cap} 条,请输入关键字精确定位', + sourceFilterOverflowHits: '命中 {total} 个文档,仅显示前 {cap} 条,请细化关键字后再全选', // Display names for the builtin attributes the gallery itself // declares. Attributes contributed by other sources fall back to the // pipeline's own wording (see the imageAttr namespace). diff --git a/frontend/src/i18n/locales/zh-TW.ts b/frontend/src/i18n/locales/zh-TW.ts index 1f357776..c36159b4 100644 --- a/frontend/src/i18n/locales/zh-TW.ts +++ b/frontend/src/i18n/locales/zh-TW.ts @@ -4560,6 +4560,19 @@ export default { viewerClose: '關閉 (Esc)', prev: '上一張 (←)', next: '下一張 (→)', + sourceFilter: '按文件', + sourceFilterTitle: '按來源文件篩選', + sourceFilterSearch: '搜尋文件名稱', + sourceFilterEmpty: '沒有符合的文件', + sourceFilterSubtitle: '圖庫僅顯示所選文件中的圖片,方便逐一核對摘要與 OCR 結果', + sourceFilterSelected: '已選 {count} 個文件', + sourceFilterClear: '清空已選', + sourceFilterTooMany: '最多只能選擇 1000 個文件', + sourceFilterColName: '文件名稱', + sourceFilterColTime: '上傳時間', + sourceFilterSelectAll: '全選 / 全不選(含全部命中結果)', + sourceFilterOverflowRecent: '文件較多,僅顯示最近 {cap} 條,請輸入關鍵字精確定位', + sourceFilterOverflowHits: '命中 {total} 個文件,僅顯示前 {cap} 條,請細化關鍵字後再全選', // Display names for the builtin attributes the gallery itself // declares. Attributes contributed by other sources fall back to the // pipeline's own wording (see the imageAttr namespace). diff --git a/frontend/src/views/knowledge/gallery/GallerySourcePicker.vue b/frontend/src/views/knowledge/gallery/GallerySourcePicker.vue new file mode 100644 index 00000000..25125e04 --- /dev/null +++ b/frontend/src/views/knowledge/gallery/GallerySourcePicker.vue @@ -0,0 +1,599 @@ + + + + + + + diff --git a/frontend/src/views/knowledge/gallery/ImageGallery.vue b/frontend/src/views/knowledge/gallery/ImageGallery.vue index e2b4d317..28472d8f 100644 --- a/frontend/src/views/knowledge/gallery/ImageGallery.vue +++ b/frontend/src/views/knowledge/gallery/ImageGallery.vue @@ -13,6 +13,7 @@ import { updateMyPreferences } from '@/api/auth' import EmptyState from '@/components/EmptyState.vue' import { galleryImageRequest } from './galleryImageSrc' import GalleryViewer, { type GalleryAttrRow } from './GalleryViewer.vue' +import GallerySourcePicker from './GallerySourcePicker.vue' const props = defineProps<{ knowledgeBaseId: string @@ -50,6 +51,12 @@ const imageRatios = ref>({}) let cardObserver: ResizeObserver | undefined let scrollObserver: ResizeObserver | undefined +// Source-document restriction (the "filter by document" picker). An empty +// array means every document of the KB; otherwise only images whose owning +// document is listed are fetched. Committed by the picker dialog. +const sourceDocIds = ref([]) +const sourcePickerVisible = ref(false) + // Attribute selections for free-text ("keywords") attributes: namespaced attr // id -> literal values (OR within the attribute, AND across attributes). const attrSelections = ref>({}) @@ -309,7 +316,8 @@ const isNarrowed = computed( () => !!keyword.value.trim() || Object.keys(activeRules.value).length > 0 || - Object.keys(activeSelections.value).length > 0, + Object.keys(activeSelections.value).length > 0 || + sourceDocIds.value.length > 0, ) function verdictOf(attrId: string, value: string): Verdict { @@ -355,12 +363,19 @@ function clearFilters(): void { reload() } -/** The empty state's way back: forget the keyword as well. */ +/** The empty state's way back: forget the keyword and source documents as well. */ function clearAll(): void { keyword.value = '' + sourceDocIds.value = [] clearFilters() } +/** Committed by the source picker: restrict the listing to these documents. */ +function onSourceDocsConfirm(ids: string[]): void { + sourceDocIds.value = ids + reload() +} + // --------------------------------------------------------------------------- // Search scope (mode + per-field toggles, persisted as the user's own record) // @@ -429,6 +444,7 @@ function buildParams(): ImageListParams { sortOrder: sortOrder.value, attrFilters: Object.keys(selections).length ? selections : undefined, attrRules: Object.keys(rules).length ? rules : undefined, + knowledgeIds: sourceDocIds.value.length ? sourceDocIds.value : undefined, pageSize, } } @@ -586,6 +602,8 @@ async function initGallery() { sortBy.value = '' attrSelections.value = {} attrVerdicts.value = {} + sourceDocIds.value = [] + sourcePickerVisible.value = false releaseBlobs() configLoaded.value = false config.value = { attribute_sources: [], attributes: [], mode: 'all', status: {} } @@ -656,6 +674,17 @@ watch( + + + + diff --git a/internal/application/repository/chunk_image_assets.go b/internal/application/repository/chunk_image_assets.go index d4d3d398..4b34b291 100644 --- a/internal/application/repository/chunk_image_assets.go +++ b/internal/application/repository/chunk_image_assets.go @@ -77,6 +77,15 @@ const winnerClause = "NOT EXISTS (SELECT 1 FROM chunk_images o " + "OR (o.updated_at = i.updated_at AND (o.chunk_id < i.chunk_id " + "OR (o.chunk_id = i.chunk_id AND o.image_index < i.image_index)))))" +// scopedWinnerClause is winnerClause restricted to copies inside the listed +// documents: a copy outside them must not hide the image from a document that +// carries it too. +const scopedWinnerClause = "NOT EXISTS (SELECT 1 FROM chunk_images o " + + "WHERE o.knowledge_base_id = i.knowledge_base_id AND o.tenant_id = i.tenant_id " + + "AND o.image_key = i.image_key AND o.knowledge_id IN ? AND (o.updated_at > i.updated_at " + + "OR (o.updated_at = i.updated_at AND (o.chunk_id < i.chunk_id " + + "OR (o.chunk_id = i.chunk_id AND o.image_index < i.image_index)))))" + // imageAssetDialect holds the expressions postgres and sqlite spell // differently: reading the attrs JSON and matching the keyword. type imageAssetDialect struct { @@ -98,6 +107,10 @@ func (d imageAssetDialect) where( clauses = append(clauses, "i.is_enabled = ?") args = append(args, *q.IsEnabled) } + if len(q.KnowledgeIDs) > 0 { + clauses = append(clauses, "i.knowledge_id IN ?") + args = append(args, q.KnowledgeIDs) + } if kw := strings.TrimSpace(q.Keyword); kw != "" { pattern := "%" + escapeLikeKeyword(kw) + "%" var matches []string @@ -143,7 +156,12 @@ func (d imageAssetDialect) where( args = append(append(args, onArgs...), offArgs...) } filtered = len(clauses) > 2 - return strings.Join(append(clauses, winnerClause), " AND "), args, filtered + winner := winnerClause + if len(q.KnowledgeIDs) > 0 { + winner = scopedWinnerClause + args = append(args, q.KnowledgeIDs) + } + return strings.Join(append(clauses, winner), " AND "), args, filtered } // anyCarries is true for an image carrying any of the sets' values. An image diff --git a/internal/application/repository/chunk_image_assets_test.go b/internal/application/repository/chunk_image_assets_test.go index d21fb42f..ef0c3033 100644 --- a/internal/application/repository/chunk_image_assets_test.go +++ b/internal/application/repository/chunk_image_assets_test.go @@ -282,6 +282,75 @@ func TestListImageAssets_AttributeFiltersAndRules(t *testing.T) { }) } +func TestListImageAssets_KnowledgeIDFilter(t *testing.T) { + imageAssetBackends(t, func(t *testing.T, db *gorm.DB) { + fx := newImageFixture(t, db) + // addRaw writes into the fixture's default document; a second chunk in + // another document of the same KB gives the filter something to exclude. + defaultDoc := fx.addRaw("text", 0, + `[{"url":"local://a.png","original_url":"local://a.png","caption":"a","ocr_text":""}]`) + other := &types.Chunk{ + ID: uuid.NewString(), + TenantID: 1, + KnowledgeBaseID: fx.kbID, + KnowledgeID: "doc-other-" + fx.kbID[:8], + Content: "x", + ChunkType: "text", + IsEnabled: true, + ImageInfo: `[{"url":"local://b.png","original_url":"local://b.png","caption":"b","ocr_text":""}]`, + CreatedAt: fx.base, + UpdatedAt: fx.base, + } + require.NoError(t, db.Create(other).Error) + + rows, total := fx.list(types.ImageAssetQuery{ + KnowledgeIDs: []string{defaultDoc.KnowledgeID}, + SortField: types.ImageAssetField{Builtin: "created_at"}, + }) + require.EqualValues(t, 1, total, "the total reflects the filtered scope") + require.Equal(t, []string{"local://a.png"}, rowURLs(t, rows)) + + rows, total = fx.list(types.ImageAssetQuery{ + KnowledgeIDs: []string{defaultDoc.KnowledgeID, other.KnowledgeID}, + }) + require.EqualValues(t, 2, total) + require.ElementsMatch(t, []string{"local://a.png", "local://b.png"}, rowURLs(t, rows)) + }) +} + +func TestListImageAssets_KnowledgeIDFilterKeepsSharedImage(t *testing.T) { + imageAssetBackends(t, func(t *testing.T, db *gorm.DB) { + fx := newImageFixture(t, db) + shared := `[{"url":"https://example.com/logo.png","original_url":"","caption":"logo","ocr_text":""}]` + older := fx.addRaw("text", 0, shared) + // The same image on a newer chunk of another document wins the + // knowledge-base-wide de-duplication. + newer := &types.Chunk{ + ID: uuid.NewString(), + TenantID: 1, + KnowledgeBaseID: fx.kbID, + KnowledgeID: "doc-newer-" + fx.kbID[:8], + Content: "x", + ChunkType: "text", + IsEnabled: true, + ImageInfo: shared, + CreatedAt: fx.base.Add(5 * time.Minute), + UpdatedAt: fx.base.Add(5 * time.Minute), + } + require.NoError(t, db.Create(newer).Error) + + rows, total := fx.list(types.ImageAssetQuery{KnowledgeIDs: []string{older.KnowledgeID}}) + require.EqualValues(t, 1, total, "the older document still lists its copy") + require.Len(t, rows, 1) + require.Equal(t, older.ID, rows[0].ChunkID) + + rows, total = fx.list(types.ImageAssetQuery{KnowledgeIDs: []string{older.KnowledgeID, newer.KnowledgeID}}) + require.EqualValues(t, 1, total, "copies inside the scope still de-duplicate") + require.Len(t, rows, 1) + require.Equal(t, newer.ID, rows[0].ChunkID) + }) +} + func TestListImageAssets_SortsByAttribute(t *testing.T) { imageAssetBackends(t, func(t *testing.T, db *gorm.DB) { fx := newImageFixture(t, db) diff --git a/internal/application/service/gallery_attrs.go b/internal/application/service/gallery_attrs.go index 7d448c01..5a1ab544 100644 --- a/internal/application/service/gallery_attrs.go +++ b/internal/application/service/gallery_attrs.go @@ -59,6 +59,9 @@ func buildImageAssetQuery(filter *types.ImageListFilter, page *types.Pagination) } q.Keyword = strings.TrimSpace(filter.Keyword) q.IsEnabled = filter.IsEnabled + if len(filter.KnowledgeIDs) > 0 { + q.KnowledgeIDs = filter.KnowledgeIDs + } searchIn := filter.SearchIn if len(searchIn) == 0 { diff --git a/internal/handler/knowledge.go b/internal/handler/knowledge.go index a9fb8db4..857bf3d7 100644 --- a/internal/handler/knowledge.go +++ b/internal/handler/knowledge.go @@ -5,6 +5,7 @@ import ( "encoding/json" goerrors "errors" "fmt" + "io" "net/http" "strconv" "strings" @@ -53,6 +54,14 @@ type backlogProbe interface { // the frontend. const stallHintAfter = 20 * time.Minute +// maxKnowledgeIDFilter caps how many source documents one gallery request may +// restrict itself to via the knowledge_ids query parameter. +const maxKnowledgeIDFilter = 50 + +// maxKnowledgeIDFilterBody is the same cap for the POST /images body variant: +// without URL length limits a generous guard against abuse is enough. +const maxKnowledgeIDFilterBody = 1000 + // stallVerdicts probes ids (all quiet past stallHintAfter) and returns each // one's StallState. Nil when the probe is unavailable or failed: an unknown // row gets no verdict rather than being called stuck. @@ -1143,6 +1152,7 @@ func (h *KnowledgeHandler) ListKnowledge(c *gin.Context) { // @Param sort_by query string false "排序属性 ID;须为 in_sortfield=true,默认 created_at" // @Param sort_order query string false "排序方向:asc / desc,默认 desc" // @Param is_enabled query bool false "仅包含启用状态的图片" +// @Param knowledge_ids query string false "来源文档 ID 列表(逗号分隔,最多 50 个),仅返回这些文档的图片" // @Param attr_filters query string false "属性筛选 JSON,同一属性多值 OR、属性间 AND" // @Param attr_rules query string false "属性逐值裁决 JSON(off 隐藏 / on 强制显示,on 优先)" // @Success 200 {object} map[string]interface{} "图片资产分页列表" @@ -1175,58 +1185,36 @@ func (h *KnowledgeHandler) ListImages(c *gin.Context) { filter.IsEnabled = &enabled } - // Every gallery attribute reference is validated against the resolved - // contract: a client may only search / sort / filter on fields whose - // usage flags allow it, so stale or hand-rolled callers cannot smuggle - // in fields the configuration no longer serves. - resolved := h.resolveGalleryConfig(ctx, kbID) - filterable, searchable, sortable := galleryEligibility(resolved) + // knowledge_ids: comma-separated knowledge item ids the gallery should + // restrict itself to (the "filter by source document" picker). Order is + // irrelevant; the cap keeps a hand-rolled caller from sending an + // unbounded URL. The POST variant lifts the cap via a JSON body. + if raw := strings.TrimSpace(c.Query("knowledge_ids")); raw != "" { + var ids []string + for _, id := range strings.Split(raw, ",") { + if id = strings.TrimSpace(id); id != "" { + ids = append(ids, id) + } + if len(ids) >= maxKnowledgeIDFilter { + break + } + } + filter.KnowledgeIDs = ids + } - // Attribute filters arrive as one JSON object keyed by namespaced - // attribute id ({"system:contain.text":["block"]}); values within one - // attribute are OR-ed, attributes are AND-ed. + // Attribute filters / rules / search fields arrive as raw JSON objects + // keyed by namespaced attribute id; eligibility against the resolved + // contract is enforced by constrainGalleryFilter below. if raw := c.Query("attr_filters"); raw != "" { var attrFilters map[string][]string if err := json.Unmarshal([]byte(raw), &attrFilters); err == nil && len(attrFilters) > 0 { - kept := make(map[string][]string, len(attrFilters)) - for id, values := range attrFilters { - if filterable[id] && len(values) > 0 { - kept[id] = values - } - } - if len(kept) > 0 { - filter.AttrFilters = kept - } + filter.AttrFilters = attrFilters } } - - // Attribute rules arrive as one JSON object keyed by namespaced - // attribute id, each holding a verdict per value - // ({"system:contain.text":{"block":"on","none":"off"}}). Only values - // the image actually carries take part; see AttrRules for the - // precedence between "on" and "off". if raw := c.Query("attr_rules"); raw != "" { var attrRules map[string]map[string]string if err := json.Unmarshal([]byte(raw), &attrRules); err == nil && len(attrRules) > 0 { - kept := make(map[string]map[string]string, len(attrRules)) - for id, verdicts := range attrRules { - if !filterable[id] || len(verdicts) == 0 { - continue - } - clean := make(map[string]string, len(verdicts)) - for value, verdict := range verdicts { - switch verdict { - case "off", "on": - clean[value] = verdict - } - } - if len(clean) > 0 { - kept[id] = clean - } - } - if len(kept) > 0 { - filter.AttrRules = kept - } + filter.AttrRules = attrRules } } @@ -1234,23 +1222,165 @@ func (h *KnowledgeHandler) ListImages(c *gin.Context) { // are dropped, and an empty remainder falls back to the service default // (builtin caption + ocr_text). if raw := strings.TrimSpace(c.Query("search_in")); raw != "" { - var searchIn []string for _, id := range strings.Split(raw, ",") { - id = strings.TrimSpace(id) - if id != "" && searchable[id] { - searchIn = append(searchIn, id) + if id = strings.TrimSpace(id); id != "" { + filter.SearchIn = append(filter.SearchIn, id) } } - filter.SearchIn = searchIn } - // sort_by must be sort-eligible; anything else falls back to the - // service default (builtin created_at, descending). + h.constrainGalleryFilter(ctx, kbID, filter) + + result, err := h.chunkService.ListImagesByKnowledgeBaseID(ctx, kbID, &pagination, filter) + if err != nil { + logger.ErrorWithFields(ctx, err, map[string]interface{}{"kb_id": kbID}) + _ = c.Error(errors.NewInternalServerError(err.Error())) + return + } + + c.JSON(http.StatusOK, gin.H{ + "success": true, + "data": result.Data, + "total": result.Total, + "page": result.Page, + "page_size": result.PageSize, + }) +} + +// constrainGalleryFilter prunes a client-supplied gallery filter to the KB's +// resolved contract: a client may only search / sort / filter on fields whose +// usage flags allow it, so stale or hand-rolled callers cannot smuggle in +// fields the configuration no longer serves. The GET (query params) and POST +// (JSON body) handlers share it; the filter carries raw values on entry. +func (h *KnowledgeHandler) constrainGalleryFilter(ctx context.Context, kbID string, filter *types.ImageListFilter) { + resolved := h.resolveGalleryConfig(ctx, kbID) + filterable, searchable, sortable := galleryEligibility(resolved) + + if len(filter.AttrFilters) > 0 { + kept := make(map[string][]string, len(filter.AttrFilters)) + for id, values := range filter.AttrFilters { + if filterable[id] && len(values) > 0 { + kept[id] = values + } + } + filter.AttrFilters = nil + if len(kept) > 0 { + filter.AttrFilters = kept + } + } + if len(filter.AttrRules) > 0 { + kept := make(map[string]map[string]string, len(filter.AttrRules)) + for id, verdicts := range filter.AttrRules { + if !filterable[id] || len(verdicts) == 0 { + continue + } + clean := make(map[string]string, len(verdicts)) + for value, verdict := range verdicts { + switch verdict { + case "off", "on": + clean[value] = verdict + } + } + if len(clean) > 0 { + kept[id] = clean + } + } + filter.AttrRules = nil + if len(kept) > 0 { + filter.AttrRules = kept + } + } + if len(filter.SearchIn) > 0 { + kept := make([]string, 0, len(filter.SearchIn)) + for _, id := range filter.SearchIn { + if searchable[id] { + kept = append(kept, id) + } + } + filter.SearchIn = kept // empty falls back to the service default + } + // An ineligible sort falls back to the service default (builtin + // created_at, descending). if filter.SortBy != "" && !sortable[filter.SortBy] { filter.SortBy = "" } +} - result, err := h.chunkService.ListImagesByKnowledgeBaseID(ctx, kbID, &pagination, filter) +// imageListRequestBody carries the same parameters as the GET /images query, +// as JSON. knowledge_ids moved into the body lifts the URL-length cap that +// keeps the GET variant to a handful of documents, so the source picker's +// select-all can name every document of a large KB. +type imageListRequestBody struct { + types.Pagination + Keyword string `json:"keyword"` + SearchIn []string `json:"search_in"` + SortBy string `json:"sort_by"` + SortOrder string `json:"sort_order"` + IsEnabled *bool `json:"is_enabled"` + KnowledgeIDs []string `json:"knowledge_ids"` + AttrFilters map[string][]string `json:"attr_filters"` + AttrRules map[string]map[string]string `json:"attr_rules"` +} + +// ListImagesPost lists image assets like ListImages, with the filter arriving +// as a JSON body. +// +// @Summary 列出知识库图片资产(body 版) +// @Description 与 GET /images 同义,筛选参数改经 JSON body 传递:knowledge_ids 不再受 URL 长度限制(上限 1000),供来源文档全选使用。 +// @Tags knowledge +// @Accept json +// @Produce json +// @Param id path string true "知识库 ID" +// @Param body body imageListRequestBody false "筛选参数(与 GET /images 同名参数同义)" +// @Success 200 {object} map[string]interface{} "图片资产分页列表" +// @Failure 400 {object} errors.AppError "请求参数错误" +// @Security Bearer +// @Security ApiKeyAuth +// @Router /knowledge-bases/{id}/images [post] +func (h *KnowledgeHandler) ListImagesPost(c *gin.Context) { + _, kbID, effectiveTenantID, _, err := h.validateKnowledgeBaseAccess(c) + if err != nil { + _ = c.Error(err) + return + } + ctx := types.WithExecutionTenant(c.Request.Context(), effectiveTenantID) + + var body imageListRequestBody + if err := c.ShouldBindJSON(&body); err != nil && !goerrors.Is(err, io.EOF) { + logger.Error(ctx, "Failed to parse image list body", err) + _ = c.Error(errors.NewBadRequestError(err.Error())) + return + } + if len(body.KnowledgeIDs) > maxKnowledgeIDFilterBody { + _ = c.Error(errors.NewBadRequestError( + fmt.Sprintf("knowledge_ids exceeds the cap of %d", maxKnowledgeIDFilterBody))) + return + } + + ids := make([]string, 0, len(body.KnowledgeIDs)) + for _, id := range body.KnowledgeIDs { + if id = strings.TrimSpace(id); id != "" { + ids = append(ids, id) + } + } + sortOrder := body.SortOrder + if sortOrder == "" { + sortOrder = "desc" + } + filter := &types.ImageListFilter{ + Keyword: strings.TrimSpace(body.Keyword), + SearchIn: body.SearchIn, + SortBy: strings.TrimSpace(body.SortBy), + SortOrder: sortOrder, + IsEnabled: body.IsEnabled, + KnowledgeIDs: ids, + AttrFilters: body.AttrFilters, + AttrRules: body.AttrRules, + } + + h.constrainGalleryFilter(ctx, kbID, filter) + + result, err := h.chunkService.ListImagesByKnowledgeBaseID(ctx, kbID, &body.Pagination, filter) if err != nil { logger.ErrorWithFields(ctx, err, map[string]interface{}{"kb_id": kbID}) _ = c.Error(errors.NewInternalServerError(err.Error())) diff --git a/internal/handler/knowledge_images_test.go b/internal/handler/knowledge_images_test.go new file mode 100644 index 00000000..c9748d5a --- /dev/null +++ b/internal/handler/knowledge_images_test.go @@ -0,0 +1,137 @@ +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) + } +} diff --git a/internal/router/routes_knowledge.go b/internal/router/routes_knowledge.go index 3e53d505..87942312 100644 --- a/internal/router/routes_knowledge.go +++ b/internal/router/routes_knowledge.go @@ -90,6 +90,10 @@ func RegisterKnowledgeRoutes(r *gin.RouterGroup, handler *handler.KnowledgeHandl kbImagesRead := kbImages.With(apiKeyRetrieve(apiKeyFullAccess())) { kbImagesRead.GET("/images", g.Viewer(), g.KBAccessRead("id"), handler.ListImages) + // Same listing with the filter as a JSON body: knowledge_ids escapes + // the URL-length cap, so the source picker's select-all can name + // every document of a large KB. + kbImagesRead.POST("/images", g.Viewer(), g.KBAccessRead("id"), handler.ListImagesPost) // Self-describing gallery contract: live attribute sources, the // resolved attribute list (definitions + merged usage) and the // caller's search activation state. Per-KB because KB-defined diff --git a/internal/types/image_gallery.go b/internal/types/image_gallery.go index 9f83b040..9c4a7017 100644 --- a/internal/types/image_gallery.go +++ b/internal/types/image_gallery.go @@ -76,6 +76,10 @@ type ImageListFilter struct { AttrRules map[string]map[string]string // IsEnabled, when non-nil, restricts to chunks with that enabled state. IsEnabled *bool + // KnowledgeIDs, when non-empty, restricts the listing to images whose + // owning document is one of these knowledge items. The handler caps the + // list so a caller cannot send an unbounded IN clause. + KnowledgeIDs []string } // ImageAssetField names one value of an image the gallery query can search, @@ -113,10 +117,13 @@ type ImageAssetQuery struct { OffRules []ImageAssetValueSet // IsEnabled, when non-nil, restricts to chunks with that enabled state. IsEnabled *bool - SortField ImageAssetField - SortDesc bool - Offset int - Limit int + // KnowledgeIDs, when non-empty, restricts to images owned by these + // knowledge items. + KnowledgeIDs []string + SortField ImageAssetField + SortDesc bool + Offset int + Limit int } // ImageAssetRow is one de-duplicated image as the repository returns it: a