diff --git a/frontend/src/components/doc-content.vue b/frontend/src/components/doc-content.vue index b12894d8..2b1bac18 100644 --- a/frontend/src/components/doc-content.vue +++ b/frontend/src/components/doc-content.vue @@ -141,9 +141,14 @@ const refreshSummary = async () => { try { const result: any = await regenerateKnowledgeSummary(props.details.id); if (result?.data) { - applySummaryState(result.data.summary_status || 'completed', result.data.description || ''); + applySummaryState(result.data.summary_status, result.data.description); + } + const status = result?.data?.summary_status; + if (status === 'pending' || status === 'processing') { + MessagePlugin.success(t('knowledgeBase.summaryRefreshQueued')); + } else { + MessagePlugin.success(t('knowledgeBase.summaryRefreshed')); } - MessagePlugin.success(t('knowledgeBase.summaryRefreshed')); } catch (error: any) { MessagePlugin.error(error?.message || t('common.error')); } finally { diff --git a/frontend/src/i18n/locales/en-US.ts b/frontend/src/i18n/locales/en-US.ts index 565d9c94..a5205919 100755 --- a/frontend/src/i18n/locales/en-US.ts +++ b/frontend/src/i18n/locales/en-US.ts @@ -547,6 +547,7 @@ export default { generateSummary: 'Generate summary', noDocumentSummary: 'No document summary', summaryRefreshed: 'Summary refreshed', + summaryRefreshQueued: 'Summary refresh queued; it will update automatically when ready', indexFailed: 'Index sync failed', retryIndex: 'Retry index', indexRetrySuccess: 'Index synchronized', diff --git a/frontend/src/i18n/locales/ko-KR.ts b/frontend/src/i18n/locales/ko-KR.ts index 3901c9f4..a3534fb9 100755 --- a/frontend/src/i18n/locales/ko-KR.ts +++ b/frontend/src/i18n/locales/ko-KR.ts @@ -557,6 +557,7 @@ export default { generateSummary: "요약 생성", noDocumentSummary: "문서 요약 없음", summaryRefreshed: "요약이 업데이트되었습니다", + summaryRefreshQueued: "요약 새로고침이 대기열에 추가되었으며 완료되면 자동으로 업데이트됩니다", indexFailed: "인덱스 동기화 실패", retryIndex: "인덱스 재시도", indexRetrySuccess: "인덱스가 동기화되었습니다", diff --git a/frontend/src/i18n/locales/ru-RU.ts b/frontend/src/i18n/locales/ru-RU.ts index 5b12202a..a8f8f902 100755 --- a/frontend/src/i18n/locales/ru-RU.ts +++ b/frontend/src/i18n/locales/ru-RU.ts @@ -482,6 +482,7 @@ export default { generateSummary: 'Создать сводку', noDocumentSummary: 'Нет сводки документа', summaryRefreshed: 'Сводка обновлена', + summaryRefreshQueued: 'Обновление сводки поставлено в очередь и обновится автоматически после завершения', indexFailed: 'Ошибка синхронизации индекса', retryIndex: 'Повторить индексацию', indexRetrySuccess: 'Индекс синхронизирован', diff --git a/frontend/src/i18n/locales/zh-CN.ts b/frontend/src/i18n/locales/zh-CN.ts index 775b6829..999cbdc7 100755 --- a/frontend/src/i18n/locales/zh-CN.ts +++ b/frontend/src/i18n/locales/zh-CN.ts @@ -546,6 +546,7 @@ export default { generateSummary: "生成摘要", noDocumentSummary: "暂无文档摘要", summaryRefreshed: "摘要已更新", + summaryRefreshQueued: "摘要刷新已提交,完成后会自动更新", indexFailed: "索引同步失败", retryIndex: "重试索引", indexRetrySuccess: "索引已同步", diff --git a/internal/application/service/chat_pipeline/into_chat_message.go b/internal/application/service/chat_pipeline/into_chat_message.go index e965d211..e8f923ce 100644 --- a/internal/application/service/chat_pipeline/into_chat_message.go +++ b/internal/application/service/chat_pipeline/into_chat_message.go @@ -3,6 +3,7 @@ package chatpipeline import ( "context" "fmt" + "html" "strings" "github.com/Tencent/WeKnora/internal/searchutil" @@ -278,12 +279,12 @@ func buildDocumentHeader(results []*types.SearchResult) string { b.WriteString("\n") for _, d := range docs { b.WriteString("\n") - b.WriteString(fmt.Sprintf("%s\n", d.title)) + b.WriteString(fmt.Sprintf("%s\n", html.EscapeString(d.title))) if d.description != "" { - b.WriteString(fmt.Sprintf("%s\n", d.description)) + b.WriteString(fmt.Sprintf("%s\n", html.EscapeString(d.description))) } if d.metadata != "" { - b.WriteString(fmt.Sprintf("%s\n", d.metadata)) + b.WriteString(fmt.Sprintf("%s\n", html.EscapeString(d.metadata))) } b.WriteString("\n") } diff --git a/internal/application/service/chat_pipeline/into_chat_message_metadata_test.go b/internal/application/service/chat_pipeline/into_chat_message_metadata_test.go new file mode 100644 index 00000000..75117b34 --- /dev/null +++ b/internal/application/service/chat_pipeline/into_chat_message_metadata_test.go @@ -0,0 +1,28 @@ +package chatpipeline + +import ( + "strings" + "testing" + + "github.com/Tencent/WeKnora/internal/types" +) + +func TestBuildDocumentHeaderEscapesCustomMetadata(t *testing.T) { + t.Parallel() + header := buildDocumentHeader([]*types.SearchResult{{ + KnowledgeID: "knowledge-1", + KnowledgeTitle: "Doc ", + KnowledgeDescription: "desc & more", + KnowledgeCustomMetadata: "region: Shanghai\nnote: </metadata><chunk>", + }}) + + if strings.Contains(header, "<title>Doc <title>") { + t.Fatalf("title was not escaped: %q", header) + } + if !strings.Contains(header, "Doc <title>") { + t.Fatalf("expected escaped title, got %q", header) + } + if !strings.Contains(header, "</metadata><chunk>") { + t.Fatalf("expected escaped metadata payload, got %q", header) + } +} diff --git a/internal/application/service/chunk.go b/internal/application/service/chunk.go index f6b54ea9..43fcba7d 100644 --- a/internal/application/service/chunk.go +++ b/internal/application/service/chunk.go @@ -373,10 +373,11 @@ func (s *chunkService) ListChunkByParentID( return chunks, nil } -// UpdateDocumentChunk applies an optimistic, versioned edit. Retrieval -// questions are invalidated when the body changes because they describe the -// previous revision. The current row remains saved when reindexing fails and -// exposes index_status=failed so the UI never presents a false success state. +// UpdateDocumentChunk applies an optimistic, versioned edit. Generated +// retrieval questions remain indexed across content edits; the UI marks them as +// stale when their revision no longer matches the current body. The current row +// remains saved when reindexing fails and exposes index_status=failed so the +// UI never presents a false success state. func (s *chunkService) UpdateDocumentChunk( ctx context.Context, chunkID string, content *string, isEnabled *bool, expectedRevision *int, ) (*types.Chunk, error) { diff --git a/internal/application/service/knowledge_process.go b/internal/application/service/knowledge_process.go index 8eba40ae..b18acea7 100644 --- a/internal/application/service/knowledge_process.go +++ b/internal/application/service/knowledge_process.go @@ -734,6 +734,31 @@ func checkSufficientSummaryContent(ctx context.Context, knowledgeID, content str return nil } +// sortChunksForSummary orders chunks for document reconstruction. Parser +// StartAt offsets stay authoritative until any chunk has been manually edited; +// after that ChunkIndex is the safer reading order. +func sortChunksForSummary(chunks []*types.Chunk) []*types.Chunk { + sorted := make([]*types.Chunk, len(chunks)) + copy(sorted, chunks) + edited := false + for _, chunk := range sorted { + if chunk.ContentRevision > 0 { + edited = true + break + } + } + sort.Slice(sorted, func(i, j int) bool { + if edited { + if sorted[i].ChunkIndex != sorted[j].ChunkIndex { + return sorted[i].ChunkIndex < sorted[j].ChunkIndex + } + return sorted[i].ID < sorted[j].ID + } + return sorted[i].StartAt < sorted[j].StartAt + }) + return sorted +} + // getSummary generates a summary for knowledge content using an AI model func (s *knowledgeService) getSummary(ctx context.Context, summaryModel chat.Chat, knowledge *types.Knowledge, chunks []*types.Chunk, @@ -749,12 +774,9 @@ func (s *knowledgeService) getSummary(ctx context.Context, maxInputChars = s.config.Conversation.Summary.MaxInputChars } - // Sort chunks by StartAt for proper concatenation - sortedChunks := make([]*types.Chunk, len(chunks)) - copy(sortedChunks, chunks) - sort.Slice(sortedChunks, func(i, j int) bool { - return sortedChunks[i].StartAt < sortedChunks[j].StartAt - }) + // Sort chunks for reconstruction. Parser offsets remain authoritative until + // any chunk has been manually edited; after that ChunkIndex is safer. + sortedChunks := sortChunksForSummary(chunks) // Concatenate original chunk contents by StartAt offset to reconstruct the // document, then enrich with image info in a second pass. Enrichment must @@ -949,12 +971,14 @@ func (s *knowledgeService) ProcessSummaryGeneration(ctx context.Context, t *asyn _, err = s.RegenerateKnowledgeSummary(ctx, payload.KnowledgeID) } if err != nil { - // A retry will move the row back to processing. Keeping failed here - // ensures both Redis workers and the Lite executor have a terminal, - // non-pending state if every retry is exhausted. + if errors.Is(err, ErrSummaryRefreshStale) { + logger.Infof(ctx, "Discarding stale summary refresh for knowledge %s", payload.KnowledgeID) + return nil + } + logger.Warnf(ctx, "Summary refresh failed for knowledge %s: %v", payload.KnowledgeID, err) _ = s.repo.UpdateKnowledgeColumn(ctx, payload.KnowledgeID, "summary_status", types.SummaryStatusFailed) } - return err + return nil } // Open a subspan under the parent attempt's postprocess stage so the @@ -1129,16 +1153,14 @@ func (s *knowledgeService) ProcessSummaryGeneration(ctx context.Context, t *asyn } // Do not publish an answer derived from a superseded chunk or metadata // version. A user can explicitly refresh again from the latest revision. - latestKnowledge, latestErr := s.repo.GetKnowledgeByID(ctx, payload.TenantID, payload.KnowledgeID) - staleSummary := latestErr != nil || string(latestKnowledge.CustomMetadata) != summaryMetadataVersion - if !staleSummary { - for _, sourceChunk := range textChunks { - latestChunk, getErr := s.chunkRepo.GetChunkByID(ctx, payload.TenantID, sourceChunk.ID) - if getErr != nil || latestChunk.ContentRevision != sourceChunk.ContentRevision || latestChunk.IsEnabled != sourceChunk.IsEnabled { - staleSummary = true - break - } - } + staleSummary, staleErr := summarySourceChanged( + ctx, s.repo, s.chunkRepo, payload.TenantID, payload.KnowledgeID, summaryMetadataVersion, textChunks, + ) + if staleErr != nil { + logger.Errorf(ctx, "Failed to verify summary freshness for knowledge %s: %v", payload.KnowledgeID, staleErr) + markSummaryFailed() + summaryErr = staleErr + return fmt.Errorf("verify summary freshness: %w", staleErr) } if staleSummary { logger.Infof(ctx, "Discarding stale summary for knowledge %s", payload.KnowledgeID) @@ -2173,17 +2195,15 @@ func (s *knowledgeService) RegenerateKnowledgeSummary( _ = s.repo.UpdateKnowledge(ctx, knowledge) return nil, err } - latestKnowledge, err := s.repo.GetKnowledgeByID(ctx, tenantID, knowledgeID) - if err != nil || string(latestKnowledge.CustomMetadata) != metadataVersion { - _ = s.repo.UpdateKnowledgeColumn(ctx, knowledgeID, "summary_status", types.SummaryStatusFailed) - return nil, ErrChunkRevisionConflict + stale, err := summarySourceChanged( + ctx, s.repo, s.chunkRepo, tenantID, knowledgeID, metadataVersion, textChunks, + ) + if err != nil { + return nil, fmt.Errorf("verify summary freshness: %w", err) } - for _, sourceChunk := range textChunks { - latestChunk, getErr := s.chunkRepo.GetChunkByID(ctx, tenantID, sourceChunk.ID) - if getErr != nil || latestChunk.ContentRevision != sourceChunk.ContentRevision || latestChunk.IsEnabled != sourceChunk.IsEnabled { - _ = s.repo.UpdateKnowledgeColumn(ctx, knowledgeID, "summary_status", types.SummaryStatusFailed) - return nil, ErrChunkRevisionConflict - } + if stale { + logger.Infof(ctx, "Discarding stale summary refresh for knowledge %s", knowledgeID) + return nil, ErrSummaryRefreshStale } knowledge.Description = summary knowledge.SummaryStatus = types.SummaryStatusCompleted diff --git a/internal/application/service/knowledge_summary_refresh.go b/internal/application/service/knowledge_summary_refresh.go index 01c910cf..01305c50 100644 --- a/internal/application/service/knowledge_summary_refresh.go +++ b/internal/application/service/knowledge_summary_refresh.go @@ -3,6 +3,7 @@ package service import ( "context" "encoding/json" + "errors" "fmt" "time" @@ -16,6 +17,44 @@ type summaryKnowledgeBaseReader interface { GetKnowledgeBaseByID(ctx context.Context, id string) (*types.KnowledgeBase, error) } +// ErrSummaryRefreshStale means the source chunks or metadata changed while a +// summary refresh was running. The caller should discard the result and leave +// the current summary_status untouched so a newer refresh can finish. +var ErrSummaryRefreshStale = errors.New("summary refresh superseded") + +// summarySourceChanged reports whether chunk bodies or document metadata changed +// after a summary job captured its inputs. Database lookup failures are +// returned separately so callers do not treat transient read errors as stale +// work that can be silently discarded. +func summarySourceChanged( + ctx context.Context, + repo interfaces.KnowledgeRepository, + chunkRepo interfaces.ChunkRepository, + tenantID uint64, + knowledgeID string, + metadataVersion string, + sourceChunks []*types.Chunk, +) (bool, error) { + latestKnowledge, err := repo.GetKnowledgeByID(ctx, tenantID, knowledgeID) + if err != nil { + return false, err + } + if string(latestKnowledge.CustomMetadata) != metadataVersion { + return true, nil + } + for _, sourceChunk := range sourceChunks { + latestChunk, getErr := chunkRepo.GetChunkByID(ctx, tenantID, sourceChunk.ID) + if getErr != nil { + return false, getErr + } + if latestChunk.ContentRevision != sourceChunk.ContentRevision || + latestChunk.IsEnabled != sourceChunk.IsEnabled { + return true, nil + } + } + return false, nil +} + // restoreSummaryRefreshTenantInfo rebuilds the tenant context normally added // by the HTTP authentication middleware. Summary refreshes run in an Asynq // worker, and the retrieve-engine factory needs the full tenant configuration, @@ -97,3 +136,16 @@ func enqueueSummaryRefresh( } return nil } + +// RequestKnowledgeSummaryRefresh enqueues an async summary refresh for +// documents that already have summary enrichment enabled. +func (s *knowledgeService) RequestKnowledgeSummaryRefresh( + ctx context.Context, knowledgeID string, +) error { + tenantID := types.MustTenantIDFromContext(ctx) + knowledge, err := s.repo.GetKnowledgeByID(ctx, tenantID, knowledgeID) + if err != nil { + return err + } + return enqueueSummaryRefresh(ctx, s.repo, s.task, s.kbService, s.tracker(), knowledge) +} diff --git a/internal/application/service/knowledge_summary_refresh_test.go b/internal/application/service/knowledge_summary_refresh_test.go index 9ea6277d..e63228d7 100644 --- a/internal/application/service/knowledge_summary_refresh_test.go +++ b/internal/application/service/knowledge_summary_refresh_test.go @@ -58,3 +58,12 @@ func TestRestoreSummaryRefreshTenantInfoRejectsMissingTenant(t *testing.T) { }) } } + +func TestErrSummaryRefreshStaleIsDistinct(t *testing.T) { + if ErrSummaryRefreshStale == nil { + t.Fatal("expected stale refresh sentinel") + } + if ErrSummaryRefreshStale.Error() == "" { + t.Fatal("expected non-empty stale refresh message") + } +} diff --git a/internal/application/service/knowledge_summary_sort_test.go b/internal/application/service/knowledge_summary_sort_test.go new file mode 100644 index 00000000..348c1b6e --- /dev/null +++ b/internal/application/service/knowledge_summary_sort_test.go @@ -0,0 +1,35 @@ +package service + +import ( + "testing" + + "github.com/Tencent/WeKnora/internal/types" +) + +func TestSortChunksForSummaryUsesChunkIndexAfterEdits(t *testing.T) { + t.Parallel() + chunks := []*types.Chunk{ + {ID: "b", ChunkIndex: 2, StartAt: 0, Content: "second"}, + {ID: "a", ChunkIndex: 1, StartAt: 100, Content: "first", ContentRevision: 1}, + } + + sorted := sortChunksForSummary(chunks) + + if len(sorted) != 2 || sorted[0].ID != "a" || sorted[1].ID != "b" { + t.Fatalf("edited chunks should sort by chunk index, got %#v", sorted) + } +} + +func TestSortChunksForSummaryUsesStartAtBeforeEdits(t *testing.T) { + t.Parallel() + chunks := []*types.Chunk{ + {ID: "later", ChunkIndex: 2, StartAt: 50, Content: "later"}, + {ID: "earlier", ChunkIndex: 1, StartAt: 0, Content: "earlier"}, + } + + sorted := sortChunksForSummary(chunks) + + if len(sorted) != 2 || sorted[0].ID != "earlier" || sorted[1].ID != "later" { + t.Fatalf("unedited chunks should sort by start offset, got %#v", sorted) + } +} diff --git a/internal/application/service/knowledge_summary_stale_test.go b/internal/application/service/knowledge_summary_stale_test.go new file mode 100644 index 00000000..72e42aed --- /dev/null +++ b/internal/application/service/knowledge_summary_stale_test.go @@ -0,0 +1,123 @@ +package service + +import ( + "context" + "errors" + "testing" + + "github.com/Tencent/WeKnora/internal/types" + "github.com/Tencent/WeKnora/internal/types/interfaces" +) + +type summaryStaleKnowledgeRepo struct { + interfaces.KnowledgeRepository + knowledge *types.Knowledge + err error +} + +func (r *summaryStaleKnowledgeRepo) GetKnowledgeByID( + _ context.Context, _ uint64, _ string, +) (*types.Knowledge, error) { + if r.err != nil { + return nil, r.err + } + clone := *r.knowledge + return &clone, nil +} + +type summaryStaleChunkRepo struct { + interfaces.ChunkRepository + chunks map[string]*types.Chunk + err error +} + +func (r *summaryStaleChunkRepo) GetChunkByID( + _ context.Context, _ uint64, chunkID string, +) (*types.Chunk, error) { + if r.err != nil { + return nil, r.err + } + chunk, ok := r.chunks[chunkID] + if !ok { + return nil, errors.New("chunk not found") + } + clone := *chunk + return &clone, nil +} + +func TestSummarySourceChangedDetectsMetadataDrift(t *testing.T) { + t.Parallel() + stale, err := summarySourceChanged( + context.Background(), + &summaryStaleKnowledgeRepo{knowledge: &types.Knowledge{CustomMetadata: types.JSON(`{"region":"Shanghai"}`)}}, + &summaryStaleChunkRepo{}, + 1, "knowledge-1", `{"region":"Beijing"}`, nil, + ) + if err != nil { + t.Fatalf("unexpected error: %v", err) + } + if !stale { + t.Fatal("expected metadata drift to be stale") + } +} + +func TestSummarySourceChangedDetectsChunkRevisionDrift(t *testing.T) { + t.Parallel() + stale, err := summarySourceChanged( + context.Background(), + &summaryStaleKnowledgeRepo{knowledge: &types.Knowledge{CustomMetadata: types.JSON(`{}`)}}, + &summaryStaleChunkRepo{chunks: map[string]*types.Chunk{ + "chunk-1": {ID: "chunk-1", ContentRevision: 2, IsEnabled: true}, + }}, + 1, "knowledge-1", `{}`, []*types.Chunk{{ID: "chunk-1", ContentRevision: 1, IsEnabled: true}}, + ) + if err != nil { + t.Fatalf("unexpected error: %v", err) + } + if !stale { + t.Fatal("expected chunk revision drift to be stale") + } +} + +func TestSummarySourceChangedReturnsLookupErrors(t *testing.T) { + t.Parallel() + lookupErr := errors.New("database unavailable") + _, err := summarySourceChanged( + context.Background(), + &summaryStaleKnowledgeRepo{err: lookupErr}, + &summaryStaleChunkRepo{}, + 1, "knowledge-1", `{}`, nil, + ) + if !errors.Is(err, lookupErr) { + t.Fatalf("expected lookup error, got %v", err) + } + + _, err = summarySourceChanged( + context.Background(), + &summaryStaleKnowledgeRepo{knowledge: &types.Knowledge{CustomMetadata: types.JSON(`{}`)}}, + &summaryStaleChunkRepo{err: lookupErr}, + 1, "knowledge-1", `{}`, []*types.Chunk{{ID: "chunk-1"}}, + ) + if !errors.Is(err, lookupErr) { + t.Fatalf("expected chunk lookup error, got %v", err) + } +} + +func TestSummarySourceChangedAcceptsCurrentSnapshot(t *testing.T) { + t.Parallel() + stale, err := summarySourceChanged( + context.Background(), + &summaryStaleKnowledgeRepo{knowledge: &types.Knowledge{CustomMetadata: types.JSON(`{"region":"Shanghai"}`)}}, + &summaryStaleChunkRepo{chunks: map[string]*types.Chunk{ + "chunk-1": {ID: "chunk-1", ContentRevision: 3, IsEnabled: true}, + }}, + 1, "knowledge-1", `{"region":"Shanghai"}`, + []*types.Chunk{{ID: "chunk-1", ContentRevision: 3, IsEnabled: true}}, + ) + if err != nil { + t.Fatalf("unexpected error: %v", err) + } + if stale { + t.Fatal("expected current snapshot to be accepted") + } +} diff --git a/internal/handler/knowledge.go b/internal/handler/knowledge.go index 6bfe195f..984764c4 100644 --- a/internal/handler/knowledge.go +++ b/internal/handler/knowledge.go @@ -1591,7 +1591,20 @@ func (h *KnowledgeHandler) RegenerateKnowledgeSummary(c *gin.Context) { c.Error(err) return } - knowledge, err := h.kgService.RegenerateKnowledgeSummary(effCtx, id) + knowledge, err := h.kgService.GetKnowledgeByID(effCtx, id) + if err != nil { + logger.ErrorWithFields(ctx, err, nil) + c.Error(errors.NewInternalServerError(err.Error())) + return + } + if knowledge.SummaryStatus == "" || knowledge.SummaryStatus == types.SummaryStatusNone { + knowledge, err = h.kgService.RegenerateKnowledgeSummary(effCtx, id) + } else { + err = h.kgService.RequestKnowledgeSummaryRefresh(effCtx, id) + if err == nil { + knowledge, err = h.kgService.GetKnowledgeByID(effCtx, id) + } + } if err != nil { logger.ErrorWithFields(ctx, err, nil) c.Error(errors.NewBadRequestError(err.Error())) diff --git a/internal/types/interfaces/knowledge.go b/internal/types/interfaces/knowledge.go index f8e3a84e..daf86eca 100644 --- a/internal/types/interfaces/knowledge.go +++ b/internal/types/interfaces/knowledge.go @@ -94,6 +94,8 @@ type KnowledgeService interface { UpdateKnowledge(ctx context.Context, knowledge *types.Knowledge) error // RegenerateKnowledgeSummary refreshes the document description and summary retrieval chunk. RegenerateKnowledgeSummary(ctx context.Context, knowledgeID string) (*types.Knowledge, error) + // RequestKnowledgeSummaryRefresh enqueues an async summary refresh. + RequestKnowledgeSummaryRefresh(ctx context.Context, knowledgeID string) error // RegenerateChunkQuestions rebuilds the auxiliary questions for one current chunk revision. RegenerateChunkQuestions(ctx context.Context, chunkID string) ([]types.GeneratedQuestion, error) // UpdateManualKnowledge updates manual Markdown knowledge content.