diff --git a/client/initialization.go b/client/initialization.go index 3e11578b..e4de9205 100644 --- a/client/initialization.go +++ b/client/initialization.go @@ -26,11 +26,11 @@ type InitializationConfig struct { // CLI. Field tags are snake_case (the CLI envelope convention), remapped from // the server's camelCase. type KBModelConfigView struct { - RetrievalReady bool `json:"retrieval_ready"` // embedding model bound → KB can embed/retrieve - Embedding ModelSlotView `json:"embedding"` - LLM ModelSlotView `json:"llm"` - Rerank RerankSlotView `json:"rerank"` - Multimodal MultimodalSlotView `json:"multimodal"` + RetrievalReady bool `json:"retrieval_ready"` // embedding model bound → KB can embed/retrieve + Embedding ModelSlotView `json:"embedding"` + LLM ModelSlotView `json:"llm"` + Rerank RerankSlotView `json:"rerank"` + Multimodal MultimodalSlotView `json:"multimodal"` } // ModelSlotView is one non-secret model slot (embedding / llm). diff --git a/docs/api/knowledge.md b/docs/api/knowledge.md index 94dc51c7..f0a091c8 100644 --- a/docs/api/knowledge.md +++ b/docs/api/knowledge.md @@ -548,7 +548,9 @@ curl --location 'http://localhost:8080/api/v1/knowledge/4c4e7c1a-09cf-485b-a7b5- ## PUT `/knowledge/:id` - 更新知识 -更新知识条目的元信息(标题/描述/标签等)。请求体为 `Knowledge` 结构,仅服务侧白名单字段会被实际更新。 +部分更新知识条目的元信息。请求体字段均可选;**未传字段保持不变**。显式传入 `"description": ""` 可清空摘要。 + +可更新字段:`title`、`description`、`custom_metadata`。 **请求**: @@ -558,9 +560,18 @@ curl --location --request PUT 'http://localhost:8080/api/v1/knowledge/4c4e7c1a-0 --header 'Content-Type: application/json' \ --data '{ "title": "彗星 - 天文百科", - "description": "彗星条目,已校对", - "tag_id": "tag-00000001", - "enable_status": "enabled" + "description": "彗星条目,已校对" +}' +``` + +清空摘要示例: + +```curl +curl --location --request PUT 'http://localhost:8080/api/v1/knowledge/4c4e7c1a-09cf-485b-a7b5-24b8cdc5acf5' \ +--header 'X-API-Key: sk-xxxxx' \ +--header 'Content-Type: application/json' \ +--data '{ + "description": "" }' ``` @@ -569,7 +580,8 @@ curl --location --request PUT 'http://localhost:8080/api/v1/knowledge/4c4e7c1a-0 ```json { "success": true, - "message": "Knowledge chunk updated successfully" + "message": "Knowledge updated successfully", + "data": {} } ``` diff --git a/frontend/src/api/knowledge-base/index.ts b/frontend/src/api/knowledge-base/index.ts index 323d87c9..d4f70c5f 100644 --- a/frontend/src/api/knowledge-base/index.ts +++ b/frontend/src/api/knowledge-base/index.ts @@ -422,6 +422,10 @@ export function updateKnowledgeMetadata(knowledgeId: string, customMetadata: Rec return put(`/api/v1/knowledge/${knowledgeId}`, { custom_metadata: customMetadata }); } +export function updateKnowledgeSummary(knowledgeId: string, description: string) { + return put(`/api/v1/knowledge/${knowledgeId}`, { description }); +} + export function regenerateKnowledgeSummary(knowledgeId: string) { return post(`/api/v1/knowledge/${knowledgeId}/regenerate-summary`, {}); } diff --git a/frontend/src/components/doc-content.vue b/frontend/src/components/doc-content.vue index 614962fb..5057229a 100644 --- a/frontend/src/components/doc-content.vue +++ b/frontend/src/components/doc-content.vue @@ -11,7 +11,7 @@ import { onMounted, ref, nextTick, onUnmounted, watch, computed } from "vue"; import { downKnowledgeDetails, deleteGeneratedQuestion, getChunkByIdOnly, previewKnowledgeFile, updateDocumentChunk, listChunkRevisions, revertDocumentChunk, updateKnowledgeMetadata, - regenerateKnowledgeSummary, upsertGeneratedQuestion, regenerateGeneratedQuestions, getKnowledgeDetails, + updateKnowledgeSummary, regenerateKnowledgeSummary, upsertGeneratedQuestion, regenerateGeneratedQuestions, getKnowledgeDetails, KNOWLEDGE_CHUNK_PAGE_SIZE, } from "@/api/knowledge-base/index"; import { MessagePlugin } from "tdesign-vue-next"; @@ -52,6 +52,34 @@ const metadataEditing = ref(false); const metadataDraft = ref([]); const metadataSaving = ref(false); const summaryRefreshing = ref(false); +const summaryEditing = ref(false); +const summaryDraft = ref(''); +const summarySaving = ref(false); + +const startSummaryEdit = () => { + summaryDraft.value = props.details?.description || ''; + summaryEditing.value = true; +}; + +const cancelSummaryEdit = () => { + summaryEditing.value = false; + summaryDraft.value = ''; +}; + +const saveSummary = async () => { + summarySaving.value = true; + try { + const description = summaryDraft.value.trim(); + const result: any = await updateKnowledgeSummary(props.details.id, description); + applySummaryState(result?.data?.summary_status, result?.data?.description ?? description); + summaryEditing.value = false; + MessagePlugin.success(t('common.saveSuccess')); + } catch (error: any) { + MessagePlugin.error(error?.message || t('common.saveFailed')); + } finally { + summarySaving.value = false; + } +}; const metadataTypeOptions = computed(() => [ { label: t('knowledgeBase.metadataTypeText'), value: 'text' }, @@ -233,6 +261,7 @@ const applySummaryState = (summaryStatus?: string, description?: string) => { const isSummaryStatusInFlight = (status?: string) => status === 'pending' || status === 'processing'; const summaryStatusRefreshing = computed(() => isSummaryStatusInFlight(props.details?.summary_status)); +const canEditSummary = computed(() => canEditContent.value && !summaryStatusRefreshing.value); let summaryStatusPollTimer: ReturnType | null = null; let summaryStatusPollGeneration = 0; @@ -603,6 +632,7 @@ onMounted(() => { }); watch(() => props.details?.id, () => { + cancelSummaryEdit(); chunkPage.value = 1; loadedChunkPage.value = 1; pendingChunkPage = null; @@ -811,11 +841,19 @@ watch(() => viewMode.value, (mode) => { }, { flush: 'post' }); watch(() => props.visible, (visible) => { - if (visible && (viewMode.value === 'chunks' || viewMode.value === 'merged')) { + if (!visible) { + cancelSummaryEdit(); + } else if (viewMode.value === 'chunks' || viewMode.value === 'merged') { runMarkdownPostRenderPipeline(); } }, { flush: 'post' }); +watch(summaryStatusRefreshing, (refreshing) => { + if (refreshing) { + cancelSummaryEdit(); + } +}); + // 渲染 Mermaid 图表的函数 const renderMermaidDiagrams = async () => { try { @@ -1724,14 +1762,34 @@ const handleChunkPageChange = (pageInfo: { current: number }) => { {{ $t('knowledgeBase.generatingSummary') }} - - - - - +
+ + + + + + + + + + +
-
+ +
+ + {{ $t('common.cancel') }} + + + {{ $t('common.save') }} + +
+
+
{{ @@ -2545,6 +2603,23 @@ const handleChunkPageChange = (pageInfo: { current: number }) => { } } +.summary-title-actions, +.summary_editor_actions { + display: flex; + align-items: center; + gap: 6px; +} + +.summary_editor { + display: flex; + flex-direction: column; + gap: 10px; +} + +.summary_editor_actions { + justify-content: flex-end; +} + .summary_content { padding: 12px; color: var(--td-text-color-primary); diff --git a/internal/application/service/knowledge.go b/internal/application/service/knowledge.go index 590a6b38..7a513913 100644 --- a/internal/application/service/knowledge.go +++ b/internal/application/service/knowledge.go @@ -698,7 +698,14 @@ func (s *knowledgeService) UpdateKnowledge(ctx context.Context, knowledge *types if knowledge.Title != "" { record.Title = knowledge.Title } - if knowledge.Description != "" { + if knowledge.DescriptionSpecified { + record.Description = knowledge.Description + if record.Description != "" { + record.SummaryStatus = types.SummaryStatusCompleted + } else { + record.SummaryStatus = types.SummaryStatusNone + } + } else if knowledge.Description != "" { record.Description = knowledge.Description } metadataChanged := false diff --git a/internal/application/service/knowledge_update_test.go b/internal/application/service/knowledge_update_test.go new file mode 100644 index 00000000..b5662a35 --- /dev/null +++ b/internal/application/service/knowledge_update_test.go @@ -0,0 +1,104 @@ +package service + +import ( + "context" + "testing" + + "github.com/Tencent/WeKnora/internal/types" + "github.com/stretchr/testify/require" +) + +func TestUpdateKnowledgeExplicitEmptyDescriptionClearsSummary(t *testing.T) { + t.Parallel() + repo := &metadataUpdateKnowledgeRepo{knowledge: &types.Knowledge{ + ID: "knowledge-1", + TenantID: 7, + KnowledgeBaseID: "kb-1", + Description: "old summary", + SummaryStatus: types.SummaryStatusCompleted, + }} + service := &knowledgeService{ + repo: repo, kbService: metadataUpdateKBService{}, + } + ctx := context.WithValue(context.Background(), types.TenantIDContextKey, uint64(7)) + + err := service.UpdateKnowledge(ctx, &types.Knowledge{ + ID: "knowledge-1", + DescriptionSpecified: true, + Description: "", + }) + require.NoError(t, err) + require.Empty(t, repo.knowledge.Description) + require.Equal(t, types.SummaryStatusNone, repo.knowledge.SummaryStatus) +} + +func TestUpdateKnowledgeOmittedDescriptionPreservesExisting(t *testing.T) { + t.Parallel() + repo := &metadataUpdateKnowledgeRepo{knowledge: &types.Knowledge{ + ID: "knowledge-1", + TenantID: 7, + KnowledgeBaseID: "kb-1", + Description: "keep me", + SummaryStatus: types.SummaryStatusCompleted, + }} + service := &knowledgeService{ + repo: repo, kbService: metadataUpdateKBService{}, + } + ctx := context.WithValue(context.Background(), types.TenantIDContextKey, uint64(7)) + + err := service.UpdateKnowledge(ctx, &types.Knowledge{ + ID: "knowledge-1", + Title: "new title", + }) + require.NoError(t, err) + require.Equal(t, "new title", repo.knowledge.Title) + require.Equal(t, "keep me", repo.knowledge.Description) + require.Equal(t, types.SummaryStatusCompleted, repo.knowledge.SummaryStatus) +} + +func TestUpdateKnowledgeManualDescriptionSetsCompletedStatus(t *testing.T) { + t.Parallel() + repo := &metadataUpdateKnowledgeRepo{knowledge: &types.Knowledge{ + ID: "knowledge-1", + TenantID: 7, + KnowledgeBaseID: "kb-1", + SummaryStatus: types.SummaryStatusFailed, + }} + service := &knowledgeService{ + repo: repo, kbService: metadataUpdateKBService{}, + } + ctx := context.WithValue(context.Background(), types.TenantIDContextKey, uint64(7)) + + err := service.UpdateKnowledge(ctx, &types.Knowledge{ + ID: "knowledge-1", + DescriptionSpecified: true, + Description: "manual summary", + }) + require.NoError(t, err) + require.Equal(t, "manual summary", repo.knowledge.Description) + require.Equal(t, types.SummaryStatusCompleted, repo.knowledge.SummaryStatus) +} + +func TestUpdateKnowledgeDescriptionOnlyDoesNotTouchMetadata(t *testing.T) { + t.Parallel() + repo := &metadataUpdateKnowledgeRepo{knowledge: &types.Knowledge{ + ID: "knowledge-1", + TenantID: 7, + KnowledgeBaseID: "kb-1", + Description: "old summary", + SummaryStatus: types.SummaryStatusCompleted, + CustomMetadata: types.JSON(`{"region":"Beijing"}`), + }} + service := &knowledgeService{ + repo: repo, kbService: metadataUpdateKBService{}, + } + ctx := context.WithValue(context.Background(), types.TenantIDContextKey, uint64(7)) + + err := service.UpdateKnowledge(ctx, &types.Knowledge{ + ID: "knowledge-1", + DescriptionSpecified: true, + Description: "updated summary", + }) + require.NoError(t, err) + require.JSONEq(t, `{"region":"Beijing"}`, string(repo.knowledge.CustomMetadata)) +} diff --git a/internal/handler/knowledge.go b/internal/handler/knowledge.go index 8bf2fe5a..ae33084c 100644 --- a/internal/handler/knowledge.go +++ b/internal/handler/knowledge.go @@ -1778,14 +1778,22 @@ func (h *KnowledgeHandler) GetKnowledgeBatch(c *gin.Context) { }) } +// UpdateKnowledgeRequest defines the partial-update body for PUT /knowledge/:id. +// Omitted fields are left unchanged; an explicit empty description clears the summary. +type UpdateKnowledgeRequest struct { + Title *string `json:"title"` + Description *string `json:"description"` + CustomMetadata json.RawMessage `json:"custom_metadata"` +} + // UpdateKnowledge godoc // @Summary 更新知识 -// @Description 更新知识条目信息 +// @Description 部分更新知识条目(标题/描述/自定义元数据);未传字段保持不变,显式传空 description 可清空摘要 // @Tags 知识管理 // @Accept json // @Produce json -// @Param id path string true "知识ID" -// @Param request body types.Knowledge true "知识信息" +// @Param id path string true "知识ID" +// @Param request body UpdateKnowledgeRequest true "更新字段(均可选)" // @Success 200 {object} map[string]interface{} "更新成功" // @Failure 400 {object} errors.AppError "请求参数错误" // @Security Bearer @@ -1807,13 +1815,20 @@ func (h *KnowledgeHandler) UpdateKnowledge(c *gin.Context) { return } - var knowledge types.Knowledge - if err := c.ShouldBindJSON(&knowledge); err != nil { + var req UpdateKnowledgeRequest + if err := c.ShouldBindJSON(&req); err != nil { logger.Error(ctx, "Failed to parse request parameters", err) c.Error(errors.NewBadRequestError(err.Error())) return } - knowledge.ID = id + knowledge := types.Knowledge{ID: id, CustomMetadata: types.JSON(req.CustomMetadata)} + if req.Title != nil { + knowledge.Title = *req.Title + } + if req.Description != nil { + knowledge.Description = *req.Description + knowledge.DescriptionSpecified = true + } if err := h.kgService.UpdateKnowledge(effCtx, &knowledge); err != nil { logger.ErrorWithFields(ctx, err, nil) diff --git a/internal/types/knowledge.go b/internal/types/knowledge.go index feb69d38..aeac79bc 100644 --- a/internal/types/knowledge.go +++ b/internal/types/knowledge.go @@ -136,6 +136,9 @@ type Knowledge struct { Title string `json:"title"` // Description of the knowledge Description string `json:"description"` + // DescriptionSpecified distinguishes an explicitly supplied empty description + // from an omitted field in partial update requests. + DescriptionSpecified bool `json:"-" gorm:"-"` // Source of the knowledge (e.g. URL address for url type, "manual" for manual type) Source string `json:"source" gorm:"type:varchar(2048)"` // Channel indicates through which channel the knowledge was ingested (web, api, browser_extension, wechat, etc.)