Open-source LLM knowledge platform: turn raw documents into a queryable RAG, an autonomous reasoning agent, and a self-maintaining Wiki.
Go agentagenticaichatbotdsh-pluginembeddingsevaluationgenerative-aigolangknowledge-basellmmulti-tenantollamaopenaiquestion-answeringragrerankingsemantic-searchvector-searchwiki
feat(gallery): filter images by source document (#4159)
tayadwx98362dd29698
diff --git a/frontend/src/api/image-gallery/index.ts b/frontend/src/api/image-gallery/index.tsindex a7c0fc6ff..9d31edbc0 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<ImageListResult> {+ 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.tsindex c40fc87f6..32c7eeff9 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.tsindex c4842a7ca..abc559f57 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.tsindex ccccf24fb..d5b1c49a2 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.tsindex dc11022b7..7c5ca99d1 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.tsindex 6db8910bc..dd4f51b29 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.tsindex 1f3577760..c36159b49 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.vuenew file mode 100644index 000000000..25125e04a--- /dev/null+++ b/frontend/src/views/knowledge/gallery/GallerySourcePicker.vue@@ -0,0 +1,599 @@+<script setup lang="ts">+import { computed, ref, watch } from 'vue'+import { useI18n } from 'vue-i18n'+import { MessagePlugin } from 'tdesign-vue-next'+import { listKnowledgeFiles } from '@/api/knowledge-base'++// GallerySourcePicker is the "filter by source document" dialog of the image+// gallery: a paginated, keyword-searchable, sortable checkbox list of the+// knowledge base's documents. Confirming hands the selected ids to the+// gallery (an empty selection clears the restriction); the selection starts+// from what is already active so reopening shows the state the user last+// committed.+//+// Overflow guards: a KB with a huge document count must neither flood the+// dialog nor produce an unbounded gallery query. Without a keyword only the+// most recent RECENT_WINDOW documents are shown; a keyword hit list beyond+// SAFE_HITS cannot be select-all-ed (the user is asked to narrow the+// keyword), which also keeps one select-all fetch within the backend's+// page_size ceiling — the same 1000 the POST /images body cap enforces.+const props = defineProps<{+ kbId: string+ visible: boolean+ selected: string[]+}>()++const emit = defineEmits<{+ (e: 'update:visible', value: boolean): void+ (e: 'confirm', knowledgeIds: string[]): void+}>()++const NS = 'knowledgeEditor.wikiBrowser.gallery'+const { t } = useI18n()++const PAGE_SIZE = 20+const RECENT_WINDOW = 500+const SAFE_HITS = 1000+const SEARCH_DEBOUNCE_MS = 300++const keyword = ref('')+const page = ref(1)+const total = ref(0)+const loading = ref(false)+const bulkLoading = ref(false)+// Sort of the document list; newest uploads first by default so recently+// added documents are at hand.+const sortBy = ref<'created_at' | 'file_name'>('created_at')+const sortDesc = ref(true)+// Documents of the current page.+const docs = ref<Array<{ id: string; file_name: string; created_at: string }>>([])+// Draft selection while the dialog is open; committed on confirm. Search,+// sort and paging only re-render the list and never touch the draft, so a+// keyword-A select-all survives a later keyword-B one (union, not replace).+const draft = ref<Set<string>>(new Set())++// How many documents the listing actually offers: the raw total, capped to+// the window the overflow guards allow for the current search state.+const shownTotal = computed(() => {+ if (keyword.value.trim()) return Math.min(total.value, SAFE_HITS)+ return Math.min(total.value, RECENT_WINDOW)+})+const overflown = computed(() => total.value > shownTotal.value)+// Select-all needs the full hit list in one fetch, so it is only offered+// while the current listing is fully enumerable.+const canSelectAll = computed(() => !overflown.value && shownTotal.value > 0)++const pageAllSelected = computed(+ () => docs.value.length > 0 && docs.value.every((d) => draft.value.has(d.id)),+)+const pageSomeSelected = computed(() => docs.value.some((d) => draft.value.has(d.id)))++// Confirming is a no-op only when nothing was committed and nothing is picked.+const canConfirm = computed(() => draft.value.size > 0 || props.selected.length > 0)++// Bumped by every listing change, so a response for an older search state+// (page fetch or select-all) is dropped.+let fetchToken = 0+async function loadDocs() {+ if (!props.kbId) return+ const token = ++fetchToken+ loading.value = true+ try {+ const res: any = await listKnowledgeFiles(props.kbId, {+ page: page.value,+ page_size: PAGE_SIZE,+ keyword: keyword.value.trim() || undefined,+ sort_by: sortBy.value,+ sort_order: sortDesc.value ? 'desc' : 'asc',+ })+ if (token !== fetchToken) return+ const items: any[] = res?.data ?? []+ docs.value = items.map((it) => ({+ id: String(it.id),+ file_name: it.file_name || it.title || it.id,+ created_at: it.created_at || '',+ }))+ total.value = Number(res?.total) || 0+ } catch (_) {+ if (token === fetchToken) {+ docs.value = []+ total.value = 0+ }+ } finally {+ if (token === fetchToken) loading.value = false+ }+}++let searchTimer: ReturnType<typeof setTimeout> | undefined+function cancelSearch() {+ if (searchTimer) clearTimeout(searchTimer)+ searchTimer = undefined+}++watch(+ () => props.visible,+ (open) => {+ cancelSearch()+ if (!open) return+ draft.value = new Set(props.selected)+ keyword.value = ''+ page.value = 1+ sortBy.value = 'created_at'+ sortDesc.value = true+ void loadDocs()+ },+)++function onKeywordChange(value: string) {+ keyword.value = value+ cancelSearch()+ searchTimer = setTimeout(() => {+ page.value = 1+ void loadDocs()+ }, SEARCH_DEBOUNCE_MS)+}++// TDesign's pagination change event hands over an info object, not a number.+function onPageChange(info: { current: number; previous: number; pageSize: number }) {+ page.value = info.current+ void loadDocs()+}++function toggleSort(field: 'created_at' | 'file_name') {+ if (sortBy.value === field) {+ sortDesc.value = !sortDesc.value+ } else {+ sortBy.value = field+ // Newest first for upload time, A→Z for names.+ sortDesc.value = field === 'created_at'+ }+ page.value = 1+ void loadDocs()+}++function toggle(id: string, checked: boolean) {+ const next = new Set(draft.value)+ if (checked) next.add(id)+ else next.delete(id)+ draft.value = next+}++// Header checkbox, across every hit of the current search (the guards above+// keep one fetch within the backend's page_size ceiling): drops the hits when+// all of them are already selected, adds them otherwise. Merged into the+// draft so earlier keywords survive.+async function onToggleAll() {+ if (!canSelectAll.value || bulkLoading.value) return+ const token = fetchToken+ bulkLoading.value = true+ try {+ const res: any = await listKnowledgeFiles(props.kbId, {+ page: 1,+ page_size: SAFE_HITS,+ keyword: keyword.value.trim() || undefined,+ sort_by: sortBy.value,+ sort_order: sortDesc.value ? 'desc' : 'asc',+ })+ if (token !== fetchToken) return+ const ids: string[] = (res?.data ?? []).map((it: any) => String(it.id))+ if (!ids.length) return+ const next = new Set(draft.value)+ if (ids.every((id) => next.has(id))) {+ for (const id of ids) next.delete(id)+ } else {+ for (const id of ids) next.add(id)+ }+ draft.value = next+ } catch (_) {+ // keep the draft untouched on failure+ } finally {+ bulkLoading.value = false+ }+}++function close() {+ emit('update:visible', false)+}++function onConfirm() {+ if (draft.value.size > SAFE_HITS) {+ MessagePlugin.warning(t(`${NS}.sourceFilterTooMany`))+ return+ }+ emit('confirm', Array.from(draft.value))+ close()+}++function onClearDraft() {+ draft.value = new Set()+}++function formatTime(raw: string): string {+ if (!raw) return '—'+ const d = new Date(raw)+ if (Number.isNaN(d.getTime())) return raw+ const p = (n: number) => String(n).padStart(2, '0')+ return `${d.getFullYear()}-${p(d.getMonth() + 1)}-${p(d.getDate())} ${p(d.getHours())}:${p(d.getMinutes())}`+}+</script>++<template>+ <t-dialog+ :visible="props.visible"+ :footer="false"+ width="640px"+ dialog-class-name="gallery-source-dialog"+ :close-on-overlay-click="false"+ @close="close"+ >+ <template #header>+ <div class="gsp-heading">+ <div class="gsp-heading__row">+ <t-icon name="file" size="16px" class="gsp-heading__icon" aria-hidden="true" />+ <span class="gsp-heading__title">{{ t(`${NS}.sourceFilterTitle`) }}</span>+ </div>+ <p class="gsp-heading__subtitle">{{ t(`${NS}.sourceFilterSubtitle`) }}</p>+ </div>+ </template>++ <div class="gsp-body">+ <t-input+ :value="keyword"+ clearable+ :placeholder="t(`${NS}.sourceFilterSearch`)"+ :aria-label="t(`${NS}.sourceFilterSearch`)"+ class="gsp-search"+ @change="(v: string) => onKeywordChange(String(v ?? ''))"+ >+ <template #prefix-icon><t-icon name="search" size="16px" /></template>+ </t-input>++ <div v-if="overflown" class="gsp-overflow-hint" role="status">+ <t-icon name="info-circle" size="14px" />+ <span>+ {{+ keyword.trim()+ ? t(`${NS}.sourceFilterOverflowHits`, { total: total, cap: shownTotal })+ : t(`${NS}.sourceFilterOverflowRecent`, { cap: shownTotal })+ }}+ </span>+ </div>++ <t-loading :loading="loading || bulkLoading" size="small" show-overlay>+ <div class="gsp-table">+ <div class="gsp-row gsp-head">+ <div class="gsp-col-check">+ <t-checkbox+ :checked="pageAllSelected"+ :indeterminate="pageSomeSelected && !pageAllSelected"+ :disabled="!canSelectAll"+ :title="canSelectAll ? t(`${NS}.sourceFilterSelectAll`) : undefined"+ @change="onToggleAll"+ />+ </div>+ <button+ type="button"+ class="gsp-head-cell"+ :class="{ 'is-active': sortBy === 'file_name' }"+ @click="toggleSort('file_name')"+ >+ <span>{{ t(`${NS}.sourceFilterColName`) }}</span>+ <t-icon v-if="sortBy === 'file_name'" :name="sortDesc ? 'arrow-down' : 'arrow-up'" size="14px" />+ </button>+ <button+ type="button"+ class="gsp-head-cell"+ :class="{ 'is-active': sortBy === 'created_at' }"+ @click="toggleSort('created_at')"+ >+ <span>{{ t(`${NS}.sourceFilterColTime`) }}</span>+ <t-icon v-if="sortBy === 'created_at'" :name="sortDesc ? 'arrow-down' : 'arrow-up'" size="14px" />+ </button>+ </div>++ <div class="gsp-list">+ <div+ v-for="d in docs"+ :key="d.id"+ class="gsp-row gsp-item"+ :class="{ 'is-selected': draft.has(d.id) }"+ @click="toggle(d.id, !draft.has(d.id))"+ >+ <div class="gsp-col-check" @click.stop>+ <t-checkbox :checked="draft.has(d.id)" @change="(checked: boolean) => toggle(d.id, checked)" />+ </div>+ <div class="gsp-col-name" :title="d.file_name">{{ d.file_name }}</div>+ <div class="gsp-col-time">{{ formatTime(d.created_at) }}</div>+ </div>+ <div v-if="!docs.length && !loading" class="gsp-empty">+ {{ t(`${NS}.sourceFilterEmpty`) }}+ </div>+ </div>+ </div>+ </t-loading>++ <t-pagination+ v-if="shownTotal > PAGE_SIZE"+ class="gsp-pagination"+ size="small"+ :current="page"+ :total="shownTotal"+ :page-size="PAGE_SIZE"+ :show-page-size="false"+ :show-jumper="false"+ @change="onPageChange"+ />+ </div>++ <div class="gsp-footer">+ <div class="gsp-footer__left">+ <span class="gsp-footer__count">{{ t(`${NS}.sourceFilterSelected`, { count: draft.size }) }}</span>+ <button v-if="draft.size" type="button" class="gsp-footer__clear" @click="onClearDraft">+ {{ t(`${NS}.sourceFilterClear`) }}+ </button>+ </div>+ <div class="gsp-footer__right">+ <t-button variant="outline" size="small" @click="close">{{ t('common.cancel') }}</t-button>+ <t-button theme="primary" size="small" :disabled="!canConfirm || bulkLoading" @click="onConfirm">+ {{ t('common.confirm') }}+ </t-button>+ </div>+ </div>+ </t-dialog>+</template>++<style>+/* The dialog renders outside the component; same shell as BatchTagDialog. */+.gallery-source-dialog {+ overflow: hidden;+ padding: 0;+ border-radius: var(--app-radius-xs);+}++.gallery-source-dialog .t-dialog__header {+ min-height: auto;+ padding: 20px 20px 0;+}++.gallery-source-dialog .t-dialog__body {+ padding: 16px 20px 20px;+}++.gallery-source-dialog .t-dialog__close {+ top: 16px;+ right: 16px;+ width: 28px;+ height: 28px;+ border-radius: var(--app-radius-xs);+ color: var(--td-text-color-secondary);+ transition: background var(--app-motion-fast) ease;+}++.gallery-source-dialog .t-dialog__close:hover {+ color: var(--td-text-color-primary);+ background: var(--td-bg-color-container-hover);+}++@media (max-width: 680px) {+ .gallery-source-dialog {+ width: calc(100vw - 24px) !important;+ }+}+</style>++<style scoped>+.gsp-heading {+ display: flex;+ flex-direction: column;+ gap: 4px;+ min-width: 0;+ padding-right: 28px;+}++.gsp-heading__row {+ display: flex;+ align-items: center;+ gap: 8px;+ min-width: 0;+}++.gsp-heading__icon {+ flex-shrink: 0;+ color: var(--td-text-color-secondary);+}++.gsp-heading__title {+ color: var(--td-text-color-primary);+ font-size: var(--app-text-lg);+ font-weight: 600;+ line-height: 22px;+}++.gsp-heading__subtitle {+ margin: 0;+ color: var(--td-text-color-placeholder);+ font-size: var(--app-text-sm);+ font-weight: 400;+ line-height: 18px;+}++.gsp-body {+ display: flex;+ flex-direction: column;+ gap: 12px;+}++.gsp-search :deep(.t-input) {+ border-color: var(--td-component-stroke);+ border-radius: var(--app-radius-md);+ font-size: var(--app-text-md);+}++.gsp-overflow-hint {+ display: flex;+ align-items: flex-start;+ gap: 6px;+ padding: 8px 10px;+ border-radius: var(--app-radius-md);+ background: var(--td-warning-color-1);+ color: var(--td-warning-color-7);+ font-size: var(--app-text-sm);+ line-height: 18px;+}++.gsp-overflow-hint .t-icon {+ flex-shrink: 0;+ margin-top: 2px;+}++.gsp-table {+ display: flex;+ flex-direction: column;+ min-height: 240px;+ border: 1px solid var(--td-component-stroke);+ border-radius: var(--app-radius-md);+ overflow: hidden;+}++.gsp-row {+ display: grid;+ grid-template-columns: 32px minmax(0, 1fr) 136px;+ align-items: center;+ gap: 8px;+ padding: 0 12px;+}++.gsp-head {+ height: 36px;+ border-bottom: 1px solid var(--td-component-stroke);+ background: var(--td-bg-color-secondarycontainer);+ color: var(--td-text-color-secondary);+ font-size: var(--app-text-sm);+}++.gsp-head-cell {+ display: inline-flex;+ align-items: center;+ gap: 4px;+ padding: 0;+ border: none;+ background: none;+ font: inherit;+ color: inherit;+ cursor: pointer;+ text-align: left;+ justify-self: start;+}++.gsp-head-cell:hover {+ color: var(--td-text-color-primary);+}++.gsp-head-cell.is-active {+ color: var(--td-text-color-primary);+ font-weight: 600;+}++.gsp-head-cell:focus-visible {+ outline: 2px solid var(--app-focus-border);+ outline-offset: 2px;+}++.gsp-list {+ max-height: 324px;+ overflow-y: auto;+}++.gsp-item {+ height: 36px;+ cursor: pointer;+ transition: background-color var(--app-motion-fast) ease;+}++.gsp-item + .gsp-item {+ border-top: 1px solid var(--td-component-stroke);+}++.gsp-item:hover {+ background: var(--td-bg-color-container-hover);+}++.gsp-item.is-selected {+ background: var(--td-brand-color-light);+}++.gsp-col-check {+ display: flex;+ align-items: center;+}++.gsp-col-name {+ overflow: hidden;+ text-overflow: ellipsis;+ white-space: nowrap;+ color: var(--td-text-color-primary);+ font-size: var(--app-text-md);+}++.gsp-col-time {+ color: var(--td-text-color-placeholder);+ font-size: var(--app-text-sm);+ font-variant-numeric: tabular-nums;+}++.gsp-empty {+ padding: 48px 0;+ text-align: center;+ color: var(--td-text-color-placeholder);+ font-size: var(--app-text-sm);+}++.gsp-pagination {+ justify-content: flex-end;+}++.gsp-footer {+ display: flex;+ align-items: center;+ justify-content: space-between;+ gap: 12px;+ margin-top: 14px;+ padding-top: 14px;+ border-top: 1px solid var(--td-component-stroke);+}++.gsp-footer__left {+ display: flex;+ align-items: center;+ gap: 12px;+ min-width: 0;+}++.gsp-footer__count {+ color: var(--td-text-color-placeholder);+ font-size: var(--app-text-sm);+ font-variant-numeric: tabular-nums;+ white-space: nowrap;+}++.gsp-footer__clear {+ padding: 0;+ border: 0;+ background: transparent;+ color: var(--td-text-color-secondary);+ font: inherit;+ font-size: var(--app-text-sm);+ cursor: pointer;+}++.gsp-footer__clear:hover {+ color: var(--td-brand-color);+}++.gsp-footer__right {+ display: flex;+ align-items: center;+ gap: 8px;+ flex-shrink: 0;+}+</style>diff --git a/frontend/src/views/knowledge/gallery/ImageGallery.vue b/frontend/src/views/knowledge/gallery/ImageGallery.vueindex e2b4d317d..28472d8f0 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<Record<string, number>>({})let cardObserver: ResizeObserver | undefinedlet 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<string[]>([])+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<Record<string, string[]>>({})@@ -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 = falsereleaseBlobs()configLoaded.value = falseconfig.value = { attribute_sources: [], attributes: [], mode: 'all', status: {} }@@ -656,6 +674,17 @@ watch(<template #prefix-icon><t-icon name="search" size="16px" /></template></t-input>+ <button+ type="button"+ class="ig-tool-btn"+ :class="{ active: sourcePickerVisible || sourceDocIds.length > 0 }"+ @click="sourcePickerVisible = true"+ >+ <t-icon name="file" size="16px" />+ {{ t(`${NS}.sourceFilter`) }}+ <span v-if="sourceDocIds.length" class="ig-tool-btn__count">{{ sourceDocIds.length }}</span>+ </button>+<t-popupv-model:visible="filterPanelVisible"trigger="click"@@ -893,6 +922,14 @@ watch(@close="closeViewer"@open-source="onOpenSource"/>++ <GallerySourcePicker+ :kb-id="props.knowledgeBaseId"+ :visible="sourcePickerVisible"+ :selected="sourceDocIds"+ @update:visible="(v: boolean) => (sourcePickerVisible = v)"+ @confirm="onSourceDocsConfirm"+ /></div></template>diff --git a/internal/application/repository/chunk_image_assets.go b/internal/application/repository/chunk_image_assets.goindex d4d3d3986..4b34b2910 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 imagediff --git a/internal/application/repository/chunk_image_assets_test.go b/internal/application/repository/chunk_image_assets_test.goindex d21fb42f6..ef0c30339 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.goindex 7d448c018..5a1ab544b 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.SearchInif len(searchIn) == 0 {diff --git a/internal/handler/knowledge.go b/internal/handler/knowledge.goindex a9fb8db44..857bf3d79 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][]stringif 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]stringif 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 []stringfor _, 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.gonew file mode 100644index 000000000..c9748d5a0--- /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.goindex 3e53d505b..879423126 100644--- a/internal/router/routes_knowledge.go+++ b/internal/router/routes_knowledge.go@@ -90,6 +90,10 @@ func RegisterKnowledgeRoutes(r *gin.RouterGroup, handler *handler.KnowledgeHandlkbImagesRead := 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-defineddiff --git a/internal/types/image_gallery.go b/internal/types/image_gallery.goindex 9f83b0402..9c4a7017f 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