feat(knowledge-base): document list filters and explicit batch-management UX

Add three new optional filters to the document list under a knowledge base
detail page — parse status, source/channel, and updated time range — and
rework multi-select to no longer cause the card title to jitter on hover.

Backend
- Introduce types.KnowledgeListFilter to aggregate optional filter dimensions
  (tag, keyword, file_type, parse_status, source, updated_from/to) and switch
  ListPagedKnowledgeByKnowledgeBaseID (repository/service/interface) to accept
  it instead of a growing positional parameter list.
- The ListKnowledge HTTP handler accepts new parse_status, source, start_time
  and end_time query params; time params accept RFC3339, "YYYY-MM-DD HH:MM:SS"
  and "YYYY-MM-DD". The repository routes source="manual"/"url" onto the type
  column to stay consistent with file_type semantics; other source values match
  the channel column.
- Update the four other callers (agent_service, initialization) to pass an
  empty filter struct, preserving prior behavior.

Frontend
- Add three controls in the doc-filter-bar (status select, source select,
  date-range picker with future-date disabled) wired through getKnowled /
  listKnowledgeFiles into the new backend params.
- Replace the hover-triggered card checkbox with an explicit "批量管理" mode
  (mirrors the session list UX): in card view the checkbox only renders while
  batch mode is on, entered via the per-card "..." menu; the list view keeps
  its leading checkbox column. Switching from list to grid auto-enables batch
  mode when something is already selected, so the selection stays visible.
- DocumentBatchBar now stays open whenever batch mode or selection > 0, and
  its "取消选择" button both clears the selection and exits batch mode.

API surface sync
- Regenerate Swagger artifacts (docs/docs.go / swagger.json / swagger.yaml).
- Update docs/api/knowledge.md with the new query parameters.
- Add backward-compatible ListKnowledgeWithFilter + KnowledgeListFilter to the
  Go SDK; the existing ListKnowledge keeps its signature.

i18n
- New filter labels in zh-CN / en-US / ko-KR / ru-RU; reuse existing
  menu.batchManage / batchManage.cancel for the multi-select strings.
This commit is contained in:
wizardchen
2026-05-12 18:16:34 +08:00
committed by lyingbug
parent f635eaf466
commit cacca049d9
20 changed files with 596 additions and 174 deletions
+54 -9
View File
@@ -278,20 +278,65 @@ func (c *Client) GetKnowledgeBatch(ctx context.Context, knowledgeIDs []string) (
return response.Data, nil return response.Data, nil
} }
// ListKnowledge lists knowledge entries in a knowledge base with pagination // ListKnowledge lists knowledge entries in a knowledge base with pagination.
// For richer filtering (keyword, file type, parse status, source, time range)
// use ListKnowledgeWithFilter.
func (c *Client) ListKnowledge(ctx context.Context, func (c *Client) ListKnowledge(ctx context.Context,
knowledgeBaseID string, knowledgeBaseID string,
page int, page int,
pageSize int, pageSize int,
tagID string, tagID string,
) ([]Knowledge, int64, error) {
return c.ListKnowledgeWithFilter(ctx, knowledgeBaseID, page, pageSize, KnowledgeListFilter{TagID: tagID})
}
// KnowledgeListFilter mirrors the server-side filters accepted by GET
// /api/v1/knowledge-bases/{id}/knowledge. Empty / zero fields are omitted from
// the request.
type KnowledgeListFilter struct {
TagID string
Keyword string
FileType string
ParseStatus string
Source string
// StartTime / EndTime filter on knowledge updated_at. Zero values are skipped.
// They are serialized in RFC3339 format.
StartTime time.Time
EndTime time.Time
}
// ListKnowledgeWithFilter lists knowledge entries with the full filter surface.
func (c *Client) ListKnowledgeWithFilter(ctx context.Context,
knowledgeBaseID string,
page int,
pageSize int,
filter KnowledgeListFilter,
) ([]Knowledge, int64, error) { ) ([]Knowledge, int64, error) {
path := fmt.Sprintf("/api/v1/knowledge-bases/%s/knowledge", knowledgeBaseID) path := fmt.Sprintf("/api/v1/knowledge-bases/%s/knowledge", knowledgeBaseID)
queryParams := url.Values{} queryParams := url.Values{}
queryParams.Add("page", strconv.Itoa(page)) queryParams.Add("page", strconv.Itoa(page))
queryParams.Add("page_size", strconv.Itoa(pageSize)) queryParams.Add("page_size", strconv.Itoa(pageSize))
if tagID != "" { if filter.TagID != "" {
queryParams.Add("tag_id", tagID) queryParams.Add("tag_id", filter.TagID)
}
if filter.Keyword != "" {
queryParams.Add("keyword", filter.Keyword)
}
if filter.FileType != "" {
queryParams.Add("file_type", filter.FileType)
}
if filter.ParseStatus != "" {
queryParams.Add("parse_status", filter.ParseStatus)
}
if filter.Source != "" {
queryParams.Add("source", filter.Source)
}
if !filter.StartTime.IsZero() {
queryParams.Add("start_time", filter.StartTime.Format(time.RFC3339))
}
if !filter.EndTime.IsZero() {
queryParams.Add("end_time", filter.EndTime.Format(time.RFC3339))
} }
resp, err := c.doRequest(ctx, http.MethodGet, path, nil, queryParams) resp, err := c.doRequest(ctx, http.MethodGet, path, nil, queryParams)
@@ -439,8 +484,8 @@ func (c *Client) UpdateImageInfo(ctx context.Context,
// CreateManualKnowledgeRequest contains the parameters for creating a manual Markdown knowledge entry. // CreateManualKnowledgeRequest contains the parameters for creating a manual Markdown knowledge entry.
type CreateManualKnowledgeRequest struct { type CreateManualKnowledgeRequest struct {
Title string `json:"title"` Title string `json:"title"`
Content string `json:"content"` Content string `json:"content"`
TagID string `json:"tag_id,omitempty"` TagID string `json:"tag_id,omitempty"`
Channel string `json:"channel,omitempty"` Channel string `json:"channel,omitempty"`
} }
@@ -550,8 +595,8 @@ func (c *Client) MoveKnowledge(ctx context.Context, req *MoveKnowledgeRequest) (
} }
var result struct { var result struct {
Success bool `json:"success"` Success bool `json:"success"`
Data *MoveKnowledgeResponse `json:"data"` Data *MoveKnowledgeResponse `json:"data"`
} }
if err := parseResponse(resp, &result); err != nil { if err := parseResponse(resp, &result); err != nil {
return nil, err return nil, err
@@ -579,8 +624,8 @@ func (c *Client) GetKnowledgeMoveProgress(ctx context.Context, taskID string) (*
} }
var result struct { var result struct {
Success bool `json:"success"` Success bool `json:"success"`
Data *KnowledgeMoveProgress `json:"data"` Data *KnowledgeMoveProgress `json:"data"`
} }
if err := parseResponse(resp, &result); err != nil { if err := parseResponse(resp, &result); err != nil {
return nil, err return nil, err
+11 -7
View File
@@ -258,13 +258,17 @@ curl --location 'http://localhost:8080/api/v1/knowledge-bases/kb-00000001/knowle
**查询参数**: **查询参数**:
| 字段 | 类型 | 默认 | 说明 | | 字段 | 类型 | 默认 | 说明 |
| ----------- | ------- | ---- | ----------------------------------- | | -------------- | ------- | ---- | --------------------------------------------------------------------------------------------------- |
| `page` | integer | 1 | 页码(从 1 开始) | | `page` | integer | 1 | 页码(从 1 开始) |
| `page_size` | integer | 20 | 每页条数 | | `page_size` | integer | 20 | 每页条数 |
| `tag_id` | string | - | 按标签 ID 过滤 | | `tag_id` | string | - | 按标签 ID 过滤 |
| `keyword` | string | - | 按标题/内容关键词过滤 | | `keyword` | string | - | 按标题/内容关键词过滤 |
| `file_type` | string | - | 按单个文件扩展名过滤(如 `pdf`) | | `file_type` | string | - | 按单个文件扩展名过滤(如 `pdf`);特殊值 `manual` / `url` 命中 `type` 列 |
| `parse_status` | string | - | 按解析状态过滤:`pending` / `processing` / `completed` / `failed` |
| `source` | string | - | 按来源/渠道过滤:`web` / `api` / `browser_extension` / `feishu` / `notion` / `yuque` / `wechat` 等; 特殊值 `manual` / `url` 命中 `type` 列 |
| `start_time` | string | - | 更新时间起点,接受 RFC3339 (`2024-05-01T00:00:00+08:00`) 或 `YYYY-MM-DD HH:MM:SS` / `YYYY-MM-DD` |
| `end_time` | string | - | 更新时间终点,格式同 `start_time` |
**请求**: **请求**:
+32 -2
View File
@@ -5097,6 +5097,30 @@ const docTemplate = `{
"description": "文件类型筛选", "description": "文件类型筛选",
"name": "file_type", "name": "file_type",
"in": "query" "in": "query"
},
{
"type": "string",
"description": "解析状态筛选 (pending/processing/completed/failed)",
"name": "parse_status",
"in": "query"
},
{
"type": "string",
"description": "来源/渠道筛选 (web/api/feishu/notion/yuque/wechat/...,或 manual/url 按 type 过滤)",
"name": "source",
"in": "query"
},
{
"type": "string",
"description": "更新时间起点,RFC3339 格式",
"name": "start_time",
"in": "query"
},
{
"type": "string",
"description": "更新时间终点,RFC3339 格式",
"name": "end_time",
"in": "query"
} }
], ],
"responses": { "responses": {
@@ -15217,6 +15241,10 @@ const docTemplate = `{
"description": "API key for the search provider (encrypted in DB)", "description": "API key for the search provider (encrypted in DB)",
"type": "string" "type": "string"
}, },
"base_url": {
"description": "Base URL for self-hosted search engines (e.g. SearXNG instance URL).\nValidated with utils.ValidateURLForSSRF; private hosts must be added to SSRF_WHITELIST.",
"type": "string"
},
"engine_id": { "engine_id": {
"description": "Google Custom Search Engine ID (only for Google provider)", "description": "Google Custom Search Engine ID (only for Google provider)",
"type": "string" "type": "string"
@@ -15242,7 +15270,8 @@ const docTemplate = `{
"duckduckgo", "duckduckgo",
"tavily", "tavily",
"ollama", "ollama",
"baidu" "baidu",
"searxng"
], ],
"x-enum-varnames": [ "x-enum-varnames": [
"WebSearchProviderTypeBing", "WebSearchProviderTypeBing",
@@ -15250,7 +15279,8 @@ const docTemplate = `{
"WebSearchProviderTypeDuckDuckGo", "WebSearchProviderTypeDuckDuckGo",
"WebSearchProviderTypeTavily", "WebSearchProviderTypeTavily",
"WebSearchProviderTypeOllama", "WebSearchProviderTypeOllama",
"WebSearchProviderTypeBaidu" "WebSearchProviderTypeBaidu",
"WebSearchProviderTypeSearxng"
] ]
}, },
"github_com_Tencent_WeKnora_internal_types.WikiConfig": { "github_com_Tencent_WeKnora_internal_types.WikiConfig": {
+32 -2
View File
@@ -5090,6 +5090,30 @@
"description": "文件类型筛选", "description": "文件类型筛选",
"name": "file_type", "name": "file_type",
"in": "query" "in": "query"
},
{
"type": "string",
"description": "解析状态筛选 (pending/processing/completed/failed)",
"name": "parse_status",
"in": "query"
},
{
"type": "string",
"description": "来源/渠道筛选 (web/api/feishu/notion/yuque/wechat/...,或 manual/url 按 type 过滤)",
"name": "source",
"in": "query"
},
{
"type": "string",
"description": "更新时间起点,RFC3339 格式",
"name": "start_time",
"in": "query"
},
{
"type": "string",
"description": "更新时间终点,RFC3339 格式",
"name": "end_time",
"in": "query"
} }
], ],
"responses": { "responses": {
@@ -15210,6 +15234,10 @@
"description": "API key for the search provider (encrypted in DB)", "description": "API key for the search provider (encrypted in DB)",
"type": "string" "type": "string"
}, },
"base_url": {
"description": "Base URL for self-hosted search engines (e.g. SearXNG instance URL).\nValidated with utils.ValidateURLForSSRF; private hosts must be added to SSRF_WHITELIST.",
"type": "string"
},
"engine_id": { "engine_id": {
"description": "Google Custom Search Engine ID (only for Google provider)", "description": "Google Custom Search Engine ID (only for Google provider)",
"type": "string" "type": "string"
@@ -15235,7 +15263,8 @@
"duckduckgo", "duckduckgo",
"tavily", "tavily",
"ollama", "ollama",
"baidu" "baidu",
"searxng"
], ],
"x-enum-varnames": [ "x-enum-varnames": [
"WebSearchProviderTypeBing", "WebSearchProviderTypeBing",
@@ -15243,7 +15272,8 @@
"WebSearchProviderTypeDuckDuckGo", "WebSearchProviderTypeDuckDuckGo",
"WebSearchProviderTypeTavily", "WebSearchProviderTypeTavily",
"WebSearchProviderTypeOllama", "WebSearchProviderTypeOllama",
"WebSearchProviderTypeBaidu" "WebSearchProviderTypeBaidu",
"WebSearchProviderTypeSearxng"
] ]
}, },
"github_com_Tencent_WeKnora_internal_types.WikiConfig": { "github_com_Tencent_WeKnora_internal_types.WikiConfig": {
+24
View File
@@ -2986,6 +2986,11 @@ definitions:
api_key: api_key:
description: API key for the search provider (encrypted in DB) description: API key for the search provider (encrypted in DB)
type: string type: string
base_url:
description: |-
Base URL for self-hosted search engines (e.g. SearXNG instance URL).
Validated with utils.ValidateURLForSSRF; private hosts must be added to SSRF_WHITELIST.
type: string
engine_id: engine_id:
description: Google Custom Search Engine ID (only for Google provider) description: Google Custom Search Engine ID (only for Google provider)
type: string type: string
@@ -3008,6 +3013,7 @@ definitions:
- tavily - tavily
- ollama - ollama
- baidu - baidu
- searxng
type: string type: string
x-enum-varnames: x-enum-varnames:
- WebSearchProviderTypeBing - WebSearchProviderTypeBing
@@ -3016,6 +3022,7 @@ definitions:
- WebSearchProviderTypeTavily - WebSearchProviderTypeTavily
- WebSearchProviderTypeOllama - WebSearchProviderTypeOllama
- WebSearchProviderTypeBaidu - WebSearchProviderTypeBaidu
- WebSearchProviderTypeSearxng
github_com_Tencent_WeKnora_internal_types.WikiConfig: github_com_Tencent_WeKnora_internal_types.WikiConfig:
properties: properties:
extraction_granularity: extraction_granularity:
@@ -7478,6 +7485,23 @@ paths:
in: query in: query
name: file_type name: file_type
type: string type: string
- description: 解析状态筛选 (pending/processing/completed/failed)
in: query
name: parse_status
type: string
- description: 来源/渠道筛选 (web/api/feishu/notion/yuque/wechat/...,或 manual/url
按 type 过滤)
in: query
name: source
type: string
- description: 更新时间起点,RFC3339 格式
in: query
name: start_time
type: string
- description: 更新时间终点,RFC3339 格式
in: query
name: end_time
type: string
produces: produces:
- application/json - application/json
responses: responses:
+18 -10
View File
@@ -133,20 +133,28 @@ export function createManualKnowledge(kbId: string, data: { title: string; conte
export function listKnowledgeFiles( export function listKnowledgeFiles(
kbId: string, kbId: string,
params: { page: number; page_size: number; tag_id?: string; keyword?: string; file_type?: string }, params: {
page: number;
page_size: number;
tag_id?: string;
keyword?: string;
file_type?: string;
parse_status?: string;
source?: string;
start_time?: string;
end_time?: string;
},
) { ) {
const query = new URLSearchParams(); const query = new URLSearchParams();
query.append('page', String(params.page)); query.append('page', String(params.page));
query.append('page_size', String(params.page_size)); query.append('page_size', String(params.page_size));
if (params.tag_id) { if (params.tag_id) query.append('tag_id', params.tag_id);
query.append('tag_id', params.tag_id); if (params.keyword) query.append('keyword', params.keyword);
} if (params.file_type) query.append('file_type', params.file_type);
if (params.keyword) { if (params.parse_status) query.append('parse_status', params.parse_status);
query.append('keyword', params.keyword); if (params.source) query.append('source', params.source);
} if (params.start_time) query.append('start_time', params.start_time);
if (params.file_type) { if (params.end_time) query.append('end_time', params.end_time);
query.append('file_type', params.file_type);
}
const qs = query.toString(); const qs = query.toString();
return get(`/api/v1/knowledge-bases/${kbId}/knowledge?${qs}`); return get(`/api/v1/knowledge-bases/${kbId}/knowledge?${qs}`);
} }
+11 -1
View File
@@ -36,7 +36,17 @@ export default function (knowledgeBaseId?: string) {
chunkLoadError: "", chunkLoadError: "",
}); });
const getKnowled = ( const getKnowled = (
query: { page: number; page_size: number; tag_id?: string; keyword?: string; file_type?: string } = { page: 1, page_size: 35 }, query: {
page: number;
page_size: number;
tag_id?: string;
keyword?: string;
file_type?: string;
parse_status?: string;
source?: string;
start_time?: string;
end_time?: string;
} = { page: 1, page_size: 35 },
kbId?: string, kbId?: string,
): Promise<void> => { ): Promise<void> => {
const targetKbId = kbId || knowledgeBaseId; const targetKbId = kbId || knowledgeBaseId;
+17
View File
@@ -315,6 +315,23 @@ export default {
docSearchPlaceholder: 'Search document names...', docSearchPlaceholder: 'Search document names...',
fileTypeFilter: 'File Type', fileTypeFilter: 'File Type',
allFileTypes: 'All Types', allFileTypes: 'All Types',
parseStatusFilter: 'Status',
allParseStatuses: 'All Statuses',
parseStatusPending: 'Pending',
parseStatusProcessing: 'Processing',
parseStatusCompleted: 'Completed',
parseStatusFailed: 'Failed',
sourceFilter: 'Source',
allSources: 'All Sources',
sourceWeb: 'Web',
sourceApi: 'API',
sourceBrowserExtension: 'Browser Extension',
sourceUpload: 'Upload',
sourceUrl: 'URL Import',
sourceManual: 'Manual',
updatedTimeFilter: 'Updated',
updatedTimeFrom: 'From',
updatedTimeTo: 'To',
noMatch: 'No matching knowledge base found', noMatch: 'No matching knowledge base found',
noKnowledge: 'No knowledge bases available', noKnowledge: 'No knowledge bases available',
loadingFailed: 'Failed to load knowledge bases', loadingFailed: 'Failed to load knowledge bases',
+17
View File
@@ -322,6 +322,23 @@ export default {
docSearchPlaceholder: "문서 이름 검색...", docSearchPlaceholder: "문서 이름 검색...",
fileTypeFilter: "파일 유형", fileTypeFilter: "파일 유형",
allFileTypes: "모든 유형", allFileTypes: "모든 유형",
parseStatusFilter: "상태",
allParseStatuses: "모든 상태",
parseStatusPending: "대기 중",
parseStatusProcessing: "처리 중",
parseStatusCompleted: "완료됨",
parseStatusFailed: "실패",
sourceFilter: "출처",
allSources: "모든 출처",
sourceWeb: "웹",
sourceApi: "API",
sourceBrowserExtension: "브라우저 확장",
sourceUpload: "로컬 업로드",
sourceUrl: "URL 가져오기",
sourceManual: "수동 생성",
updatedTimeFilter: "업데이트 시간",
updatedTimeFrom: "시작",
updatedTimeTo: "종료",
noMatch: "일치하는 지식베이스를 찾을 수 없음", noMatch: "일치하는 지식베이스를 찾을 수 없음",
noKnowledge: "사용 가능한 지식베이스 없음", noKnowledge: "사용 가능한 지식베이스 없음",
loadingFailed: "지식베이스 로드 실패", loadingFailed: "지식베이스 로드 실패",
+17
View File
@@ -286,6 +286,23 @@ export default {
docSearchPlaceholder: 'Поиск документов...', docSearchPlaceholder: 'Поиск документов...',
fileTypeFilter: 'Тип файла', fileTypeFilter: 'Тип файла',
allFileTypes: 'Все типы', allFileTypes: 'Все типы',
parseStatusFilter: 'Статус',
allParseStatuses: 'Все статусы',
parseStatusPending: 'Ожидание',
parseStatusProcessing: 'Обработка',
parseStatusCompleted: 'Завершено',
parseStatusFailed: 'Ошибка',
sourceFilter: 'Источник',
allSources: 'Все источники',
sourceWeb: 'Веб',
sourceApi: 'API',
sourceBrowserExtension: 'Расширение браузера',
sourceUpload: 'Загрузка',
sourceUrl: 'URL импорт',
sourceManual: 'Создан вручную',
updatedTimeFilter: 'Обновлено',
updatedTimeFrom: 'С',
updatedTimeTo: 'По',
noMatch: 'Совпадающих баз знаний не найдено', noMatch: 'Совпадающих баз знаний не найдено',
noKnowledge: 'Нет доступных баз знаний', noKnowledge: 'Нет доступных баз знаний',
loadingFailed: 'Не удалось загрузить базы знаний', loadingFailed: 'Не удалось загрузить базы знаний',
+17
View File
@@ -319,6 +319,23 @@ export default {
docSearchPlaceholder: "搜索文档名称...", docSearchPlaceholder: "搜索文档名称...",
fileTypeFilter: "文件类型", fileTypeFilter: "文件类型",
allFileTypes: "全部类型", allFileTypes: "全部类型",
parseStatusFilter: "解析状态",
allParseStatuses: "全部状态",
parseStatusPending: "等待中",
parseStatusProcessing: "处理中",
parseStatusCompleted: "已完成",
parseStatusFailed: "失败",
sourceFilter: "来源",
allSources: "全部来源",
sourceWeb: "网页",
sourceApi: "API",
sourceBrowserExtension: "浏览器扩展",
sourceUpload: "本地上传",
sourceUrl: "URL 导入",
sourceManual: "手动创建",
updatedTimeFilter: "更新时间",
updatedTimeFrom: "起始时间",
updatedTimeTo: "结束时间",
noMatch: "未找到匹配的知识库", noMatch: "未找到匹配的知识库",
noKnowledge: "暂无可用知识库", noKnowledge: "暂无可用知识库",
loadingFailed: "加载知识库失败", loadingFailed: "加载知识库失败",
+161 -49
View File
@@ -307,22 +307,65 @@ let docSearchDebounce: ReturnType<typeof setTimeout> | null = null;
const docSearchKeyword = ref(''); const docSearchKeyword = ref('');
const selectedFileType = ref(''); const selectedFileType = ref('');
const fileTypeOptions = computed(() => [ const fileTypeOptions = computed(() => [
{ content: t('knowledgeBase.allFileTypes'), value: '' }, { label: t('knowledgeBase.allFileTypes'), value: '' },
{ content: 'PDF', value: 'pdf' }, { label: 'PDF', value: 'pdf' },
{ content: 'DOCX', value: 'docx' }, { label: 'DOCX', value: 'docx' },
{ content: 'DOC', value: 'doc' }, { label: 'DOC', value: 'doc' },
{ content: 'PPTX', value: 'pptx' }, { label: 'PPTX', value: 'pptx' },
{ content: 'PPT', value: 'ppt' }, { label: 'PPT', value: 'ppt' },
{ content: 'TXT', value: 'txt' }, { label: 'TXT', value: 'txt' },
{ content: 'MD', value: 'md' }, { label: 'MD', value: 'md' },
{ content: 'URL', value: 'url' }, { label: 'URL', value: 'url' },
{ content: t('knowledgeBase.typeManual'), value: 'manual' }, { label: t('knowledgeBase.typeManual'), value: 'manual' },
{ content: 'MP3', value: 'mp3' }, { label: 'MP3', value: 'mp3' },
{ content: 'WAV', value: 'wav' }, { label: 'WAV', value: 'wav' },
{ content: 'M4A', value: 'm4a' }, { label: 'M4A', value: 'm4a' },
{ content: 'FLAC', value: 'flac' }, { label: 'FLAC', value: 'flac' },
{ content: 'OGG', value: 'ogg' }, { label: 'OGG', value: 'ogg' },
]); ]);
const selectedParseStatus = ref('');
const parseStatusOptions = computed(() => [
{ label: t('knowledgeBase.allParseStatuses'), value: '' },
{ label: t('knowledgeBase.parseStatusPending'), value: 'pending' },
{ label: t('knowledgeBase.parseStatusProcessing'), value: 'processing' },
{ label: t('knowledgeBase.parseStatusCompleted'), value: 'completed' },
{ label: t('knowledgeBase.parseStatusFailed'), value: 'failed' },
]);
const selectedSource = ref('');
// Source filter combines ingestion channels and the "manual"/"url" virtual
// sources that the backend routes onto the `type` column.
const sourceOptions = computed(() => [
{ label: t('knowledgeBase.allSources'), value: '' },
{ label: t('knowledgeBase.sourceUpload'), value: 'web' },
{ label: t('knowledgeBase.sourceUrl'), value: 'url' },
{ label: t('knowledgeBase.sourceManual'), value: 'manual' },
{ label: t('knowledgeBase.sourceApi'), value: 'api' },
{ label: t('knowledgeBase.sourceBrowserExtension'), value: 'browser_extension' },
{ label: t('knowledgeBase.channelFeishu'), value: 'feishu' },
{ label: t('knowledgeBase.channelNotion'), value: 'notion' },
{ label: t('knowledgeBase.channelYuque'), value: 'yuque' },
{ label: t('knowledgeBase.channelWechat'), value: 'wechat' },
{ label: t('knowledgeBase.channelWecom'), value: 'wecom' },
{ label: t('knowledgeBase.channelDingtalk'), value: 'dingtalk' },
{ label: t('knowledgeBase.channelSlack'), value: 'slack' },
{ label: t('knowledgeBase.channelIm'), value: 'im' },
]);
// Date range as [start, end] in "YYYY-MM-DD" form (t-date-range-picker default).
const updatedTimeRange = ref<string[]>([]);
// Disable any date after today so users cannot filter into the future.
const disableFutureDate = { after: new Date(new Date().setHours(23, 59, 59, 999)) };
const filterParams = computed(() => {
const [start, end] = updatedTimeRange.value || [];
return {
tag_id: selectedTagId.value || undefined,
keyword: docSearchKeyword.value ? docSearchKeyword.value.trim() : undefined,
file_type: selectedFileType.value || undefined,
parse_status: selectedParseStatus.value || undefined,
source: selectedSource.value || undefined,
start_time: start ? `${start} 00:00:00` : undefined,
end_time: end ? `${end} 23:59:59` : undefined,
};
});
type TagInputInstance = ComponentPublicInstance<{ focus: () => void; select: () => void }>; type TagInputInstance = ComponentPublicInstance<{ focus: () => void; select: () => void }>;
const tagDropdownOptions = computed(() => const tagDropdownOptions = computed(() =>
tagList.value.map((tag: any) => ({ tagList.value.map((tag: any) => ({
@@ -419,9 +462,7 @@ const loadKnowledgeFiles = (kbIdValue: string): Promise<void> => {
{ {
page: 1, page: 1,
page_size: pageSize, page_size: pageSize,
tag_id: selectedTagId.value || undefined, ...filterParams.value,
keyword: docSearchKeyword.value ? docSearchKeyword.value.trim() : undefined,
file_type: selectedFileType.value || undefined,
}, },
kbIdValue, kbIdValue,
); );
@@ -763,6 +804,14 @@ watch(selectedFileType, (newVal, oldVal) => {
} }
}); });
// 监听解析状态/来源/更新时间范围筛选变化(与文件类型行为一致)
watch([selectedParseStatus, selectedSource, updatedTimeRange], () => {
if (kbId.value) {
page = 1;
loadKnowledgeFiles(kbId.value);
}
}, { deep: true });
// 监听文件上传事件 // 监听文件上传事件
const handleFileUploaded = (event: CustomEvent) => { const handleFileUploaded = (event: CustomEvent) => {
const uploadedKbId = event.detail.kbId; const uploadedKbId = event.detail.kbId;
@@ -1625,7 +1674,7 @@ const handleScroll = () => {
if (scrollTop + clientHeight >= scrollHeight) { if (scrollTop + clientHeight >= scrollHeight) {
page++; page++;
if (cardList.value.length < total.value && page <= pageNum) { if (cardList.value.length < total.value && page <= pageNum) {
getKnowled({ page, page_size: pageSize, tag_id: selectedTagId.value, keyword: docSearchKeyword.value ? docSearchKeyword.value.trim() : undefined, file_type: selectedFileType.value || undefined }); getKnowled({ page, page_size: pageSize, ...filterParams.value });
} }
} }
} }
@@ -1680,6 +1729,42 @@ const clearSelection = () => {
lastSelectedIndex = -1; lastSelectedIndex = -1;
}; };
// Batch (multi-select) mode mirrors the session list's "批量管理" UX: while off,
// no checkbox is rendered so the title doesn't jitter on hover; while on,
// checkboxes are persistent and clicking a card toggles its selection.
const batchMode = ref(false);
const toggleBatchMode = () => {
batchMode.value = !batchMode.value;
if (!batchMode.value) clearSelection();
};
// "取消选择" / 退出批量管理:清空选择,并退出 grid 视图下的批量模式。
const handleBatchCancel = () => {
clearSelection();
batchMode.value = false;
};
// 切到卡片视图时,如果列表视图里已经勾选过文档,需要自动开启批量管理模式,
// 否则卡片视图默认不渲染 checkbox,会看不到勾选态。
watch(viewMode, (mode) => {
if (mode === 'grid' && selectedIds.value.size > 0) {
batchMode.value = true;
}
});
// Triggered from a card / row "..." menu — match the session-list UX where
// the menu item simply opens batch mode (no auto-selection).
const handleEnterBatchFromCard = (item: any) => {
if (item) item.isMore = false;
moreIndex.value = -1;
clearSelection();
batchMode.value = true;
};
const onCardClick = (item: any) => {
if (batchMode.value) {
onCardGridCheckboxChange(item.id, !selectedIds.value.has(item.id));
} else {
openCardDetails(item);
}
};
const openBatchDeleteDialog = () => { const openBatchDeleteDialog = () => {
if (selectedIds.value.size === 0) return; if (selectedIds.value.size === 0) return;
batchDeleteDialog.value = true; batchDeleteDialog.value = true;
@@ -1695,6 +1780,7 @@ const confirmBatchDelete = async () => {
if (res?.success) { if (res?.success) {
MessagePlugin.success(t('knowledgeBase.batchDeleteSuccess', { count: ids.length })); MessagePlugin.success(t('knowledgeBase.batchDeleteSuccess', { count: ids.length }));
clearSelection(); clearSelection();
batchMode.value = false;
batchDeleteDialog.value = false; batchDeleteDialog.value = false;
page = 1; page = 1;
// 后端将批量删除放入异步队列,立刻拉列表仍可能包含待删项;短轮询直到列表与后端一致或超时 // 后端将批量删除放入异步队列,立刻拉列表仍可能包含待删项;短轮询直到列表与后端一致或超时
@@ -1730,9 +1816,12 @@ const handleListAction = (
}; };
// Clear selection on filter/tag/kb change to avoid acting on hidden items. // Clear selection on filter/tag/kb change to avoid acting on hidden items.
watch([selectedTagId, docSearchKeyword, selectedFileType, kbId], () => { watch(
clearSelection(); [selectedTagId, docSearchKeyword, selectedFileType, selectedParseStatus, selectedSource, updatedTimeRange, kbId],
}); () => {
clearSelection();
},
);
// After cardList reloads: stable keys rely on correct indices for shift-range; clamp anchor index. // After cardList reloads: stable keys rely on correct indices for shift-range; clamp anchor index.
watch(cardList, () => { watch(cardList, () => {
@@ -2130,6 +2219,28 @@ async function createNewSession(value: string): Promise<void> {
class="doc-type-select" class="doc-type-select"
clearable clearable
/> />
<t-select
v-model="selectedParseStatus"
:options="parseStatusOptions"
:placeholder="$t('knowledgeBase.parseStatusFilter')"
class="doc-type-select"
clearable
/>
<t-select
v-model="selectedSource"
:options="sourceOptions"
:placeholder="$t('knowledgeBase.sourceFilter')"
class="doc-type-select"
clearable
/>
<t-date-range-picker
v-model="updatedTimeRange"
:placeholder="[$t('knowledgeBase.updatedTimeFrom'), $t('knowledgeBase.updatedTimeTo')]"
:disable-date="disableFutureDate"
class="doc-date-range"
clearable
allow-input
/>
<div class="doc-view-toggle" role="group" :aria-label="$t('knowledgeBase.viewModeToggle')"> <div class="doc-view-toggle" role="group" :aria-label="$t('knowledgeBase.viewModeToggle')">
<t-tooltip :content="$t('knowledgeBase.viewModeGrid')" placement="top"> <t-tooltip :content="$t('knowledgeBase.viewModeGrid')" placement="top">
<button <button
@@ -2194,10 +2305,10 @@ async function createNewSession(value: string): Promise<void> {
<!-- 现有文档卡片 --> <!-- 现有文档卡片 -->
<div <div
class="knowledge-card" class="knowledge-card"
:class="{ 'is-selected': selectedIds.has(item.id), 'has-selection': selectedIds.size > 0 }" :class="{ 'is-selected': selectedIds.has(item.id), 'batch-mode': batchMode }"
v-for="(item, index) in cardList" v-for="(item, index) in cardList"
:key="item.id" :key="item.id"
@click="openCardDetails(item)" @click="onCardClick(item)"
@mouseenter="onCardMouseEnter($event, item)" @mouseenter="onCardMouseEnter($event, item)"
@mousemove="onCardMouseMove($event)" @mousemove="onCardMouseMove($event)"
@mouseleave="onCardMouseLeave" @mouseleave="onCardMouseLeave"
@@ -2205,9 +2316,8 @@ async function createNewSession(value: string): Promise<void> {
<div class="card-content"> <div class="card-content">
<div class="card-content-nav"> <div class="card-content-nav">
<div <div
v-if="canEdit" v-if="canEdit && batchMode"
class="card-nav-check" class="card-nav-check"
:class="{ active: selectedIds.has(item.id) }"
@click.stop @click.stop
> >
<t-checkbox <t-checkbox
@@ -2255,6 +2365,10 @@ async function createNewSession(value: string): Promise<void> {
<t-icon class="icon" name="swap" /> <t-icon class="icon" name="swap" />
<span>{{ t('knowledgeBase.moveDocument') }}</span> <span>{{ t('knowledgeBase.moveDocument') }}</span>
</div> </div>
<div class="card-menu-item" @click.stop="handleEnterBatchFromCard(item)">
<t-icon class="icon" name="queue" />
<span>{{ t('menu.batchManage') }}</span>
</div>
<div class="card-menu-item danger" @click.stop="delCard(index, item)"> <div class="card-menu-item danger" @click.stop="delCard(index, item)">
<t-icon class="icon" name="delete" /> <t-icon class="icon" name="delete" />
<span>{{ t('knowledgeBase.deleteDocument') }}</span> <span>{{ t('knowledgeBase.deleteDocument') }}</span>
@@ -2442,11 +2556,12 @@ async function createNewSession(value: string): Promise<void> {
</div> </div>
</template> </template>
</div> </div>
<div class="doc-batch-bar-anchor" v-show="selectedIds.size > 0"> <div class="doc-batch-bar-anchor" v-show="batchMode || selectedIds.size > 0">
<DocumentBatchBar <DocumentBatchBar
:count="selectedIds.size" :count="selectedIds.size"
:loading="batchDeleting" :loading="batchDeleting"
@clear="clearSelection" :visible="batchMode || selectedIds.size > 0"
@cancel="handleBatchCancel"
@delete="openBatchDeleteDialog" @delete="openBatchDeleteDialog"
/> />
</div> </div>
@@ -3063,10 +3178,11 @@ async function createNewSession(value: string): Promise<void> {
display: flex; display: flex;
gap: 12px; gap: 12px;
align-items: center; align-items: center;
flex-wrap: wrap;
.doc-search-input { .doc-search-input {
flex: 1; flex: 1 1 220px;
min-width: 0; min-width: 220px;
} }
.doc-type-select { .doc-type-select {
@@ -3074,6 +3190,18 @@ async function createNewSession(value: string): Promise<void> {
flex-shrink: 0; flex-shrink: 0;
} }
.doc-date-range {
width: 280px;
flex-shrink: 0;
// TDesign focuses both the outer popup reference and inner inputs, which
// visually stacks into a "double border" — drop the inner shadow.
:deep(.t-input--focused),
:deep(.t-is-focused) {
box-shadow: none;
}
}
.doc-view-toggle { .doc-view-toggle {
flex-shrink: 0; flex-shrink: 0;
display: inline-flex; display: inline-flex;
@@ -3854,26 +3982,17 @@ async function createNewSession(value: string): Promise<void> {
cursor: pointer; cursor: pointer;
transition: border-color 0.2s ease, box-shadow 0.2s ease, background-color 0.2s ease; transition: border-color 0.2s ease, box-shadow 0.2s ease, background-color 0.2s ease;
/* 默认折叠不占位,悬停/多选/已选时展开,避免非选择态左侧错位 */ /* 仅在批量管理模式下渲染 checkbox,常态下不占位,避免标题在 hover 时右滑 */
.card-nav-check { .card-nav-check {
flex-shrink: 0; flex-shrink: 0;
display: inline-flex; display: inline-flex;
align-items: center; align-items: center;
justify-content: center; justify-content: center;
width: 0; width: 22px;
height: 29px; height: 29px;
margin-right: 0; margin-right: 8px;
opacity: 0;
overflow: hidden;
transition: width 0.2s ease, margin-right 0.2s ease, opacity 0.2s ease;
cursor: pointer; cursor: pointer;
&.active {
width: 22px;
margin-right: 8px;
opacity: 1;
}
.card-select-checkbox { .card-select-checkbox {
margin: 0; margin: 0;
line-height: 0; line-height: 0;
@@ -3900,13 +4019,6 @@ async function createNewSession(value: string): Promise<void> {
} }
} }
&:hover .card-nav-check,
&.has-selection .card-nav-check {
width: 22px;
margin-right: 8px;
opacity: 1;
}
.card-content { .card-content {
flex: 1; flex: 1;
min-height: 0; min-height: 0;
@@ -4,10 +4,13 @@ import { useI18n } from 'vue-i18n';
defineProps<{ defineProps<{
count: number; count: number;
loading?: boolean; loading?: boolean;
// When true the bar stays visible even with 0 selections, so users can exit
// batch mode from here without selecting anything first.
visible?: boolean;
}>(); }>();
const emit = defineEmits<{ const emit = defineEmits<{
(e: 'clear'): void; (e: 'cancel'): void;
(e: 'delete'): void; (e: 'delete'): void;
}>(); }>();
@@ -16,11 +19,22 @@ const { t } = useI18n();
<template> <template>
<transition name="batch-bar-fade"> <transition name="batch-bar-fade">
<div v-if="count > 0" class="doc-batch-bar" role="region" :aria-label="t('knowledgeBase.selectedCount', { count })"> <div
v-if="visible || count > 0"
class="doc-batch-bar"
role="region"
:aria-label="t('knowledgeBase.selectedCount', { count })"
>
<div class="batch-bar-inner"> <div class="batch-bar-inner">
<div class="batch-bar-left"> <div class="batch-bar-left">
<span class="batch-bar-count">{{ t('knowledgeBase.selectedCount', { count }) }}</span> <span class="batch-bar-count">{{ t('knowledgeBase.selectedCount', { count }) }}</span>
<t-button variant="text" theme="default" size="small" class="batch-bar-clear" @click="emit('clear')"> <t-button
variant="text"
theme="default"
size="small"
class="batch-bar-clear"
@click="emit('cancel')"
>
{{ t('knowledgeBase.clearSelection') }} {{ t('knowledgeBase.clearSelection') }}
</t-button> </t-button>
</div> </div>
@@ -29,6 +43,7 @@ const { t } = useI18n();
theme="danger" theme="danger"
variant="outline" variant="outline"
size="small" size="small"
:disabled="count === 0"
:loading="loading" :loading="loading"
@click="emit('delete')" @click="emit('delete')"
> >
+52 -43
View File
@@ -80,64 +80,73 @@ func (r *knowledgeRepository) ListKnowledgeByKnowledgeBaseID(
return knowledges, nil return knowledges, nil
} }
// applyKnowledgeListFilter applies the optional filter dimensions of
// KnowledgeListFilter to a GORM query. Tenant / knowledge base scoping must be
// applied by the caller before invoking this helper.
func applyKnowledgeListFilter(query *gorm.DB, filter types.KnowledgeListFilter) *gorm.DB {
if filter.TagID != "" {
query = query.Where("tag_id = ?", filter.TagID)
}
if filter.Keyword != "" {
escaped := escapeLikeKeyword(filter.Keyword)
query = query.Where("(file_name LIKE ? OR title LIKE ?)", "%"+escaped+"%", "%"+escaped+"%")
}
// FileType and Source share the same special-case routing onto `type` for
// the "manual" / "url" values, so callers can pick either control.
applyTypeOrFileType := func(q *gorm.DB, val string) *gorm.DB {
switch val {
case "":
return q
case "manual", "url":
return q.Where("type = ?", val)
default:
return q.Where("file_type = ?", val)
}
}
query = applyTypeOrFileType(query, filter.FileType)
if filter.Source != "" {
switch filter.Source {
case "manual", "url":
query = query.Where("type = ?", filter.Source)
default:
query = query.Where("channel = ?", filter.Source)
}
}
if filter.ParseStatus != "" {
query = query.Where("parse_status = ?", filter.ParseStatus)
}
if !filter.UpdatedFrom.IsZero() {
query = query.Where("updated_at >= ?", filter.UpdatedFrom)
}
if !filter.UpdatedTo.IsZero() {
query = query.Where("updated_at <= ?", filter.UpdatedTo)
}
return query
}
// ListPagedKnowledgeByKnowledgeBaseID lists all knowledge in a knowledge base with pagination // ListPagedKnowledgeByKnowledgeBaseID lists all knowledge in a knowledge base with pagination
func (r *knowledgeRepository) ListPagedKnowledgeByKnowledgeBaseID( func (r *knowledgeRepository) ListPagedKnowledgeByKnowledgeBaseID(
ctx context.Context, ctx context.Context,
tenantID uint64, tenantID uint64,
kbID string, kbID string,
page *types.Pagination, page *types.Pagination,
tagID string, filter types.KnowledgeListFilter,
keyword string,
fileType string,
) ([]*types.Knowledge, int64, error) { ) ([]*types.Knowledge, int64, error) {
var knowledges []*types.Knowledge var knowledges []*types.Knowledge
var total int64 var total int64
query := r.db.WithContext(ctx).Model(&types.Knowledge{}). scope := func(q *gorm.DB) *gorm.DB {
Where("tenant_id = ? AND knowledge_base_id = ?", tenantID, kbID) return applyKnowledgeListFilter(
if tagID != "" { q.Where("tenant_id = ? AND knowledge_base_id = ?", tenantID, kbID),
query = query.Where("tag_id = ?", tagID) filter,
} )
if keyword != "" {
escaped := escapeLikeKeyword(keyword)
query = query.Where("(file_name LIKE ? OR title LIKE ?)", "%"+escaped+"%", "%"+escaped+"%")
}
if fileType != "" {
if fileType == "manual" {
query = query.Where("type = ?", "manual")
} else if fileType == "url" {
query = query.Where("type = ?", "url")
} else {
query = query.Where("file_type = ?", fileType)
}
} }
// Query total count first if err := scope(r.db.WithContext(ctx).Model(&types.Knowledge{})).Count(&total).Error; err != nil {
if err := query.Count(&total).Error; err != nil {
return nil, 0, err return nil, 0, err
} }
// Then query paginated data if err := scope(r.db.WithContext(ctx)).
dataQuery := r.db.Debug().WithContext(ctx).
Where("tenant_id = ? AND knowledge_base_id = ?", tenantID, kbID)
if tagID != "" {
dataQuery = dataQuery.Where("tag_id = ?", tagID)
}
if keyword != "" {
escaped := escapeLikeKeyword(keyword)
dataQuery = dataQuery.Where("(file_name LIKE ? OR title LIKE ?)", "%"+escaped+"%", "%"+escaped+"%")
}
if fileType != "" {
if fileType == "manual" {
dataQuery = dataQuery.Where("type = ?", "manual")
} else if fileType == "url" {
dataQuery = dataQuery.Where("type = ?", "url")
} else {
dataQuery = dataQuery.Where("file_type = ?", fileType)
}
}
if err := dataQuery.
Order("created_at DESC"). Order("created_at DESC").
Offset(page.Offset()). Offset(page.Offset()).
Limit(page.Limit()). Limit(page.Limit()).
@@ -687,7 +687,7 @@ func (s *agentService) getKnowledgeBaseInfos(ctx context.Context, kbIDs []string
pageResult, err := s.knowledgeService.ListPagedKnowledgeByKnowledgeBaseID(ctx, kbID, &types.Pagination{ pageResult, err := s.knowledgeService.ListPagedKnowledgeByKnowledgeBaseID(ctx, kbID, &types.Pagination{
Page: 1, Page: 1,
PageSize: 10, PageSize: 10,
}, "", "", "") }, types.KnowledgeListFilter{})
if err == nil && pageResult != nil { if err == nil && pageResult != nil {
docCount = int(pageResult.Total) docCount = int(pageResult.Total)
+21 -21
View File
@@ -36,25 +36,25 @@ var (
// knowledgeService implements the knowledge service interface // knowledgeService implements the knowledge service interface
// service 实现知识服务接口 // service 实现知识服务接口
type knowledgeService struct { type knowledgeService struct {
config *config.Config config *config.Config
retrieveEngine interfaces.RetrieveEngineRegistry retrieveEngine interfaces.RetrieveEngineRegistry
repo interfaces.KnowledgeRepository repo interfaces.KnowledgeRepository
kbService interfaces.KnowledgeBaseService kbService interfaces.KnowledgeBaseService
tenantRepo interfaces.TenantRepository tenantRepo interfaces.TenantRepository
tenantService interfaces.TenantService tenantService interfaces.TenantService
documentReader interfaces.DocumentReader documentReader interfaces.DocumentReader
chunkService interfaces.ChunkService chunkService interfaces.ChunkService
chunkRepo interfaces.ChunkRepository chunkRepo interfaces.ChunkRepository
tagRepo interfaces.KnowledgeTagRepository tagRepo interfaces.KnowledgeTagRepository
tagService interfaces.KnowledgeTagService tagService interfaces.KnowledgeTagService
fileSvc interfaces.FileService fileSvc interfaces.FileService
modelService interfaces.ModelService modelService interfaces.ModelService
task interfaces.TaskEnqueuer task interfaces.TaskEnqueuer
graphEngine interfaces.RetrieveGraphRepository graphEngine interfaces.RetrieveGraphRepository
redisClient *redis.Client redisClient *redis.Client
kbShareService interfaces.KBShareService kbShareService interfaces.KBShareService
imageResolver *docparser.ImageResolver imageResolver *docparser.ImageResolver
taskPendingRepo interfaces.TaskPendingOpsRepository taskPendingRepo interfaces.TaskPendingOpsRepository
// In-memory fallbacks for Lite mode (no Redis) // In-memory fallbacks for Lite mode (no Redis)
memFAQProgress sync.Map // taskID -> *types.FAQImportProgress memFAQProgress sync.Map // taskID -> *types.FAQImportProgress
@@ -208,10 +208,10 @@ func (s *knowledgeService) ListKnowledgeByKnowledgeBaseID(ctx context.Context,
// ListPagedKnowledgeByKnowledgeBaseID returns paginated knowledge entries in a knowledge base // ListPagedKnowledgeByKnowledgeBaseID returns paginated knowledge entries in a knowledge base
func (s *knowledgeService) ListPagedKnowledgeByKnowledgeBaseID(ctx context.Context, func (s *knowledgeService) ListPagedKnowledgeByKnowledgeBaseID(ctx context.Context,
kbID string, page *types.Pagination, tagID string, keyword string, fileType string, kbID string, page *types.Pagination, filter types.KnowledgeListFilter,
) (*types.PageResult, error) { ) (*types.PageResult, error) {
knowledges, total, err := s.repo.ListPagedKnowledgeByKnowledgeBaseID(ctx, knowledges, total, err := s.repo.ListPagedKnowledgeByKnowledgeBaseID(ctx,
ctx.Value(types.TenantIDContextKey).(uint64), kbID, page, tagID, keyword, fileType) ctx.Value(types.TenantIDContextKey).(uint64), kbID, page, filter)
if err != nil { if err != nil {
return nil, err return nil, err
} }
+3 -3
View File
@@ -250,7 +250,7 @@ func (h *InitializationHandler) UpdateKBConfig(c *gin.Context) {
kbIdStr, &types.Pagination{ kbIdStr, &types.Pagination{
Page: 1, Page: 1,
PageSize: 1, PageSize: 1,
}, "", "", "") }, types.KnowledgeListFilter{})
if err == nil && knowledgeList != nil && knowledgeList.Total > 0 { if err == nil && knowledgeList != nil && knowledgeList.Total > 0 {
logger.Error(ctx, "Cannot change embedding model when files exist") logger.Error(ctx, "Cannot change embedding model when files exist")
c.Error(errors.NewBadRequestError("知识库中已有文件,无法修改Embedding模型")) c.Error(errors.NewBadRequestError("知识库中已有文件,无法修改Embedding模型"))
@@ -363,7 +363,7 @@ func (h *InitializationHandler) UpdateKBConfig(c *gin.Context) {
} }
if oldProvider != provider { if oldProvider != provider {
knowledgeList, err := h.knowledgeService.ListPagedKnowledgeByKnowledgeBaseID(ctx, knowledgeList, err := h.knowledgeService.ListPagedKnowledgeByKnowledgeBaseID(ctx,
kbIdStr, &types.Pagination{Page: 1, PageSize: 1}, "", "", "") kbIdStr, &types.Pagination{Page: 1, PageSize: 1}, types.KnowledgeListFilter{})
if err == nil && knowledgeList != nil && knowledgeList.Total > 0 { if err == nil && knowledgeList != nil && knowledgeList.Total > 0 {
logger.Warn(ctx, "Storage engine changed with existing files, old files may become inaccessible") logger.Warn(ctx, "Storage engine changed with existing files, old files may become inaccessible")
} }
@@ -1341,7 +1341,7 @@ func (h *InitializationHandler) GetCurrentConfigByKB(c *gin.Context) {
kbIdStr, &types.Pagination{ kbIdStr, &types.Pagination{
Page: 1, Page: 1,
PageSize: 1, PageSize: 1,
}, "", "", "") }, types.KnowledgeListFilter{})
hasFiles := err == nil && knowledgeList != nil && knowledgeList.Total > 0 hasFiles := err == nil && knowledgeList != nil && knowledgeList.Total > 0
// 构建配置响应 // 构建配置响应
+59 -11
View File
@@ -538,9 +538,13 @@ func (h *KnowledgeHandler) GetKnowledge(c *gin.Context) {
// @Param id path string true "知识库ID" // @Param id path string true "知识库ID"
// @Param page query int false "页码" // @Param page query int false "页码"
// @Param page_size query int false "每页数量" // @Param page_size query int false "每页数量"
// @Param tag_id query string false "标签ID筛选" // @Param tag_id query string false "标签ID筛选"
// @Param keyword query string false "关键词搜索" // @Param keyword query string false "关键词搜索"
// @Param file_type query string false "文件类型筛选" // @Param file_type query string false "文件类型筛选"
// @Param parse_status query string false "解析状态筛选 (pending/processing/completed/failed)"
// @Param source query string false "来源/渠道筛选 (web/api/feishu/notion/yuque/wechat/...,或 manual/url 按 type 过滤)"
// @Param start_time query string false "更新时间起点,RFC3339 格式"
// @Param end_time query string false "更新时间终点,RFC3339 格式"
// @Success 200 {object} map[string]interface{} "知识列表" // @Success 200 {object} map[string]interface{} "知识列表"
// @Failure 400 {object} errors.AppError "请求参数错误" // @Failure 400 {object} errors.AppError "请求参数错误"
// @Security Bearer // @Security Bearer
@@ -569,24 +573,48 @@ func (h *KnowledgeHandler) ListKnowledge(c *gin.Context) {
return return
} }
tagID := c.Query("tag_id") filter := types.KnowledgeListFilter{
keyword := c.Query("keyword") TagID: c.Query("tag_id"),
fileType := c.Query("file_type") Keyword: c.Query("keyword"),
FileType: c.Query("file_type"),
ParseStatus: c.Query("parse_status"),
Source: c.Query("source"),
}
if raw := c.Query("start_time"); raw != "" {
t, err := parseFilterTime(raw)
if err != nil {
c.Error(errors.NewBadRequestError("invalid start_time: " + err.Error()))
return
}
filter.UpdatedFrom = t
}
if raw := c.Query("end_time"); raw != "" {
t, err := parseFilterTime(raw)
if err != nil {
c.Error(errors.NewBadRequestError("invalid end_time: " + err.Error()))
return
}
filter.UpdatedTo = t
}
logger.Infof( logger.Infof(
ctx, ctx,
"Retrieving knowledge list under knowledge base, knowledge base ID: %s, tag_id: %s, keyword: %s, file_type: %s, page: %d, page size: %d, effectiveTenantID: %d", "Retrieving knowledge list under knowledge base, kb_id=%s tag_id=%s keyword=%s file_type=%s parse_status=%s source=%s start_time=%s end_time=%s page=%d page_size=%d effectiveTenantID=%d",
secutils.SanitizeForLog(kbID), secutils.SanitizeForLog(kbID),
secutils.SanitizeForLog(tagID), secutils.SanitizeForLog(filter.TagID),
secutils.SanitizeForLog(keyword), secutils.SanitizeForLog(filter.Keyword),
secutils.SanitizeForLog(fileType), secutils.SanitizeForLog(filter.FileType),
secutils.SanitizeForLog(filter.ParseStatus),
secutils.SanitizeForLog(filter.Source),
secutils.SanitizeForLog(c.Query("start_time")),
secutils.SanitizeForLog(c.Query("end_time")),
pagination.Page, pagination.Page,
pagination.PageSize, pagination.PageSize,
effectiveTenantID, effectiveTenantID,
) )
// Retrieve paginated knowledge entries // Retrieve paginated knowledge entries
result, err := h.kgService.ListPagedKnowledgeByKnowledgeBaseID(ctx, kbID, &pagination, tagID, keyword, fileType) result, err := h.kgService.ListPagedKnowledgeByKnowledgeBaseID(ctx, kbID, &pagination, filter)
if err != nil { if err != nil {
logger.ErrorWithFields(ctx, err, nil) logger.ErrorWithFields(ctx, err, nil)
c.Error(errors.NewInternalServerError(err.Error())) c.Error(errors.NewInternalServerError(err.Error()))
@@ -1796,6 +1824,26 @@ func resolveAgentAllowedKBIDs(agent *types.CustomAgent) []string {
} }
} }
// parseFilterTime parses a query-string timestamp accepted by knowledge list
// filters. It supports RFC3339, RFC3339 with milliseconds, and the date-only
// "2006-01-02" form (interpreted at start of day in the local timezone).
func parseFilterTime(raw string) (time.Time, error) {
raw = strings.TrimSpace(raw)
if raw == "" {
return time.Time{}, nil
}
layouts := []string{time.RFC3339Nano, time.RFC3339, "2006-01-02 15:04:05", "2006-01-02"}
var lastErr error
for _, layout := range layouts {
if t, err := time.ParseInLocation(layout, raw, time.Local); err == nil {
return t, nil
} else {
lastErr = err
}
}
return time.Time{}, lastErr
}
func sliceContains(ss []string, target string) bool { func sliceContains(ss []string, target string) bool {
for _, s := range ss { for _, s := range ss {
if s == target { if s == target {
+10 -12
View File
@@ -61,17 +61,15 @@ type KnowledgeService interface {
GetKnowledgeBatchWithSharedAccess(ctx context.Context, tenantID uint64, ids []string) ([]*types.Knowledge, error) GetKnowledgeBatchWithSharedAccess(ctx context.Context, tenantID uint64, ids []string) ([]*types.Knowledge, error)
// ListKnowledgeByKnowledgeBaseID lists all knowledge under a knowledge base. // ListKnowledgeByKnowledgeBaseID lists all knowledge under a knowledge base.
ListKnowledgeByKnowledgeBaseID(ctx context.Context, kbID string) ([]*types.Knowledge, error) ListKnowledgeByKnowledgeBaseID(ctx context.Context, kbID string) ([]*types.Knowledge, error)
// ListPagedKnowledgeByKnowledgeBaseID lists all knowledge under a knowledge base with pagination. // ListPagedKnowledgeByKnowledgeBaseID lists all knowledge under a knowledge base
// When tagID is non-empty, results are filtered by tag_id. // with pagination. The filter struct controls optional dimensions (tag, keyword,
// When keyword is non-empty, results are filtered by file_name. // file type, parse status, source channel, updated time range); pass a zero
// When fileType is non-empty, results are filtered by file_type or type. // struct to disable all filters.
ListPagedKnowledgeByKnowledgeBaseID( ListPagedKnowledgeByKnowledgeBaseID(
ctx context.Context, ctx context.Context,
kbID string, kbID string,
page *types.Pagination, page *types.Pagination,
tagID string, filter types.KnowledgeListFilter,
keyword string,
fileType string,
) (*types.PageResult, error) ) (*types.PageResult, error)
// DeleteKnowledge deletes knowledge by ID. // DeleteKnowledge deletes knowledge by ID.
DeleteKnowledge(ctx context.Context, id string) error DeleteKnowledge(ctx context.Context, id string) error
@@ -178,12 +176,12 @@ type KnowledgeRepository interface {
// GetKnowledgeByIDOnly returns knowledge by ID without tenant filter (for permission resolution). // GetKnowledgeByIDOnly returns knowledge by ID without tenant filter (for permission resolution).
GetKnowledgeByIDOnly(ctx context.Context, id string) (*types.Knowledge, error) GetKnowledgeByIDOnly(ctx context.Context, id string) (*types.Knowledge, error)
ListKnowledgeByKnowledgeBaseID(ctx context.Context, tenantID uint64, kbID string) ([]*types.Knowledge, error) ListKnowledgeByKnowledgeBaseID(ctx context.Context, tenantID uint64, kbID string) ([]*types.Knowledge, error)
// ListPagedKnowledgeByKnowledgeBaseID lists all knowledge in a knowledge base with pagination. // ListPagedKnowledgeByKnowledgeBaseID lists all knowledge in a knowledge base
// When tagID is non-empty, results are filtered by tag_id. // with pagination. The filter struct controls optional dimensions (tag, keyword,
// When keyword is non-empty, results are filtered by file_name. // file type, parse status, source channel, updated time range); pass a zero
// When fileType is non-empty, results are filtered by file_type or type. // struct to disable all filters.
ListPagedKnowledgeByKnowledgeBaseID(ctx context.Context, ListPagedKnowledgeByKnowledgeBaseID(ctx context.Context,
tenantID uint64, kbID string, page *types.Pagination, tagID string, keyword string, fileType string, tenantID uint64, kbID string, page *types.Pagination, filter types.KnowledgeListFilter,
) ([]*types.Knowledge, int64, error) ) ([]*types.Knowledge, int64, error)
UpdateKnowledge(ctx context.Context, knowledge *types.Knowledge) error UpdateKnowledge(ctx context.Context, knowledge *types.Knowledge) error
// UpdateKnowledgeBatch updates knowledge items in batch // UpdateKnowledgeBatch updates knowledge items in batch
+21
View File
@@ -67,6 +67,27 @@ const (
ManualKnowledgeStatusPublish = "publish" ManualKnowledgeStatusPublish = "publish"
) )
// KnowledgeListFilter aggregates optional filters for listing knowledge entries
// under a knowledge base. Empty / zero fields mean "no filter on that dimension".
type KnowledgeListFilter struct {
// TagID filters by tag_id when non-empty.
TagID string
// Keyword performs a LIKE match on file_name / title when non-empty.
Keyword string
// FileType filters by file_type, or by type for the special values "manual" / "url".
FileType string
// ParseStatus filters by parse_status when non-empty (e.g. pending, processing, completed, failed).
ParseStatus string
// Source filters by ingestion channel when non-empty (web, api, feishu, notion, wechat, ...).
// The special values "manual" and "url" are routed to the `type` column to match
// FileType semantics, so callers can filter "manually created" / "URL imported" entries.
Source string
// UpdatedFrom, when non-zero, keeps rows with updated_at >= UpdatedFrom.
UpdatedFrom time.Time
// UpdatedTo, when non-zero, keeps rows with updated_at <= UpdatedTo.
UpdatedTo time.Time
}
// Knowledge represents a knowledge entity in the system. // Knowledge represents a knowledge entity in the system.
// It contains metadata about the knowledge source, its processing status, // It contains metadata about the knowledge source, its processing status,
// and references to the physical file if applicable. // and references to the physical file if applicable.