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
feat(chat): enhance references drawer behavior and citation handling
wizardchen53a66a64565b
diff --git a/frontend/src/components/ChatReferencesDrawer.vue b/frontend/src/components/ChatReferencesDrawer.vueindex 82b3c39e8..b405e3364 100644--- a/frontend/src/components/ChatReferencesDrawer.vue+++ b/frontend/src/components/ChatReferencesDrawer.vue@@ -1,6 +1,6 @@<template><Teleport to="body" :disabled="!useOverlay">- <Transition name="references-panel">+ <Transition name="references-panel" @after-enter="handlePanelAfterEnter"><asidev-if="visible"class="chat-references-panel"@@ -157,6 +157,7 @@ const listElement = ref<HTMLElement | null>(null)const itemElements = new Map<string, HTMLElement>()const expandedKeys = reactive(new Set<string>())const pointerDownSelectionText = ref('')+const panelEntered = ref(false)const visible = computed(() => drawer?.visible.value ?? false)const references = computed(() => drawer?.references.value ?? [])@@ -267,24 +268,52 @@ function getDocumentHref(item: ReferenceListItem) {}async function scrollToHighlight() {+ if (!panelEntered.value) returnconst key = activeHighlightKey.valueif (!key) returnawait nextTick()const el = itemElements.get(key)- if (!el) return- el.scrollIntoView({ block: 'nearest', behavior: 'smooth' })+ const container = listElement.value+ if (!el || !container) return++ // Keep citation positioning inside the drawer. Native element scrolling may+ // also adjust the outer chat viewport while the fixed panel is still+ // entering, which makes the conversation column visibly jump sideways.+ const itemRect = el.getBoundingClientRect()+ const containerRect = container.getBoundingClientRect()+ let nextTop: number | null = null+ if (itemRect.top < containerRect.top) {+ nextTop = container.scrollTop + itemRect.top - containerRect.top - 8+ } else if (itemRect.bottom > containerRect.bottom) {+ nextTop = container.scrollTop + itemRect.bottom - containerRect.bottom + 8+ }+ if (nextTop !== null) {+ container.scrollTo({ top: Math.max(0, nextTop), behavior: 'smooth' })+ }+}++function handlePanelAfterEnter() {+ panelEntered.value = true+ void scrollToHighlight()}watch(activeHighlightKey, () => {void scrollToHighlight()})+// A user may click the same citation again after manually scrolling the drawer+// away from its card. The resolved key does not change in that case, but the+// highlight target object does, so replay the scroll for every activation.+watch(highlight, () => {+ void scrollToHighlight()+})+watch(visible, (open) => {if (!open) {+ panelEntered.value = falseexpandedKeys.clear()return}- void scrollToHighlight()})</script>diff --git a/frontend/src/utils/grepResultsGroup.test.mjs b/frontend/src/utils/grepResultsGroup.test.mjsindex 11f440888..500319594 100644--- a/frontend/src/utils/grepResultsGroup.test.mjs+++ b/frontend/src/utils/grepResultsGroup.test.mjs@@ -31,6 +31,8 @@ test('groupGrepChunkResults merges chunks from the same document', () => {assert.equal(grouped.length, 2)assert.equal(grouped[0].chunk_hit_count, 2)assert.equal(grouped[0].chunks.length, 2)+ assert.equal(grouped[0].knowledge_base_id, 'kb-1')+ assert.deepEqual(grouped[0].chunks.map((chunk) => chunk.chunk_id), ['chunk-a', 'chunk-b'])assert.equal(grouped[1].chunk_hit_count, 1)})diff --git a/frontend/src/utils/grepResultsGroup.ts b/frontend/src/utils/grepResultsGroup.tsindex 1f75f5bae..6d0ac79e4 100644--- a/frontend/src/utils/grepResultsGroup.ts+++ b/frontend/src/utils/grepResultsGroup.ts@@ -3,6 +3,7 @@ import type { GrepChunkResult, GrepKnowledgeResult } from '@/types/tool-results'export type GrepGroupedRow = {key: stringknowledge_id: string+ knowledge_base_id: stringtitle: stringis_faq: booleanchunk_hit_count: number@@ -26,6 +27,7 @@ export function groupGrepChunkResults(chunkRows: GrepChunkResult[]): GrepGroupedmap.set(key, {key,knowledge_id: result.knowledge_id,+ knowledge_base_id: result.knowledge_base_id,title: result.faq_question || result.knowledge_title || '',is_faq: isFAQ,chunk_hit_count: 0,diff --git a/frontend/src/utils/referenceSources.test.mjs b/frontend/src/utils/referenceSources.test.mjsindex bcbf151f6..73c82c918 100644--- a/frontend/src/utils/referenceSources.test.mjs+++ b/frontend/src/utils/referenceSources.test.mjs@@ -85,6 +85,42 @@ test('resolveReferenceHighlightKey matches web url', () => {assert.equal(key, 'web:https://news.example.com/post')})+test('resolveReferenceHighlightKey matches any chunk merged into a document item', () => {+ const refs = [+ {+ id: 'chunk-1',+ chunk_ids: ['chunk-1', 'chunk-2'],+ knowledge_id: 'doc-1',+ knowledge_title: 'Policy',+ },+ ]++ assert.equal(+ resolveReferenceHighlightKey(refs, { chunkId: 'chunk-2' }),+ 'doc:doc-1',+ )+})++test('resolveReferenceHighlightKey falls back to document title and knowledge base', () => {+ const refs = [+ {+ id: 'available-chunk',+ knowledge_id: 'doc-1',+ knowledge_title: 'Claude Sonnet 5.md',+ knowledge_base_id: 'kb-1',+ },+ ]++ assert.equal(+ resolveReferenceHighlightKey(refs, {+ chunkId: 'cited-chunk-missing-from-legacy-replay',+ documentTitle: 'Claude Sonnet 5.md',+ knowledgeBaseId: 'kb-1',+ }),+ 'doc:doc-1',+ )+})+test('normalizeReferenceUrl trims trailing slash', () => {assert.equal(normalizeReferenceUrl('https://example.com/path/'),diff --git a/frontend/src/utils/referenceSources.ts b/frontend/src/utils/referenceSources.tsindex 50e89fe3c..29a4dc12c 100644--- a/frontend/src/utils/referenceSources.ts+++ b/frontend/src/utils/referenceSources.ts@@ -275,6 +275,8 @@ export function buildReferenceList(export type ReferenceHighlightTarget = {url?: stringchunkId?: string+ documentTitle?: string+ knowledgeBaseId?: stringkey?: string}@@ -308,5 +310,21 @@ export function resolveReferenceHighlightKey(if (hit) return hit.key}+ // Defensive fallback for historical/partially streamed Agent messages whose+ // tool replay payload no longer contains the exact cited chunk. The public+ // citation still carries the full document title and KB id, which identify+ // the same document-level drawer card.+ if (target.documentTitle) {+ const title = target.documentTitle.trim().toLowerCase()+ const candidates = items.filter(+ (item) => item.kind === 'document' && item.title.trim().toLowerCase() === title,+ )+ const scoped = target.knowledgeBaseId+ ? candidates.find((item) => item.knowledgeBaseId === target.knowledgeBaseId)+ : undefined+ if (scoped) return scoped.key+ if (candidates.length === 1) return candidates[0].key+ }+return null}diff --git a/frontend/src/views/chat/components/AgentStreamDisplay.vue b/frontend/src/views/chat/components/AgentStreamDisplay.vueindex 8cfe8389f..8f69906c3 100644--- a/frontend/src/views/chat/components/AgentStreamDisplay.vue+++ b/frontend/src/views/chat/components/AgentStreamDisplay.vue@@ -486,7 +486,7 @@ import { getKnowledgeChunksSummaryHtml } from '@/utils/knowledgeChunksDisplay';import { getAttachmentParsingSummaryHtml } from '@/utils/attachmentParsingDisplay';import { useChatCitationPopover } from '@/composables/useChatCitationPopover';import { useChatReferencesDrawer } from '@/composables/useChatReferencesDrawer';-import type { KnowledgeReferenceLike } from '@/utils/referenceSources';+import type { KnowledgeReferenceLike, ReferenceHighlightTarget } from '@/utils/referenceSources';import { resolveCitationChunkId } from '@/utils/citationMarkdown';import { getWikiPage, type WikiPage } from '@/api/wiki';import { MessagePlugin } from 'tdesign-vue-next';@@ -813,11 +813,29 @@ const {const referencesDrawer = useChatReferencesDrawer();+const getReferencesForDrawer = (+ refsOverride?: KnowledgeReferenceLike[] | null,+): KnowledgeReferenceLike[] => {+ const messageReferences = refsOverride?.length+ ? refsOverride+ : props.session?.knowledge_references;+ if (messageReferences?.length) return messageReferences;++ // Agent answers can already contain citation tags before the aggregated+ // knowledge_references event is emitted (and some restored conversations do+ // not have that aggregate at all). The completed retrieval tool events still+ // carry the same source data, so use them to keep citation clicks in the+ // references drawer instead of falling through to KB-page navigation.+ return (props.session?.agentEventStream || []).flatMap((event) =>+ getToolReferenceItems(event),+ );+};+const openReferencesDrawer = (- highlight?: { url?: string; chunkId?: string },+ highlight?: ReferenceHighlightTarget,refsOverride?: KnowledgeReferenceLike[] | null,) => {- const refs = refsOverride?.length ? refsOverride : props.session?.knowledge_references+ const refs = getReferencesForDrawer(refsOverride)if (!referencesDrawer || !refs?.length) return falsereferencesDrawer.open({references: refs,@@ -887,7 +905,7 @@ const formatToolResultContent = (value: unknown): string => {const isMcpTool = (toolName?: string | null): boolean => String(toolName || '').startsWith('mcp_');-const getToolReferenceItems = (event: any): KnowledgeReferenceLike[] => {+function getToolReferenceItems(event: any): KnowledgeReferenceLike[] {if (!event || event.pending) return [];const toolName = event.tool_name;const toolData = event.tool_data;@@ -969,8 +987,10 @@ const getToolReferenceItems = (event: any): KnowledgeReferenceLike[] => {.filter((group) => group.knowledge_id || group.title).map((group, index) => ({id: group.knowledge_id || group.key,+ chunk_ids: group.chunks.map((chunk) => chunk.chunk_id).filter(Boolean),knowledge_id: group.knowledge_id,knowledge_title: group.title,+ knowledge_base_id: group.knowledge_base_id,chunk_index: index + 1,chunk_type: group.is_faq ? 'faq' : undefined,content: group.chunks.map((chunk) => chunk.content).filter(Boolean).slice(0, 3).join('\n\n') || group.match_snippet || '',@@ -1019,7 +1039,7 @@ const getToolReferenceItems = (event: any): KnowledgeReferenceLike[] => {}return [];-};+}const canOpenToolReferences = (event: any): boolean => getToolReferenceItems(event).length > 0;@@ -1932,9 +1952,13 @@ const onRootClick = (e: Event) => {resolveCitationChunkId(rawChunkId,{ doc: title, kbId },- props.session?.knowledge_references,+ getReferencesForDrawer(),) || rawChunkId;- if (openReferencesDrawer({ chunkId })) {+ if (openReferencesDrawer({+ chunkId,+ documentTitle: title,+ knowledgeBaseId: kbId,+ })) {return;}if (kbId) {@@ -2004,9 +2028,13 @@ const onRootKeydown = (e: KeyboardEvent) => {resolveCitationChunkId(rawChunkId,{ doc: title, kbId },- props.session?.knowledge_references,+ getReferencesForDrawer(),) || rawChunkId;- if (openReferencesDrawer({ chunkId })) {+ if (openReferencesDrawer({+ chunkId,+ documentTitle: title,+ knowledgeBaseId: kbId,+ })) {return;}if (kbId) {@@ -2099,7 +2127,7 @@ const renderAgentMarkdown = (escapeMarkdown,sanitizeHtml: sanitizeMarkdownHTML,streaming: !isConversationDone.value,- knowledgeReferences: props.session?.knowledge_references,+ knowledgeReferences: getReferencesForDrawer(),cachedMermaidSvgHtml: streamingMermaidSvgCache.value,prepareMarkdown: prepareAgentMarkdown,injectCachedMermaidSvg,diff --git a/frontend/src/views/chat/components/chatLinksNewTab.test.mjs b/frontend/src/views/chat/components/chatLinksNewTab.test.mjsindex 8e6ff3ba5..72a95e6b9 100644--- a/frontend/src/views/chat/components/chatLinksNewTab.test.mjs+++ b/frontend/src/views/chat/components/chatLinksNewTab.test.mjs@@ -8,6 +8,7 @@ const referenceDrawer = readFileSync()const legacyReferences = readFileSync(new URL('./docInfo.vue', import.meta.url), 'utf8')const agentStream = readFileSync(new URL('./AgentStreamDisplay.vue', import.meta.url), 'utf8')+const chatView = readFileSync(new URL('../index.vue', import.meta.url), 'utf8')test('reference document links open in a new tab', () => {assert.match(@@ -28,3 +29,44 @@ test('wiki drawer navigation and citation fallbacks open in a new tab', () => {assert.match(agentStream, /window\.open\(href, '_blank', 'noopener,noreferrer'\)/)assert.doesNotMatch(agentStream, /router\.push\(/)})++test('agent citations recover drawer references from retrieval tool events', () => {+ assert.match(+ agentStream,+ /const getReferencesForDrawer = \([\s\S]*?props\.session\?\.knowledge_references[\s\S]*?props\.session\?\.agentEventStream[\s\S]*?getToolReferenceItems\(event\)/,+ )+ assert.match(+ agentStream,+ /const refs = getReferencesForDrawer\(refsOverride\)[\s\S]*?referencesDrawer\.open\(/,+ )+ assert.match(+ agentStream,+ /chunk_ids: group\.chunks\.map\(\(chunk\) => chunk\.chunk_id\)\.filter\(Boolean\)/,+ )+ assert.equal(+ agentStream.match(/knowledgeReferences: getReferencesForDrawer\(\)|getReferencesForDrawer\(\),/g)?.length,+ 3,+ )+ assert.match(+ referenceDrawer,+ /watch\(highlight,[\s\S]*?scrollToHighlight\(\)/,+ )+ assert.equal(+ agentStream.match(/documentTitle: title,[\s\S]*?knowledgeBaseId: kbId,/g)?.length,+ 2,+ )+})++test('citation highlighting waits for drawer entry and only scrolls its own body', () => {+ assert.match(referenceDrawer, /@after-enter="handlePanelAfterEnter"/)+ assert.match(referenceDrawer, /if \(!panelEntered\.value\) return/)+ assert.match(referenceDrawer, /container\.scrollTo\(\{ top: Math\.max\(0, nextTop\), behavior: 'smooth' \}\)/)+ assert.doesNotMatch(referenceDrawer, /el\.scrollIntoView\(/)+})++test('references drawer smoothly shifts the chat area while opening', () => {+ assert.match(referenceDrawer, /\.chat-references-panel \{[\s\S]*?position: fixed;/)+ assert.match(chatView, /'has-references-panel': referencesDrawerVisible/)+ assert.match(chatView, /transition: padding-right 0\.3s cubic-bezier\(0\.22, 0\.61, 0\.36, 1\)/)+ assert.match(chatView, /&\.has-references-panel:not\(\.is-embedded\)[\s\S]*?padding-right:\s*420px/)+})