Open-source LLM knowledge platform: turn raw documents into a queryable RAG, an autonomous reasoning agent, and a self-maintaining Wiki.
Go agentagenticaichatbotdsh-pluginembeddingsevaluationgenerative-aigolangknowledge-basellmmulti-tenantollamaopenaiquestion-answeringragrerankingsemantic-searchvector-searchwiki
fix(chat): restore citation source navigation and soften highlights
wizardchen0de62b2f8015
diff --git a/frontend/src/assets/theme/theme.css b/frontend/src/assets/theme/theme.cssindex aef4d07cf..c74e894ed 100644--- a/frontend/src/assets/theme/theme.css+++ b/frontend/src/assets/theme/theme.css@@ -217,12 +217,18 @@ select:-webkit-autofill {--app-accent-purple: #9d7cff;}-/* 引用原文定位的高亮:荧光笔黄,和品牌绿的界面元素(表头、选中态)区分开 */+/* 引用原文定位:低饱和薄荷绿,文字轻染色,较大区域用浅底和细描边。 */:root {- --app-source-highlight: #ffd84d;+ --app-source-highlight: #3b9b83;+ --app-source-highlight-bg: color-mix(in srgb, var(--app-source-highlight) 20%, transparent);+ --app-source-highlight-soft-bg: color-mix(in srgb, var(--app-source-highlight) 8%, transparent);+ --app-source-highlight-border: color-mix(in srgb, var(--app-source-highlight) 40%, transparent);}:root[theme-mode="dark"] {- --app-source-highlight: #b58f1c;+ --app-source-highlight: #71c4aa;+ --app-source-highlight-bg: color-mix(in srgb, var(--app-source-highlight) 24%, transparent);+ --app-source-highlight-soft-bg: color-mix(in srgb, var(--app-source-highlight) 10%, transparent);+ --app-source-highlight-border: color-mix(in srgb, var(--app-source-highlight) 48%, transparent);}/* 全局旋转动画:spinner / 刷新图标统一用 `animation: wk-spin 0.8s linear infinite` */diff --git a/frontend/src/components/ChatReferenceSourceView.vue b/frontend/src/components/ChatReferenceSourceView.vueindex 4e3a5bbcf..557102786 100644--- a/frontend/src/components/ChatReferenceSourceView.vue+++ b/frontend/src/components/ChatReferenceSourceView.vue@@ -187,6 +187,8 @@ async function loadChunk(version: number) {imageContext.value = undefinedimageDigest.value = undefinedchunkType.value = props.target.chunkType || ''+ // Document-only cards have no passage to look up or highlight.+ if (!props.target.chunkId) returnlet loadedCurrent = false// Old conversations and agent tool results carry no locators; the chunk@@ -298,7 +300,7 @@ async function load() {return}// A summary speaks for the whole document: open it without hunting for a passage.- if (next === 'file' && chunkType.value !== 'summary') {+ if (next === 'file' && props.target.chunkId && chunkType.value !== 'summary') {locate.value = buildLocate()status.value = locate.value.unavailable ? 'stale' : 'locating'}@@ -420,8 +422,8 @@ watch(.reference-source__quote {margin: 0;padding: 10px 12px;- border-left: 3px solid var(--app-source-highlight);- background: color-mix(in srgb, var(--app-source-highlight) 18%, transparent);+ border-left: 2px solid var(--app-source-highlight-border);+ background: var(--app-source-highlight-soft-bg);font-size: var(--app-text-md);line-height: 1.6;color: var(--td-text-color-primary);diff --git a/frontend/src/components/ChatReferencesDrawer.vue b/frontend/src/components/ChatReferencesDrawer.vueindex 063f9a462..1d1de33c6 100644--- a/frontend/src/components/ChatReferencesDrawer.vue+++ b/frontend/src/components/ChatReferencesDrawer.vue@@ -267,11 +267,11 @@ function savePanelWidths() {}function canOpenSource(item: ReferenceListItem) {- return !props.embeddedMode && item.kind === 'document' && !!item.knowledgeId && !!item.chunkId+ return !props.embeddedMode && item.kind === 'document' && !!item.knowledgeId}function openItemSource(item: ReferenceListItem) {- if (!drawer || !item.knowledgeId || !item.chunkId) return+ if (!drawer || !item.knowledgeId) returndrawer.openSource({chunkId: item.sourceChunkId || item.chunkId,knowledgeId: item.knowledgeId,diff --git a/frontend/src/components/document-preview.vue b/frontend/src/components/document-preview.vueindex 8663be955..3c4a77927 100644--- a/frontend/src/components/document-preview.vue+++ b/frontend/src/components/document-preview.vue@@ -1321,8 +1321,8 @@ onUnmounted(() => {position: absolute;pointer-events: none;border-radius: var(--app-radius-xs);- background: color-mix(in srgb, var(--td-success-color) 22%, transparent);- outline: 1px solid color-mix(in srgb, var(--td-success-color) 50%, transparent);+ background: var(--app-source-highlight-soft-bg);+ outline: 1px solid var(--app-source-highlight-border);}.preview-image {@@ -1414,7 +1414,7 @@ onUnmounted(() => {max-width: 480px;padding: 10px 12px;border-radius: @border-radius;- background: color-mix(in srgb, var(--td-success-color) 10%, transparent);+ background: var(--app-source-highlight-soft-bg);color: @text-primary;&__time {font-size: var(--app-text-sm);@@ -1679,22 +1679,23 @@ html[theme-mode="dark"] {/* Citation highlights live outside the scoped block: they apply to DOM thatthird-party renderers (docx-preview, pptx-preview, SheetJS) create. */::highlight(source-locate) {- background-color: color-mix(in srgb, var(--app-source-highlight) 60%, transparent);+ background-color: var(--app-source-highlight-bg);}mark.source-locate-mark {- background-color: color-mix(in srgb, var(--app-source-highlight) 60%, transparent);+ background-color: var(--app-source-highlight-bg);color: inherit;+ border-radius: var(--app-radius-xs);}.source-locate-block {- background-color: color-mix(in srgb, var(--app-source-highlight) 22%, transparent) !important;- outline: 1px solid var(--app-source-highlight);+ background-color: var(--app-source-highlight-soft-bg) !important;+ outline: 1px solid var(--app-source-highlight-border);outline-offset: 2px;border-radius: var(--app-radius-xs);}tr.source-locate-block > td {- background-color: color-mix(in srgb, var(--app-source-highlight) 45%, transparent) !important;+ background-color: var(--app-source-highlight-soft-bg) !important;}</style>diff --git a/frontend/src/components/source-preview/PdfSourceViewer.vue b/frontend/src/components/source-preview/PdfSourceViewer.vueindex 9b76c0bb0..8e5eadfa5 100644--- a/frontend/src/components/source-preview/PdfSourceViewer.vue+++ b/frontend/src/components/source-preview/PdfSourceViewer.vue@@ -538,16 +538,17 @@ defineExpose({ relocate: () => applyLocate(props.locate) }).pdf-source-mark {position: absolute;border-radius: var(--app-radius-xs);- background: color-mix(in srgb, var(--app-source-highlight) 55%, transparent);+ background: var(--app-source-highlight-bg);mix-blend-mode: multiply;&--box {- outline: 1px solid var(--app-source-highlight);+ background: var(--app-source-highlight-soft-bg);+ outline: 1px solid var(--app-source-highlight-border);}&--page {background: transparent;- outline: 2px solid var(--app-source-highlight);+ outline: 1px solid var(--app-source-highlight-border);mix-blend-mode: normal;}}diff --git a/frontend/src/types/tool-results.ts b/frontend/src/types/tool-results.tsindex 2dac12514..afa1c50e4 100644--- a/frontend/src/types/tool-results.ts+++ b/frontend/src/types/tool-results.ts@@ -299,6 +299,7 @@ export interface GrepResultsData {// Chunk row inside a knowledge_chunks_list payload. `role` / `match_snippet`// are only set by read_document in query mode (in-document search).export interface KnowledgeChunksListChunk {+ id?: string;index?: number;chunk_id?: string;chunk_index?: number;@@ -331,6 +332,9 @@ export interface KnowledgeChunksListDocument {export interface KnowledgeChunksListData {display_type: 'knowledge_chunks_list';knowledge_id?: string;+ knowledge_base_id?: string;+ chunk_ids?: string[];+ source_chunk_id?: string;knowledge_title?: string;total_chunks?: number;fetched_chunks?: number;diff --git a/frontend/src/utils/readDocumentReferences.test.ts b/frontend/src/utils/readDocumentReferences.test.tsnew file mode 100644index 000000000..4045f226e--- /dev/null+++ b/frontend/src/utils/readDocumentReferences.test.ts@@ -0,0 +1,70 @@+import assert from 'node:assert/strict'+import test from 'node:test'+import { readDocumentReferences } from './readDocumentReferences'+import { buildReferenceList, resolveReferenceSource } from './referenceSources'+import type { KnowledgeChunksListData } from '../types/tool-results'++const legacy: KnowledgeChunksListData = {+ display_type: 'knowledge_chunks_list',+ knowledge_id: 'doc-1',+ knowledge_title: 'Proposal.pptx',+ document: { knowledge_id: 'doc-1', file_name: 'Proposal.pptx' },+ fetched_chunks: 14,+ total_chunks: 14,+}+const summary = 'Listed 14/14 chunks from Proposal.pptx (content omitted from history)'+const citation = { chunkId: 'cited-chunk', documentTitle: 'Proposal.pptx', knowledgeBaseId: 'kb-1', anchorText: '一期功能' }++test('legacy compacted read_document resolves the actual citation without a saved KB id', () => {+ const refs = readDocumentReferences(legacy, summary, 'Read document')+ const source = resolveReferenceSource(refs, citation)!+ assert.equal(source.chunkId, 'cited-chunk')+ assert.equal(source.knowledgeId, 'doc-1')+ assert.equal(source.knowledgeBaseId, 'kb-1')+ assert.equal(source.fileName, 'Proposal.pptx')+ assert.equal(source.anchorText, '一期功能')+ assert.equal(source.content, undefined)+})++test('a legacy document card never turns a document ID or summary into a passage', () => {+ const [item] = buildReferenceList(readDocumentReferences(legacy, summary, 'Read document'))+ assert.equal(item!.knowledgeId, 'doc-1')+ assert.equal(item!.chunkId, undefined)+ assert.deepEqual(item!.chunkIds, [])+ assert.equal(item!.content, undefined)+})++test('compact live and restored results retain every chunk identity and a positioned source', () => {+ const refs = readDocumentReferences({ ...legacy, knowledge_base_id: 'kb-1',+ chunk_ids: ['first-chunk', 'cited-chunk'], source_chunk_id: 'cited-chunk',+ }, '', 'Read document')+ const [item] = buildReferenceList(refs)+ assert.equal(item!.chunkId, 'first-chunk')+ assert.equal(item!.sourceChunkId, 'cited-chunk')+ assert.deepEqual(item!.chunkIds, ['first-chunk', 'cited-chunk'])+ assert.equal(resolveReferenceSource(refs, citation)!.chunkId, 'cited-chunk')+})++test('full tool results preserve chunk identities even without body text', () => {+ const refs = readDocumentReferences({ ...legacy, knowledge_base_id: 'kb-1', chunks: [+ { chunk_id: 'first-chunk', content: 'First passage' },+ { chunk_id: 'cited-chunk' },+ ] }, '', 'Read document')+ assert.deepEqual(buildReferenceList(refs)[0]!.chunkIds, ['first-chunk', 'cited-chunk'])+ assert.equal(resolveReferenceSource(refs, citation)!.chunkId, 'cited-chunk')+})++test('legacy title recovery rejects conflicting KBs and ambiguous documents', () => {+ const refs = readDocumentReferences({ ...legacy, knowledge_base_id: 'other-kb' }, summary, '')+ assert.equal(resolveReferenceSource(refs, citation), null)+ const unknown = readDocumentReferences(legacy, summary, '')+ assert.equal(resolveReferenceSource([...unknown, { ...unknown[0], id: 'doc-2', knowledge_id: 'doc-2' }], citation), null)+ // A known match must not silently win over an unknown, same-titled document.+ assert.equal(resolveReferenceSource([...unknown, { ...unknown[0], id: 'doc-2', knowledge_id: 'doc-2', knowledge_base_id: 'kb-1' }], citation), null)+})++test('FAQ references retain their chunk identity and do not open an original file', () => {+ const refs = readDocumentReferences({ ...legacy, faq_id: 'faq-1', faq_question: 'Question' }, summary, '')+ assert.equal(buildReferenceList(refs)[0]!.chunkId, 'faq-1')+ assert.equal(resolveReferenceSource(refs, { chunkId: 'faq-1' }), null)+})diff --git a/frontend/src/utils/readDocumentReferences.ts b/frontend/src/utils/readDocumentReferences.tsnew file mode 100644index 000000000..963105813--- /dev/null+++ b/frontend/src/utils/readDocumentReferences.ts@@ -0,0 +1,38 @@+import type { KnowledgeChunksListData } from '../types/tool-results'+import { mergeDocumentReferences, type KnowledgeReferenceLike } from './referenceSources'++/** Read results retain citation IDs even when SSE/history omits chunk bodies. */+export function readDocumentReferences(+ data: KnowledgeChunksListData,+ output: string,+ fallbackTitle: string,+): KnowledgeReferenceLike[] {+ const knowledgeId = data.knowledge_id || data.document?.knowledge_id+ const title = data.faq_question || data.knowledge_title || data.document?.title || knowledgeId || fallbackTitle+ const fileName = data.document?.file_name+ if (data.chunks?.length) {+ return mergeDocumentReferences(data.chunks.map((item, index) => ({+ id: item.chunk_id || item.id || knowledgeId,+ knowledge_id: item.knowledge_id || knowledgeId,+ knowledge_title: title,+ knowledge_filename: fileName,+ knowledge_base_id: item.knowledge_base_id || data.knowledge_base_id,+ chunk_index: item.chunk_index ?? item.index ?? index + 1,+ chunk_type: item.chunk_type || (data.faq_question ? 'faq' : undefined),+ content: item.content,+ })))+ }+ if (!knowledgeId && !data.faq_id) return []+ return [{+ // A document ID identifies the card, never a chunk to request from the API.+ id: data.faq_id || knowledgeId,+ chunk_ids: data.chunk_ids,+ source_chunk_id: data.source_chunk_id || undefined,+ knowledge_id: knowledgeId,+ knowledge_title: title,+ knowledge_filename: fileName,+ knowledge_base_id: data.knowledge_base_id,+ chunk_type: data.faq_question ? 'faq' : undefined,+ content: output.includes('omitted from history') ? undefined : output || undefined,+ }]+}diff --git a/frontend/src/utils/referenceSources.ts b/frontend/src/utils/referenceSources.tsindex 4aee2ded8..311ce4230 100644--- a/frontend/src/utils/referenceSources.ts+++ b/frontend/src/utils/referenceSources.ts@@ -170,12 +170,12 @@ function buildWebItem(item: KnowledgeReferenceLike, index: number): ReferenceLis}function buildDocumentItem(item: KnowledgeReferenceLike, index: number): ReferenceListItem {- const chunkId = item.id || `${item.knowledge_id || 'doc'}-${item.chunk_index ?? index}`+ const chunkId = item.id !== item.knowledge_id ? item.id : item.chunk_ids?.[0]const title = item.knowledge_title || item.knowledge_filename || item.knowledge_id || 'Document'const documentKey =item.knowledge_id ||[item.knowledge_base_id, item.knowledge_title || item.knowledge_filename].filter(Boolean).join(':') ||- chunkId+ chunkId || `doc-${index}`return {key: `doc:${documentKey}`,kind: 'document',@@ -222,7 +222,7 @@ export function mergeDocumentReferences(refs: KnowledgeReferenceLike[]): Knowledrefs.forEach((item, index) => {const key = getDocumentGroupKey(item, index)const content = String(item.content || '').trim()- const chunkIds = Array.from(new Set([...(item.chunk_ids || []), ...(item.id ? [item.id] : [])]))+ const chunkIds = Array.from(new Set([...(item.chunk_ids || []), ...(item.id && item.id !== item.knowledge_id ? [item.id] : [])]))const located = item.id && item.source_locators?.length ? item.id : undefinedconst existing = groups.get(key)@@ -343,7 +343,8 @@ export type ReferenceHighlightTarget = {/** A cited chunk to show inside its original document. */export type ReferenceSourceTarget = {- chunkId: string+ /** Absent when opening a document card without a cited passage. */+ chunkId?: stringknowledgeId: stringknowledgeBaseId?: stringtitle?: string@@ -379,7 +380,7 @@ export function resolveReferenceSource(return {chunkId,knowledgeId: ref.knowledge_id,- knowledgeBaseId: ref.knowledge_base_id,+ knowledgeBaseId: ref.knowledge_base_id || target?.knowledgeBaseId,title: ref.knowledge_title,fileName: ref.knowledge_filename,knowledgeSource: ref.knowledge_source,@@ -431,7 +432,9 @@ export function resolveReferenceHighlightKey((item) => item.kind === 'document' && item.title.trim().toLowerCase() === title,)const scoped = target.knowledgeBaseId- ? candidates.filter((item) => item.knowledgeBaseId === target.knowledgeBaseId)+ // Legacy read_document results omitted the KB id. Accept only one+ // candidate; loadChunk still verifies its knowledge_id before locating.+ ? candidates.filter((item) => !item.knowledgeBaseId || item.knowledgeBaseId === target.knowledgeBaseId): candidatesif (scoped.length === 1) return scoped[0]!.key}diff --git a/frontend/src/views/chat/components/AgentStreamDisplay.vue b/frontend/src/views/chat/components/AgentStreamDisplay.vueindex c3aac903a..a9c8697da 100644--- a/frontend/src/views/chat/components/AgentStreamDisplay.vue+++ b/frontend/src/views/chat/components/AgentStreamDisplay.vue@@ -628,6 +628,7 @@</template><script setup lang="ts">+import { readDocumentReferences } from '@/utils/readDocumentReferences';import { isAssistantTurnComplete } from '@/utils/steerStreamFork';import { ref, computed, watch, onMounted, onBeforeUnmount, onUpdated, nextTick } from 'vue';import { useRouter, useRoute } from 'vue-router';@@ -1414,31 +1415,7 @@ function getToolReferenceItems(event: any): KnowledgeReferenceLike[] {}if (toolName === 'read_document' || toolName === 'list_knowledge_chunks' || toolName === 'wiki_read_source_doc') {- const chunks = Array.isArray(toolData.chunks) ? toolData.chunks : [];- if (chunks.length) {- return mergeDocumentReferences(chunks- .filter((item: any) => item?.content)- .map((item: any, index: number) => ({- id: item.chunk_id || item.id || `${toolData.knowledge_id || 'doc'}-${index + 1}`,- knowledge_id: item.knowledge_id || toolData.knowledge_id,- knowledge_title: toolData.faq_question || toolData.knowledge_title || toolData.knowledge_id,- knowledge_base_id: item.knowledge_base_id || toolData.knowledge_base_id,- chunk_index: item.chunk_index ?? item.index ?? index + 1,- chunk_type: item.chunk_type || (toolData.faq_question ? 'faq' : undefined),- content: item.content || '',- })));- }-- const output = cleanToolOutputContent(event.output);- if (!output) return [];- return [{- id: toolData.faq_id || toolData.knowledge_id || event.tool_call_id,- knowledge_id: toolData.knowledge_id,- knowledge_title: toolData.faq_question || toolData.knowledge_title || toolData.knowledge_id || getToolDescription(event),- knowledge_base_id: toolData.knowledge_base_id,- chunk_type: toolData.faq_question ? 'faq' : undefined,- content: output,- }];+ return readDocumentReferences(toolData, cleanToolOutputContent(event.output), getToolDescription(event));}return [];diff --git a/internal/agent/tools/read_document.go b/internal/agent/tools/read_document.goindex 410e9f296..8a6c9ed94 100644--- a/internal/agent/tools/read_document.go+++ b/internal/agent/tools/read_document.go@@ -545,7 +545,13 @@ func (t *ReadDocumentTool) buildData(knowledge *types.Knowledge, total int64, rows []readChunkRow,) map[string]interface{} {formatted := make([]map[string]interface{}, 0, len(rows))+ chunkIDs := make([]string, 0, len(rows))+ sourceChunkID := ""for i, r := range rows {+ chunkIDs = append(chunkIDs, r.chunk.ID)+ if sourceChunkID == "" && len(r.chunk.SourceLocators) > 0 {+ sourceChunkID = r.chunk.ID+ }row := chunkDataMap(i+1, r.chunk)if row["knowledge_id"] == "" {row["knowledge_id"] = knowledge.ID@@ -559,9 +565,13 @@ func (t *ReadDocumentTool) buildData(formatted = append(formatted, row)}return map[string]interface{}{- "display_type": "knowledge_chunks_list",- "knowledge_id": knowledge.ID,- "knowledge_title": strings.TrimSpace(knowledge.Title),+ "display_type": "knowledge_chunks_list",+ "knowledge_id": knowledge.ID,+ "knowledge_base_id": knowledge.KnowledgeBaseID,+ "knowledge_title": strings.TrimSpace(knowledge.Title),+ // Keep citation identities when chunks are omitted from SSE/history.+ "chunk_ids": chunkIDs,+ "source_chunk_id": sourceChunkID,"total_chunks": total,"fetched_chunks": len(formatted),"chunks": formatted,diff --git a/internal/agent/tools/read_document_test.go b/internal/agent/tools/read_document_test.goindex fe113aa8b..76158bb55 100644--- a/internal/agent/tools/read_document_test.go+++ b/internal/agent/tools/read_document_test.go@@ -5,6 +5,7 @@ import ("encoding/json""errors""fmt"+ "reflect""strings""testing"@@ -12,6 +13,43 @@ import ("github.com/Tencent/WeKnora/internal/types/interfaces")+func TestReadDocumentCitationIdentitySurvivesClientAndHistoryCompaction(t *testing.T) {+ knowledge := &types.Knowledge{+ ID: "doc-1", KnowledgeBaseID: "kb-1", Title: "Proposal.pptx", FileName: "Proposal.pptx",+ }+ rows := []readChunkRow{+ {chunk: &types.Chunk{ID: "chunk-1", Content: "First body"}},+ {chunk: &types.Chunk{+ ID: "chunk-2", Content: "Cited body",+ SourceLocators: types.SourceLocators{{Type: types.SourceLocatorSlide, Slide: 8}},+ }},+ }+ data := (&ReadDocumentTool{}).buildData(knowledge, 2, rows)+ result := &types.ToolResult{Success: true, Data: data, Output: "full model-only output"}+ steps := []types.AgentStep{{ToolCalls: []types.ToolCall{{Name: ToolReadDocument, Result: result}}}}+ stored := SanitizeAgentStepsForStorage(steps)[0].ToolCalls[0].Result+ for name, compact := range map[string]map[string]interface{}{+ "live": SanitizeToolResultForClient(ToolReadDocument, result),+ "history": stored.Data,+ } {+ t.Run(name, func(t *testing.T) {+ if compact["knowledge_id"] != "doc-1" || compact["knowledge_base_id"] != "kb-1" ||+ compact["source_chunk_id"] != "chunk-2" {+ t.Fatalf("lost citation provenance: %#v", compact)+ }+ if !reflect.DeepEqual(compact["chunk_ids"], []string{"chunk-1", "chunk-2"}) {+ t.Fatalf("lost cited chunk IDs: %#v", compact["chunk_ids"])+ }+ if _, exists := compact["chunks"]; exists {+ t.Fatal("chunk bodies should still be omitted")+ }+ })+ }+ if len(data["chunks"].([]map[string]interface{})) != 2 || result.Output != "full model-only output" {+ t.Fatal("compaction must not mutate the full model result")+ }+}+// ---- fakes -----------------------------------------------------------------type readDocKnowledgeService struct {