feat(chat): enhance references drawer behavior and citation handling

Implement improvements to the chat references drawer, including a new event for handling panel entry to ensure smooth scrolling to highlighted citations. Update the logic for retrieving references from agent events, allowing for better integration of citation data. Additionally, enhance tests to cover new functionality and ensure correct behavior of the references drawer during interactions.
This commit is contained in:
wizardchen
2026-07-16 22:29:37 +08:00
committed by lyingbug
parent e938a76be4
commit 53a66a6456
7 changed files with 171 additions and 14 deletions
@@ -1,6 +1,6 @@
<template>
<Teleport to="body" :disabled="!useOverlay">
<Transition name="references-panel">
<Transition name="references-panel" @after-enter="handlePanelAfterEnter">
<aside
v-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) return
const key = activeHighlightKey.value
if (!key) return
await 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 = false
expandedKeys.clear()
return
}
void scrollToHighlight()
})
</script>
@@ -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)
})
+2
View File
@@ -3,6 +3,7 @@ import type { GrepChunkResult, GrepKnowledgeResult } from '@/types/tool-results'
export type GrepGroupedRow = {
key: string
knowledge_id: string
knowledge_base_id: string
title: string
is_faq: boolean
chunk_hit_count: number
@@ -26,6 +27,7 @@ export function groupGrepChunkResults(chunkRows: GrepChunkResult[]): GrepGrouped
map.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,
@@ -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/'),
+18
View File
@@ -275,6 +275,8 @@ export function buildReferenceList(
export type ReferenceHighlightTarget = {
url?: string
chunkId?: string
documentTitle?: string
knowledgeBaseId?: string
key?: 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
}
@@ -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 false
referencesDrawer.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,
@@ -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/)
})