feat: support editing document summaries (#2752)

* feat: support editing document summaries

* fix: address review feedback for manual summary editing

Reset summary edit state when the drawer closes or generation is in
flight, sync summary_status on manual description updates, and add
service tests plus API docs for partial PUT behavior.

* chore: gofmt client/initialization.go for pre-push hook

---------

Co-authored-by: wizardchen <wizardchen@tencent.com>
main
Anky 2026-08-20 14:54:53 +08:00 committed by GitHub
parent 24a96b5590
commit 0eb79c25e4
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
8 changed files with 246 additions and 26 deletions

View File

@ -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).

View File

@ -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": {}
}
```

View File

@ -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`, {});
}

View File

@ -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<MetadataDraftRow[]>([]);
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<typeof setTimeout> | 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 }) => {
<span>{{ $t('knowledgeBase.generatingSummary') }}</span>
</span>
</div>
<t-tooltip v-if="canEditContent" :content="$t('knowledgeBase.regenerateSummary')" placement="top">
<t-button class="icon-action-btn" size="small" variant="text" shape="square"
:loading="summaryRefreshing" @click="refreshSummary">
<template #icon><t-icon name="refresh" size="15px" /></template>
</t-button>
</t-tooltip>
<div v-if="canEditContent && !summaryEditing" class="summary-title-actions">
<t-tooltip v-if="canEditSummary" :content="$t('common.edit')" placement="top">
<t-button class="icon-action-btn" size="small" variant="text" shape="square"
@click="startSummaryEdit">
<template #icon><t-icon name="edit" size="15px" /></template>
</t-button>
</t-tooltip>
<t-tooltip :content="$t('knowledgeBase.regenerateSummary')" placement="top">
<t-button class="icon-action-btn" size="small" variant="text" shape="square"
:loading="summaryRefreshing" @click="refreshSummary">
<template #icon><t-icon name="refresh" size="15px" /></template>
</t-button>
</t-tooltip>
</div>
</div>
<div v-if="details.description" class="summary_wrapper"
<div v-if="summaryEditing" class="summary_editor">
<t-textarea v-model="summaryDraft" :autosize="{ minRows: 4, maxRows: 10 }"
:placeholder="$t('knowledgeBase.noDocumentSummary')" />
<div class="summary_editor_actions">
<t-button size="small" variant="outline" :disabled="summarySaving" @click="cancelSummaryEdit">
{{ $t('common.cancel') }}
</t-button>
<t-button size="small" theme="primary" :loading="summarySaving" @click="saveSummary">
{{ $t('common.save') }}
</t-button>
</div>
</div>
<div v-else-if="details.description" class="summary_wrapper"
:class="{ 'summary_clickable': summaryOverflow || summaryExpanded }"
@click="(summaryOverflow || summaryExpanded) && (summaryExpanded = !summaryExpanded)">
<div ref="summaryRef" :class="['summary_content', { 'summary_collapsed': !summaryExpanded }]">{{
@ -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);

View File

@ -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

View File

@ -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))
}

View File

@ -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)

View File

@ -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.)