Skip to content

Open-source LLM knowledge platform: turn raw documents into a queryable RAG, an autonomous reasoning agent, and a self-maintaining Wiki.

feat(quick-qa): add references drawer and polish retrieval source UI

wizardchen3209ed77fde6
diff --git a/frontend/src/components/ChatReferencesDrawer.vue b/frontend/src/components/ChatReferencesDrawer.vue
new file mode 100644
index 000000000..b2f55dbfb
--- /dev/null
+++ b/frontend/src/components/ChatReferencesDrawer.vue
@@ -0,0 +1,580 @@
+<template>
+ <Teleport to="body" :disabled="!useOverlay">
+ <Transition name="references-panel">
+ <aside
+ v-if="visible"
+ class="chat-references-panel"
+ :class="{ 'is-overlay': useOverlay, 'is-embedded': embeddedMode }"
+ role="complementary"
+ :aria-label="panelTitle"
+ >
+ <header class="chat-references-panel__header">
+ <div class="chat-references-panel__heading">
+ <h3 class="chat-references-panel__title">{{ panelTitle }}</h3>
+ <span v-if="totalCount" class="chat-references-panel__count">{{ totalCount }}</span>
+ </div>
+ <button
+ type="button"
+ class="chat-references-panel__close"
+ :aria-label="t('common.close')"
+ @click="close"
+ >
+ <t-icon name="close" />
+ </button>
+ </header>
+
+ <div ref="listElement" class="chat-references-panel__body">
+ <div v-if="sections.length === 0" class="chat-references-panel__empty">
+ {{ t('chat.referencesDrawerEmpty') }}
+ </div>
+
+ <section
+ v-for="section in sections"
+ :key="section.id"
+ class="chat-references-panel__section"
+ >
+ <h4 v-if="sections.length > 1" class="chat-references-panel__section-title">
+ {{ sectionTitle(section.id) }}
+ </h4>
+
+ <article
+ v-for="item in section.items"
+ :key="item.key"
+ :ref="(el) => setItemRef(item.key, el as HTMLElement | null)"
+ class="reference-card"
+ :class="{
+ 'reference-card--web': item.kind === 'web',
+ 'reference-card--document': item.kind === 'document',
+ 'reference-card--tool': item.kind === 'tool',
+ 'is-highlighted': item.key === activeHighlightKey,
+ }"
+ >
+ <component
+ :is="item.kind === 'web' ? 'a' : 'div'"
+ class="reference-card__inner"
+ :class="{ 'is-expandable': item.kind === 'document' && hasMoreContent(item) }"
+ :href="item.kind === 'web' ? item.url : undefined"
+ :target="item.kind === 'web' ? '_blank' : undefined"
+ :rel="item.kind === 'web' ? 'noopener noreferrer' : undefined"
+ :role="item.kind === 'document' && hasMoreContent(item) ? 'button' : undefined"
+ :tabindex="item.kind === 'document' && hasMoreContent(item) ? 0 : undefined"
+ @mousedown="trackContentPointerDown"
+ @click="item.kind === 'document' && hasMoreContent(item) ? toggleDocumentSnippet(item, $event) : undefined"
+ @keydown.enter="item.kind === 'document' && hasMoreContent(item) ? toggleDocumentSnippet(item) : undefined"
+ @keydown.space.prevent="item.kind === 'document' && hasMoreContent(item) ? toggleDocumentSnippet(item) : undefined"
+ >
+ <div class="reference-card__meta">
+ <span class="reference-card__index">{{ item.index }}</span>
+ <img
+ v-if="item.kind === 'web' && item.faviconUrl"
+ class="reference-card__favicon"
+ :src="item.faviconUrl"
+ alt=""
+ loading="lazy"
+ @error="onFaviconError"
+ />
+ <t-icon
+ v-else-if="item.kind === 'document'"
+ name="file"
+ class="reference-card__doc-icon"
+ />
+ <t-icon
+ v-else-if="item.kind === 'tool'"
+ name="tools"
+ class="reference-card__doc-icon"
+ />
+ <span v-if="item.domain" class="reference-card__domain">{{ item.domain }}</span>
+ <span v-else-if="item.kind === 'document'" class="reference-card__domain">
+ {{ t('chat.referencesDrawerDocument') }}
+ </span>
+ <span v-else-if="item.kind === 'tool'" class="reference-card__domain">
+ {{ t('chat.referencesDrawerTool') }}
+ </span>
+ </div>
+
+ <h5 class="reference-card__title">{{ item.title }}</h5>
+ <p v-if="item.snippet && !expandedKeys.has(item.key)" class="reference-card__snippet">
+ {{ item.snippet }}
+ </p>
+ <div v-if="item.kind === 'document' && expandedKeys.has(item.key)" class="reference-card__content">
+ {{ item.content }}
+ </div>
+ <div v-else-if="item.kind === 'tool' && item.content" class="reference-card__content">
+ {{ item.content }}
+ </div>
+
+ </component>
+
+ <div v-if="item.kind === 'document'" class="reference-card__actions">
+ <button v-if="item.knowledgeBaseId && !embeddedMode" type="button" class="reference-card__action" @click="navigateToDocument(item)">
+ <t-icon name="jump" size="14px" />
+ <span>{{ t('chat.navigateToDocument') }}</span>
+ </button>
+ </div>
+ </article>
+ </section>
+ </div>
+ </aside>
+ </Transition>
+ </Teleport>
+
+ <Transition name="references-backdrop">
+ <div
+ v-if="visible && useOverlay"
+ class="chat-references-panel__backdrop"
+ @click="close"
+ />
+ </Transition>
+</template>
+
+<script setup lang="ts">
+import { computed, nextTick, reactive, ref, watch } from 'vue'
+import { useI18n } from 'vue-i18n'
+import { useRouter } from 'vue-router'
+import { useChatReferencesDrawer } from '@/composables/useChatReferencesDrawer'
+import {
+ buildReferenceSections,
+ resolveReferenceHighlightKey,
+ type ReferenceListItem,
+} from '@/utils/referenceSources'
+
+const props = defineProps<{
+ embeddedMode?: boolean
+ overlayBreakpoint?: number
+}>()
+
+const { t } = useI18n()
+const router = useRouter()
+const drawer = useChatReferencesDrawer()
+
+const listElement = ref<HTMLElement | null>(null)
+const itemElements = new Map<string, HTMLElement>()
+const expandedKeys = reactive(new Set<string>())
+const pointerDownSelectionText = ref('')
+
+const visible = computed(() => drawer?.visible.value ?? false)
+const references = computed(() => drawer?.references.value ?? [])
+const highlight = computed(() => drawer?.highlight.value ?? null)
+
+const useOverlay = computed(() => {
+ if (props.embeddedMode) return true
+ if (typeof window === 'undefined') return false
+ return window.innerWidth < (props.overlayBreakpoint ?? 960)
+})
+
+const sections = computed(() => buildReferenceSections(references.value))
+const totalCount = computed(() => sections.value.reduce((sum, section) => sum + section.items.length, 0))
+
+const activeHighlightKey = computed(() =>
+ resolveReferenceHighlightKey(references.value, highlight.value),
+)
+
+const panelTitle = computed(() => {
+ const webCount = sections.value.find((section) => section.id === 'web')?.items.length ?? 0
+ const docCount = sections.value.find((section) => section.id === 'documents')?.items.length ?? 0
+ const toolCount = sections.value.find((section) => section.id === 'tools')?.items.length ?? 0
+ if (toolCount > 0 && webCount === 0 && docCount === 0) {
+ return t('chat.referencesDrawerTitleTools')
+ }
+ if ([webCount, docCount, toolCount].filter((count) => count > 0).length > 1) {
+ return t('chat.referencesDrawerTitleMixed')
+ }
+ if (webCount > 0) {
+ return t('chat.referencesDrawerTitleWeb')
+ }
+ if (docCount > 0) {
+ return t('chat.referencesDrawerTitleDocs')
+ }
+ return t('chat.referencesDrawerTitle')
+})
+
+function sectionTitle(id: 'web' | 'documents' | 'tools') {
+ if (id === 'web') return t('chat.referencesDrawerWebSection')
+ if (id === 'tools') return t('chat.referencesDrawerToolsSection')
+ return t('chat.referencesDrawerDocsSection')
+}
+
+function close() {
+ drawer?.close()
+}
+
+function setItemRef(key: string, el: HTMLElement | null) {
+ if (!el) {
+ itemElements.delete(key)
+ return
+ }
+ itemElements.set(key, el)
+}
+
+function onFaviconError(event: Event) {
+ const img = event.target as HTMLImageElement | null
+ if (img) img.style.display = 'none'
+}
+
+function hasMoreContent(item: ReferenceListItem) {
+ const content = String(item.content || '').trim()
+ const snippet = String(item.snippet || '').replace(/…$/, '').trim()
+ if (!content) return false
+ if (!snippet) return true
+ return content.length > snippet.length && !content.startsWith(snippet)
+ ? true
+ : content.length > snippet.length + 8
+}
+
+function getSelectedText() {
+ if (typeof window === 'undefined') return ''
+ return window.getSelection()?.toString().trim() || ''
+}
+
+function trackContentPointerDown() {
+ pointerDownSelectionText.value = getSelectedText()
+}
+
+function shouldIgnoreContentToggle(event?: MouseEvent) {
+ if (!event) return false
+ const selectedText = getSelectedText()
+ if (selectedText || pointerDownSelectionText.value) {
+ pointerDownSelectionText.value = ''
+ return true
+ }
+ pointerDownSelectionText.value = ''
+ return false
+}
+
+function toggleDocumentSnippet(item: ReferenceListItem, event?: MouseEvent) {
+ if (shouldIgnoreContentToggle(event)) return
+ if (expandedKeys.has(item.key)) {
+ expandedKeys.delete(item.key)
+ return
+ }
+ expandedKeys.add(item.key)
+}
+
+function navigateToDocument(item: ReferenceListItem) {
+ if (!item.knowledgeBaseId) return
+ const query: Record<string, string> = {}
+ if (item.knowledgeId) query.knowledge_id = item.knowledgeId
+ router.push({
+ path: `/platform/knowledge-bases/${item.knowledgeBaseId}`,
+ query,
+ })
+}
+
+async function scrollToHighlight() {
+ const key = activeHighlightKey.value
+ if (!key) return
+ await nextTick()
+ const el = itemElements.get(key)
+ if (!el) return
+ el.scrollIntoView({ block: 'nearest', behavior: 'smooth' })
+}
+
+watch(activeHighlightKey, () => {
+ void scrollToHighlight()
+})
+
+watch(visible, (open) => {
+ if (!open) {
+ expandedKeys.clear()
+ return
+ }
+ void scrollToHighlight()
+})
+</script>
+
+<style scoped lang="less">
+.chat-references-panel__backdrop {
+ position: fixed;
+ inset: 0;
+ background: rgba(0, 0, 0, 0.28);
+ z-index: 1200;
+}
+
+.chat-references-panel {
+ position: fixed;
+ top: 0;
+ right: 0;
+ bottom: 0;
+ width: min(420px, 100vw);
+ z-index: 1201;
+ display: flex;
+ flex-direction: column;
+ background: var(--td-bg-color-container);
+ border-left: 1px solid var(--td-component-stroke);
+ box-shadow: -8px 0 24px rgba(0, 0, 0, 0.06);
+
+ &.is-overlay {
+ box-shadow: -12px 0 32px rgba(0, 0, 0, 0.12);
+ }
+}
+
+.chat-references-panel__header {
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ gap: 12px;
+ padding: 16px 16px 12px;
+ border-bottom: 1px solid var(--td-component-stroke);
+}
+
+.chat-references-panel__heading {
+ display: flex;
+ align-items: center;
+ gap: 10px;
+ min-width: 0;
+}
+
+.chat-references-panel__title {
+ margin: 0;
+ font-size: 15px;
+ font-weight: 600;
+ color: var(--td-text-color-primary);
+ line-height: 1.4;
+}
+
+.chat-references-panel__count {
+ flex-shrink: 0;
+ min-width: 22px;
+ height: 22px;
+ padding: 0 8px;
+ border-radius: 999px;
+ background: var(--td-bg-color-secondarycontainer);
+ color: var(--td-text-color-secondary);
+ font-size: 12px;
+ font-weight: 600;
+ display: inline-flex;
+ align-items: center;
+ justify-content: center;
+}
+
+.chat-references-panel__close {
+ border: 0;
+ background: transparent;
+ color: var(--td-text-color-placeholder);
+ width: 32px;
+ height: 32px;
+ border-radius: 8px;
+ cursor: pointer;
+ display: inline-flex;
+ align-items: center;
+ justify-content: center;
+
+ &:hover {
+ background: var(--td-bg-color-component-hover);
+ color: var(--td-text-color-secondary);
+ }
+}
+
+.chat-references-panel__body {
+ flex: 1;
+ overflow-y: auto;
+ padding: 12px 12px 20px;
+}
+
+.chat-references-panel__empty {
+ padding: 24px 8px;
+ text-align: center;
+ color: var(--td-text-color-placeholder);
+ font-size: 13px;
+}
+
+.chat-references-panel__section + .chat-references-panel__section {
+ margin-top: 16px;
+}
+
+.chat-references-panel__section-title {
+ margin: 0 0 8px;
+ padding: 0 4px;
+ font-size: 12px;
+ font-weight: 600;
+ color: var(--td-text-color-placeholder);
+ text-transform: uppercase;
+ letter-spacing: 0.04em;
+}
+
+.reference-card {
+ border: 1px solid var(--td-component-stroke);
+ border-radius: 12px;
+ background: var(--td-bg-color-container);
+ overflow: hidden;
+ transition: border-color 0.2s ease, box-shadow 0.2s ease, background-color 0.2s ease;
+
+ & + & {
+ margin-top: 10px;
+ }
+
+ &:hover {
+ border-color: color-mix(in srgb, var(--td-text-color-placeholder) 42%, var(--td-component-stroke));
+ box-shadow: 0 4px 14px rgba(0, 0, 0, 0.04);
+ }
+
+ &.is-highlighted {
+ border-color: var(--td-text-color-placeholder);
+ background: var(--td-bg-color-secondarycontainer);
+ box-shadow: none;
+ animation: reference-card-highlight 1s ease;
+ }
+}
+
+@keyframes reference-card-highlight {
+ 0% {
+ background: var(--td-bg-color-component-hover);
+ }
+ 100% {
+ background: var(--td-bg-color-secondarycontainer);
+ }
+}
+
+.reference-card__inner {
+ display: block;
+ padding: 12px 14px;
+ color: inherit;
+ text-decoration: none;
+ transition: background-color 0.16s ease;
+
+ &.is-expandable {
+ cursor: pointer;
+ }
+}
+
+.reference-card--web .reference-card__inner:hover {
+ background: color-mix(in srgb, var(--td-text-color-primary) 3%, var(--td-bg-color-container));
+}
+
+.reference-card--document .reference-card__inner:hover,
+.reference-card--tool .reference-card__inner:hover {
+ background: color-mix(in srgb, var(--td-text-color-primary) 3%, var(--td-bg-color-container));
+}
+
+.reference-card__meta {
+ display: flex;
+ align-items: center;
+ gap: 8px;
+ margin-bottom: 8px;
+ min-width: 0;
+}
+
+.reference-card__index {
+ flex-shrink: 0;
+ width: 20px;
+ height: 20px;
+ border-radius: 999px;
+ background: var(--td-bg-color-secondarycontainer);
+ color: var(--td-text-color-secondary);
+ font-size: 11px;
+ font-weight: 600;
+ display: inline-flex;
+ align-items: center;
+ justify-content: center;
+}
+
+.reference-card__favicon {
+ width: 16px;
+ height: 16px;
+ border-radius: 4px;
+ flex-shrink: 0;
+}
+
+.reference-card__doc-icon {
+ color: var(--td-text-color-placeholder);
+ flex-shrink: 0;
+}
+
+.reference-card__domain {
+ font-size: 12px;
+ color: var(--td-text-color-placeholder);
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+}
+
+.reference-card__title {
+ margin: 0;
+ font-size: 14px;
+ font-weight: 600;
+ line-height: 1.45;
+ color: var(--td-text-color-primary);
+ display: -webkit-box;
+ -webkit-line-clamp: 2;
+ -webkit-box-orient: vertical;
+ overflow: hidden;
+}
+
+.reference-card__snippet {
+ margin: 8px 0 0;
+ font-size: 13px;
+ line-height: 1.55;
+ color: var(--td-text-color-secondary);
+ display: -webkit-box;
+ -webkit-line-clamp: 4;
+ -webkit-box-orient: vertical;
+ overflow: hidden;
+}
+
+.reference-card__content {
+ margin-top: 8px;
+ font-size: 13px;
+ line-height: 1.6;
+ color: var(--td-text-color-secondary);
+ white-space: pre-wrap;
+ word-break: break-word;
+ max-height: 360px;
+ overflow-y: auto;
+}
+
+.reference-card__actions {
+ display: flex;
+ align-items: center;
+ gap: 10px;
+ flex-wrap: wrap;
+ padding: 0 14px 12px;
+}
+
+.reference-card__action {
+ border: 0;
+ background: transparent;
+ color: var(--td-text-color-secondary);
+ font-size: 12px;
+ display: inline-flex;
+ align-items: center;
+ gap: 4px;
+ cursor: pointer;
+ padding: 0;
+
+ &:hover {
+ color: var(--td-text-color-primary);
+ text-decoration: underline;
+ }
+}
+
+.references-panel-enter-active {
+ transition:
+ transform 0.24s cubic-bezier(0.22, 0.61, 0.36, 1),
+ opacity 0.24s cubic-bezier(0.22, 0.61, 0.36, 1);
+}
+
+.references-panel-leave-active {
+ transition:
+ transform 0.3s cubic-bezier(0.22, 0.61, 0.36, 1),
+ opacity 0.3s cubic-bezier(0.22, 0.61, 0.36, 1);
+}
+
+.references-panel-enter-from,
+.references-panel-leave-to {
+ transform: translateX(100%);
+ opacity: 0.6;
+}
+
+.references-backdrop-enter-active {
+ transition: opacity 0.24s ease;
+}
+
+.references-backdrop-leave-active {
+ transition: opacity 0.3s ease;
+}
+
+.references-backdrop-enter-from,
+.references-backdrop-leave-to {
+ opacity: 0;
+}
+</style>
diff --git a/frontend/src/composables/useChatCitationPopover.ts b/frontend/src/composables/useChatCitationPopover.ts
index c9ce30c81..b1142ec34 100644
--- a/frontend/src/composables/useChatCitationPopover.ts
+++ b/frontend/src/composables/useChatCitationPopover.ts
@@ -7,6 +7,7 @@ import {
getCitationChunkCache,
setCitationChunkCache,
} from '@/utils/citationChunkCache'
+import { useChatReferencesDrawer } from '@/composables/useChatReferencesDrawer'
export { clearCitationChunkCache } from '@/utils/citationChunkCache'
@@ -36,6 +37,7 @@ export function useChatCitationPopover(
options?: ChatCitationPopoverOptions,
) {
const { t } = useI18n()
+ const referencesDrawer = useChatReferencesDrawer()
const getCacheScope = () => {
const channelId = options?.embedChannelId?.()
@@ -175,12 +177,42 @@ export function useChatCitationPopover(
scheduleClose()
}
+ const openDrawerForCitation = (payload: { url?: string; chunkId?: string }) => {
+ const refs = options?.getKnowledgeReferences?.() || []
+ if (!referencesDrawer || !refs.length) return false
+ referencesDrawer.open({
+ references: refs,
+ highlight: payload,
+ })
+ return true
+ }
+
const onClick = (e: Event) => {
const target = e.target as HTMLElement
+ const webEl = target.closest?.('.citation-web') as HTMLElement | null
+ if (webEl) {
+ e.preventDefault()
+ e.stopPropagation()
+ const url = webEl.getAttribute('data-url') || ''
+ if (openDrawerForCitation({ url })) return
+ openWeb(webEl)
+ return
+ }
+
const kbEl = target.closest?.('.citation-kb') as HTMLElement | null
if (kbEl) {
e.preventDefault()
e.stopPropagation()
+ const rawChunkId = kbEl.getAttribute('data-chunk-id') || ''
+ const title = kbEl.getAttribute('data-doc') || ''
+ const kbId = kbEl.getAttribute('data-kb-id') || ''
+ const chunkId =
+ resolveCitationChunkId(
+ rawChunkId,
+ { doc: title, kbId },
+ options?.getKnowledgeReferences?.(),
+ ) || rawChunkId
+ if (openDrawerForCitation({ chunkId })) return
void openKb(kbEl)
}
}
diff --git a/frontend/src/composables/useChatReferencesDrawer.ts b/frontend/src/composables/useChatReferencesDrawer.ts
new file mode 100644
index 000000000..72dab0779
--- /dev/null
+++ b/frontend/src/composables/useChatReferencesDrawer.ts
@@ -0,0 +1,92 @@
+import { inject, provide, ref, type InjectionKey, type Ref } from 'vue'
+import type { KnowledgeReferenceLike, ReferenceHighlightTarget } from '@/utils/referenceSources'
+
+export type ChatReferencesDrawerOpenOptions = {
+ references: KnowledgeReferenceLike[]
+ highlight?: ReferenceHighlightTarget | null
+ messageId?: string
+ sourceKey?: string
+}
+
+export type ChatReferencesDrawerContext = {
+ visible: Ref<boolean>
+ references: Ref<KnowledgeReferenceLike[]>
+ highlight: Ref<ReferenceHighlightTarget | null>
+ messageId: Ref<string>
+ sourceKey: Ref<string>
+ open: (options: ChatReferencesDrawerOpenOptions) => void
+ toggle: (options: ChatReferencesDrawerOpenOptions) => boolean
+ close: () => void
+ setHighlight: (highlight: ReferenceHighlightTarget | null) => void
+}
+
+const CHAT_REFERENCES_DRAWER_KEY: InjectionKey<ChatReferencesDrawerContext> = Symbol(
+ 'chatReferencesDrawer',
+)
+
+export function provideChatReferencesDrawer(): ChatReferencesDrawerContext {
+ const visible = ref(false)
+ const references = ref<KnowledgeReferenceLike[]>([])
+ const highlight = ref<ReferenceHighlightTarget | null>(null)
+ const messageId = ref('')
+ const sourceKey = ref('')
+
+ const getFallbackSourceKey = (options: ChatReferencesDrawerOpenOptions) => {
+ if (options.sourceKey) return options.sourceKey
+ if (options.messageId) return `message:${options.messageId}`
+ return options.references
+ .map((item) => item.id || item.knowledge_id || item.knowledge_title || item.metadata?.url || '')
+ .filter(Boolean)
+ .join('|')
+ }
+
+ const open = (options: ChatReferencesDrawerOpenOptions) => {
+ references.value = Array.isArray(options.references) ? options.references : []
+ highlight.value = options.highlight ?? null
+ messageId.value = options.messageId || ''
+ sourceKey.value = getFallbackSourceKey(options)
+ visible.value = true
+ }
+
+ const toggle = (options: ChatReferencesDrawerOpenOptions) => {
+ const nextSourceKey = getFallbackSourceKey(options)
+ if (visible.value && sourceKey.value && sourceKey.value === nextSourceKey) {
+ close()
+ return false
+ }
+ open(options)
+ return true
+ }
+
+ const close = () => {
+ visible.value = false
+ highlight.value = null
+ sourceKey.value = ''
+ }
+
+ const setHighlight = (next: ReferenceHighlightTarget | null) => {
+ highlight.value = next
+ if (next && references.value.length) {
+ visible.value = true
+ }
+ }
+
+ const ctx: ChatReferencesDrawerContext = {
+ visible,
+ references,
+ highlight,
+ messageId,
+ sourceKey,
+ open,
+ toggle,
+ close,
+ setHighlight,
+ }
+
+ provide(CHAT_REFERENCES_DRAWER_KEY, ctx)
+ return ctx
+}
+
+export function useChatReferencesDrawer(): ChatReferencesDrawerContext | null {
+ return inject(CHAT_REFERENCES_DRAWER_KEY, null)
+}
diff --git a/frontend/src/composables/useEmbedCitationPopover.ts b/frontend/src/composables/useEmbedCitationPopover.ts
index fd7a71334..28142e08c 100644
--- a/frontend/src/composables/useEmbedCitationPopover.ts
+++ b/frontend/src/composables/useEmbedCitationPopover.ts
@@ -4,6 +4,12 @@ import {
getCitationChunkCache,
setCitationChunkCache,
} from '@/utils/citationChunkCache'
+import { resolveCitationChunkId, type CitationKnowledgeRef } from '@/utils/citationMarkdown'
+import { useChatReferencesDrawer } from '@/composables/useChatReferencesDrawer'
+
+type EmbedCitationPopoverOptions = {
+ getKnowledgeReferences?: () => CitationKnowledgeRef[] | null | undefined
+}
type FloatState = {
visible: boolean
@@ -21,7 +27,9 @@ export function useEmbedCitationPopover(
rootRef: Ref<HTMLElement | null>,
channelId: MaybeRef<string>,
token: MaybeRef<string>,
+ options?: EmbedCitationPopoverOptions,
) {
+ const referencesDrawer = useChatReferencesDrawer()
const float = ref<FloatState>({
visible: false,
type: 'kb',
@@ -126,12 +134,42 @@ export function useEmbedCitationPopover(
scheduleClose()
}
+ const openDrawerForCitation = (payload: { url?: string; chunkId?: string }) => {
+ const refs = options?.getKnowledgeReferences?.() || []
+ if (!referencesDrawer || !refs.length) return false
+ referencesDrawer.open({
+ references: refs,
+ highlight: payload,
+ })
+ return true
+ }
+
const onClick = (e: Event) => {
const target = e.target as HTMLElement
+ const webEl = target.closest?.('.citation-web') as HTMLElement | null
+ if (webEl) {
+ e.preventDefault()
+ e.stopPropagation()
+ const url = webEl.getAttribute('data-url') || ''
+ if (openDrawerForCitation({ url })) return
+ openWeb(webEl)
+ return
+ }
+
const kbEl = target.closest?.('.citation-kb') as HTMLElement | null
if (kbEl) {
e.preventDefault()
e.stopPropagation()
+ const rawChunkId = kbEl.getAttribute('data-chunk-id') || ''
+ const title = kbEl.getAttribute('data-doc') || ''
+ const kbId = kbEl.getAttribute('data-kb-id') || ''
+ const chunkId =
+ resolveCitationChunkId(
+ rawChunkId,
+ { doc: title, kbId },
+ options?.getKnowledgeReferences?.(),
+ ) || rawChunkId
+ if (openDrawerForCitation({ chunkId })) return
void openKb(kbEl)
return
}
diff --git a/frontend/src/i18n/locales/en-US.ts b/frontend/src/i18n/locales/en-US.ts
index d5bc7f162..dc652652f 100755
--- a/frontend/src/i18n/locales/en-US.ts
+++ b/frontend/src/i18n/locales/en-US.ts
@@ -3058,6 +3058,23 @@ export default {
referencesDocCount: 'Referenced {count} document(s)',
referencesWebCount: 'Referenced {count} web result(s)',
referencesDocAndWebCount: 'Referenced {docCount} document(s) and {webCount} web page(s)',
+ referencesDrawerTitle: 'Sources',
+ referencesDrawerTitleWeb: 'Web sources',
+ referencesDrawerTitleDocs: 'Document sources',
+ referencesDrawerTitleTools: 'Tool results',
+ referencesDrawerTitleMixed: 'Sources',
+ referencesDrawerChipWeb: '{count} web',
+ referencesDrawerChipDocs: '{count} docs',
+ referencesDrawerChipMixed: '{count} sources',
+ referencesDrawerOpenWeb: 'View {count} web',
+ referencesDrawerOpenDocs: 'View {count} docs',
+ referencesDrawerOpenMixed: 'View {count} sources',
+ referencesDrawerWebSection: 'Web',
+ referencesDrawerDocsSection: 'Documents',
+ referencesDrawerToolsSection: 'Tools',
+ referencesDrawerDocument: 'Knowledge document',
+ referencesDrawerTool: 'Tool result',
+ referencesDrawerEmpty: 'No sources available',
referenceChunkCount: '{count} chunk(s)',
fallbackHint: 'No relevant content found in knowledge base. Above is a direct response from the model.',
requestInfoTitle: 'Request info',
diff --git a/frontend/src/i18n/locales/ko-KR.ts b/frontend/src/i18n/locales/ko-KR.ts
index 1bd9eea39..d207705d4 100755
--- a/frontend/src/i18n/locales/ko-KR.ts
+++ b/frontend/src/i18n/locales/ko-KR.ts
@@ -926,6 +926,23 @@ export default {
referencesDocCount: "{count}개 문서 참조",
referencesWebCount: "{count}개 웹 결과 참조",
referencesDocAndWebCount: "{docCount}개 문서와 {webCount}개 웹페이지 참조",
+ referencesDrawerTitle: "참고 출처",
+ referencesDrawerTitleWeb: "웹 출처",
+ referencesDrawerTitleDocs: "문서 출처",
+ referencesDrawerTitleTools: "도구 결과",
+ referencesDrawerTitleMixed: "참고 출처",
+ referencesDrawerChipWeb: "웹 {count}건",
+ referencesDrawerChipDocs: "문서 {count}건",
+ referencesDrawerChipMixed: "출처 {count}건",
+ referencesDrawerOpenWeb: "웹 {count}건 보기",
+ referencesDrawerOpenDocs: "문서 {count}건 보기",
+ referencesDrawerOpenMixed: "출처 {count}건 보기",
+ referencesDrawerWebSection: "웹",
+ referencesDrawerDocsSection: "지식베이스 문서",
+ referencesDrawerToolsSection: "도구",
+ referencesDrawerDocument: "지식베이스 문서",
+ referencesDrawerTool: "도구 결과",
+ referencesDrawerEmpty: "참고 출처가 없습니다",
referenceChunkCount: "{count}개 청크",
fallbackHint: "지식 베이스에서 관련 내용을 찾지 못했습니다. 위는 모델의 직접 응답입니다.",
channelWeb: "웹",
diff --git a/frontend/src/i18n/locales/ru-RU.ts b/frontend/src/i18n/locales/ru-RU.ts
index 423363797..670bef39a 100755
--- a/frontend/src/i18n/locales/ru-RU.ts
+++ b/frontend/src/i18n/locales/ru-RU.ts
@@ -3431,6 +3431,23 @@ export default {
referencesDocCount: 'Использовано {count} документ(ов)',
referencesWebCount: 'Использовано {count} веб-результат(ов)',
referencesDocAndWebCount: 'Использовано {docCount} документ(ов) и {webCount} веб-страниц(ы)',
+ referencesDrawerTitle: 'Источники',
+ referencesDrawerTitleWeb: 'Веб-источники',
+ referencesDrawerTitleDocs: 'Документы',
+ referencesDrawerTitleTools: 'Результаты инструментов',
+ referencesDrawerTitleMixed: 'Источники',
+ referencesDrawerChipWeb: '{count} веб',
+ referencesDrawerChipDocs: '{count} док.',
+ referencesDrawerChipMixed: '{count} источн.',
+ referencesDrawerOpenWeb: 'Показать {count} веб',
+ referencesDrawerOpenDocs: 'Показать {count} док.',
+ referencesDrawerOpenMixed: 'Показать {count} источн.',
+ referencesDrawerWebSection: 'Веб',
+ referencesDrawerDocsSection: 'Документы базы знаний',
+ referencesDrawerToolsSection: 'Инструменты',
+ referencesDrawerDocument: 'Документ базы знаний',
+ referencesDrawerTool: 'Результат инструмента',
+ referencesDrawerEmpty: 'Источники отсутствуют',
referenceChunkCount: '{count} фрагмент(ов)',
fallbackHint: 'В базе знаний не найдено релевантного содержимого. Выше представлен прямой ответ модели.',
channelWeb: 'Веб',
diff --git a/frontend/src/i18n/locales/zh-CN.ts b/frontend/src/i18n/locales/zh-CN.ts
index 7775a5115..d976bcb7e 100755
--- a/frontend/src/i18n/locales/zh-CN.ts
+++ b/frontend/src/i18n/locales/zh-CN.ts
@@ -924,6 +924,23 @@ export default {
referencesDocCount: "引用了{count}篇文档",
referencesWebCount: "参考了{count}条网页",
referencesDocAndWebCount: "引用了{docCount}篇文档和{webCount}条网页",
+ referencesDrawerTitle: "参考来源",
+ referencesDrawerTitleWeb: "网页来源",
+ referencesDrawerTitleDocs: "文档来源",
+ referencesDrawerTitleTools: "工具结果",
+ referencesDrawerTitleMixed: "参考来源",
+ referencesDrawerChipWeb: "{count} 条网页",
+ referencesDrawerChipDocs: "{count} 篇文档",
+ referencesDrawerChipMixed: "{count} 条来源",
+ referencesDrawerOpenWeb: "查看 {count} 条网页",
+ referencesDrawerOpenDocs: "查看 {count} 篇文档",
+ referencesDrawerOpenMixed: "查看 {count} 条来源",
+ referencesDrawerWebSection: "网页",
+ referencesDrawerDocsSection: "知识库文档",
+ referencesDrawerToolsSection: "工具",
+ referencesDrawerDocument: "知识库文档",
+ referencesDrawerTool: "工具结果",
+ referencesDrawerEmpty: "暂无参考来源",
referenceChunkCount: "{count}个片段",
fallbackHint: "未从知识库中检索到相关内容,以上为模型直接回答",
requestInfoTitle: "请求信息",
diff --git a/frontend/src/types/tool-results.ts b/frontend/src/types/tool-results.ts
index ef1ce9481..20d90f571 100644
--- a/frontend/src/types/tool-results.ts
+++ b/frontend/src/types/tool-results.ts
@@ -35,6 +35,7 @@ export interface SearchResultItem {
score: number;
relevance_level: RelevanceLevel;
knowledge_id: string;
+ knowledge_base_id?: string;
knowledge_title: string;
match_type: string;
knowledge_base_type?: string;
@@ -343,4 +344,3 @@ export interface ActionData {
display_type?: DisplayType;
tool_data?: Record<string, any>;
}
-
diff --git a/frontend/src/utils/referenceSources.test.mjs b/frontend/src/utils/referenceSources.test.mjs
new file mode 100644
index 000000000..bcbf151f6
--- /dev/null
+++ b/frontend/src/utils/referenceSources.test.mjs
@@ -0,0 +1,97 @@
+import assert from 'node:assert/strict'
+import test from 'node:test'
+import {
+ buildReferenceSections,
+ buildReferenceList,
+ getDomainFromUrl,
+ normalizeReferenceUrl,
+ resolveReferenceHighlightKey,
+} from './referenceSources.ts'
+
+test('buildReferenceList separates web and document references', () => {
+ const items = buildReferenceList([
+ {
+ id: 'https://example.com/a',
+ chunk_type: 'web_search',
+ knowledge_title: 'Example A',
+ metadata: { url: 'https://example.com/a', snippet: 'snippet a' },
+ content: 'Example A\n\nsnippet a',
+ },
+ {
+ id: 'chunk-1',
+ knowledge_id: 'doc-1',
+ knowledge_title: 'Policy',
+ content: 'refund rules',
+ },
+ ])
+
+ assert.equal(items.length, 2)
+ assert.equal(items[0].kind, 'web')
+ assert.equal(items[0].domain, 'example.com')
+ assert.equal(items[1].kind, 'document')
+})
+
+test('buildReferenceList aggregates chunks from the same document', () => {
+ const items = buildReferenceList([
+ {
+ id: 'chunk-1',
+ knowledge_id: 'doc-1',
+ knowledge_title: 'Policy',
+ content: 'refund rules',
+ },
+ {
+ id: 'chunk-2',
+ knowledge_id: 'doc-1',
+ knowledge_title: 'Policy',
+ content: 'shipping rules',
+ },
+ ])
+
+ assert.equal(items.length, 1)
+ assert.equal(items[0].key, 'doc:doc-1')
+ assert.deepEqual(items[0].chunkIds, ['chunk-1', 'chunk-2'])
+ assert.match(items[0].content || '', /refund rules/)
+ assert.match(items[0].content || '', /shipping rules/)
+})
+
+test('buildReferenceSections keeps tool results in their own section', () => {
+ const sections = buildReferenceSections([
+ {
+ id: 'mcp-result-1',
+ chunk_type: 'tool_result',
+ knowledge_title: 'MCP Search',
+ content: 'tool output',
+ metadata: { source: 'MCP service' },
+ },
+ ])
+
+ assert.equal(sections.length, 1)
+ assert.equal(sections[0].id, 'tools')
+ assert.equal(sections[0].items[0].kind, 'tool')
+ assert.equal(sections[0].items[0].content, 'tool output')
+})
+
+test('resolveReferenceHighlightKey matches web url', () => {
+ const refs = [
+ {
+ id: 'https://news.example.com/post',
+ chunk_type: 'web_search',
+ metadata: { url: 'https://news.example.com/post/' },
+ },
+ ]
+ const key = resolveReferenceHighlightKey(refs, {
+ url: 'https://news.example.com/post',
+ })
+ assert.equal(key, 'web:https://news.example.com/post')
+})
+
+test('normalizeReferenceUrl trims trailing slash', () => {
+ assert.equal(
+ normalizeReferenceUrl('https://example.com/path/'),
+ 'https://example.com/path',
+ )
+})
+
+test('getDomainFromUrl strips www prefix', () => {
+ assert.equal(getDomainFromUrl('https://www.example.com/x'), 'example.com')
+})
diff --git a/frontend/src/utils/referenceSources.ts b/frontend/src/utils/referenceSources.ts
new file mode 100644
index 000000000..50e89fe3c
--- /dev/null
+++ b/frontend/src/utils/referenceSources.ts
@@ -0,0 +1,312 @@
+export type ReferenceItemKind = 'web' | 'document' | 'tool'
+
+export type KnowledgeReferenceLike = {
+ id?: string
+ chunk_ids?: string[]
+ knowledge_id?: string
+ knowledge_title?: string
+ knowledge_filename?: string
+ knowledge_base_id?: string
+ chunk_index?: number
+ chunk_type?: string
+ content?: string
+ metadata?: Record<string, string>
+}
+
+export type ReferenceListItem = {
+ key: string
+ kind: ReferenceItemKind
+ index: number
+ title: string
+ url?: string
+ domain?: string
+ faviconUrl?: string
+ snippet?: string
+ chunkId?: string
+ chunkIds?: string[]
+ knowledgeId?: string
+ knowledgeBaseId?: string
+ content?: string
+}
+
+export type ReferenceDrawerSection = {
+ id: 'web' | 'documents' | 'tools'
+ items: ReferenceListItem[]
+}
+
+export function normalizeReferenceUrl(url: string): string {
+ const raw = String(url || '').trim()
+ if (!raw) return ''
+ try {
+ const parsed = new URL(raw)
+ parsed.hash = ''
+ let pathname = parsed.pathname
+ if (pathname.length > 1 && pathname.endsWith('/')) {
+ pathname = pathname.slice(0, -1)
+ }
+ parsed.pathname = pathname
+ return parsed.toString()
+ } catch {
+ return raw.replace(/\/$/, '')
+ }
+}
+
+export function getWebSearchUrl(item: KnowledgeReferenceLike): string {
+ if (item.metadata?.url) return item.metadata.url
+ if (item.id && (item.id.startsWith('http://') || item.id.startsWith('https://'))) {
+ return item.id
+ }
+ return ''
+}
+
+export function getDomainFromUrl(url: string): string {
+ if (!url) return ''
+ try {
+ return new URL(url).hostname.replace(/^www\./i, '')
+ } catch {
+ return url
+ }
+}
+
+export function getFaviconUrl(urlOrDomain: string): string {
+ const domain = urlOrDomain.includes('://')
+ ? getDomainFromUrl(urlOrDomain)
+ : urlOrDomain.replace(/^www\./i, '')
+ if (!domain) return ''
+ return `https://www.google.com/s2/favicons?domain=${encodeURIComponent(domain)}&sz=32`
+}
+
+function truncateText(text: string, maxLen: number): string {
+ const normalized = String(text || '').replace(/\s+/g, ' ').trim()
+ if (normalized.length <= maxLen) return normalized
+ return `${normalized.slice(0, maxLen)}…`
+}
+
+function isWebReference(item: KnowledgeReferenceLike): boolean {
+ return item.chunk_type === 'web_search'
+}
+
+function isToolReference(item: KnowledgeReferenceLike): boolean {
+ return item.chunk_type === 'tool_result'
+}
+
+function buildWebItem(item: KnowledgeReferenceLike, index: number): ReferenceListItem | null {
+ const url = getWebSearchUrl(item)
+ if (!url) return null
+ const title =
+ item.knowledge_title ||
+ item.metadata?.title ||
+ getDomainFromUrl(url) ||
+ url
+ const snippet =
+ item.metadata?.snippet ||
+ truncateText(item.content || '', 220)
+ const domain = getDomainFromUrl(url)
+ const normalizedUrl = normalizeReferenceUrl(url)
+ return {
+ key: `web:${normalizedUrl}`,
+ kind: 'web',
+ index,
+ title,
+ url,
+ domain,
+ faviconUrl: getFaviconUrl(url),
+ snippet: snippet || undefined,
+ chunkId: item.id,
+ content: item.content,
+ }
+}
+
+function buildDocumentItem(item: KnowledgeReferenceLike, index: number): ReferenceListItem {
+ const chunkId = item.id || `${item.knowledge_id || 'doc'}-${item.chunk_index ?? index}`
+ 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
+ return {
+ key: `doc:${documentKey}`,
+ kind: 'document',
+ index,
+ title,
+ chunkId,
+ chunkIds: item.chunk_ids,
+ knowledgeId: item.knowledge_id,
+ knowledgeBaseId: item.knowledge_base_id,
+ snippet: truncateText(item.content || '', 220) || undefined,
+ content: item.content,
+ }
+}
+
+function buildToolItem(item: KnowledgeReferenceLike, index: number): ReferenceListItem {
+ const id = item.id || `tool-${index}`
+ return {
+ key: `tool:${id}`,
+ kind: 'tool',
+ index,
+ title: item.knowledge_title || item.metadata?.title || 'Tool result',
+ domain: item.metadata?.source || item.metadata?.tool || undefined,
+ snippet: truncateText(item.content || '', 220) || undefined,
+ chunkId: id,
+ content: item.content,
+ }
+}
+
+function getDocumentGroupKey(item: KnowledgeReferenceLike, index: number): string {
+ if (item.knowledge_id) return item.knowledge_id
+ const title = item.knowledge_title || item.knowledge_filename
+ if (title) return [item.knowledge_base_id, title].filter(Boolean).join(':')
+ return (
+ item.id ||
+ `doc-${index}`
+ )
+}
+
+function mergeDocumentReferences(refs: KnowledgeReferenceLike[]): KnowledgeReferenceLike[] {
+ const groups = new Map<string, KnowledgeReferenceLike & { content_parts?: string[] }>()
+
+ refs.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 existing = groups.get(key)
+
+ if (!existing) {
+ groups.set(key, {
+ ...item,
+ id: item.id || key,
+ content_parts: content ? [content] : [],
+ chunk_ids: chunkIds,
+ })
+ return
+ }
+
+ if (!existing.knowledge_id && item.knowledge_id) existing.knowledge_id = item.knowledge_id
+ if (!existing.knowledge_title && item.knowledge_title) existing.knowledge_title = item.knowledge_title
+ if (!existing.knowledge_filename && item.knowledge_filename) existing.knowledge_filename = item.knowledge_filename
+ if (!existing.knowledge_base_id && item.knowledge_base_id) existing.knowledge_base_id = item.knowledge_base_id
+ for (const chunkId of chunkIds) {
+ if (!existing.chunk_ids?.includes(chunkId)) {
+ existing.chunk_ids = [...(existing.chunk_ids || []), chunkId]
+ }
+ }
+ if (content && !existing.content_parts?.includes(content)) {
+ existing.content_parts = [...(existing.content_parts || []), content]
+ }
+ })
+
+ return Array.from(groups.values()).map((item) => {
+ const { content_parts: contentParts, ...rest } = item
+ return {
+ ...rest,
+ content: contentParts?.slice(0, 3).join('\n\n') || rest.content,
+ }
+ })
+}
+
+function mergeWebReferences(refs: KnowledgeReferenceLike[]): KnowledgeReferenceLike[] {
+ const groups = new Map<string, KnowledgeReferenceLike>()
+
+ refs.forEach((item, index) => {
+ const url = getWebSearchUrl(item)
+ const key = url ? normalizeReferenceUrl(url) : item.id || `web-${index}`
+ if (!groups.has(key)) {
+ groups.set(key, item)
+ }
+ })
+
+ return Array.from(groups.values())
+}
+
+export function buildReferenceSections(
+ refs: KnowledgeReferenceLike[] | null | undefined,
+): ReferenceDrawerSection[] {
+ const list = Array.isArray(refs) ? refs.filter(Boolean) : []
+ if (!list.length) return []
+
+ const webReferences: KnowledgeReferenceLike[] = []
+ const documentReferences: KnowledgeReferenceLike[] = []
+ const toolReferences: KnowledgeReferenceLike[] = []
+ const webItems: ReferenceListItem[] = []
+ const docItems: ReferenceListItem[] = []
+ const toolItems: ReferenceListItem[] = []
+ let webIndex = 0
+ let docIndex = 0
+ let toolIndex = 0
+
+ for (const item of list) {
+ if (isWebReference(item)) {
+ webReferences.push(item)
+ continue
+ }
+ if (isToolReference(item)) {
+ toolReferences.push(item)
+ continue
+ }
+ documentReferences.push(item)
+ }
+
+ for (const item of mergeWebReferences(webReferences)) {
+ const built = buildWebItem(item, ++webIndex)
+ if (built) webItems.push(built)
+ }
+
+ for (const item of mergeDocumentReferences(documentReferences)) {
+ docItems.push(buildDocumentItem(item, ++docIndex))
+ }
+
+ for (const item of toolReferences) {
+ toolItems.push(buildToolItem(item, ++toolIndex))
+ }
+
+ const sections: ReferenceDrawerSection[] = []
+ if (webItems.length) sections.push({ id: 'web', items: webItems })
+ if (docItems.length) sections.push({ id: 'documents', items: docItems })
+ if (toolItems.length) sections.push({ id: 'tools', items: toolItems })
+ return sections
+}
+
+export function buildReferenceList(
+ refs: KnowledgeReferenceLike[] | null | undefined,
+): ReferenceListItem[] {
+ return buildReferenceSections(refs).flatMap((section) => section.items)
+}
+
+export type ReferenceHighlightTarget = {
+ url?: string
+ chunkId?: string
+ key?: string
+}
+
+export function resolveReferenceHighlightKey(
+ refs: KnowledgeReferenceLike[] | null | undefined,
+ target: ReferenceHighlightTarget | null | undefined,
+): string | null {
+ if (!target) return null
+ if (target.key) return target.key
+
+ const items = buildReferenceList(refs)
+ if (!items.length) return null
+
+ if (target.url) {
+ const normalized = normalizeReferenceUrl(target.url)
+ const hit = items.find(
+ (item) => item.kind === 'web' && item.url && normalizeReferenceUrl(item.url) === normalized,
+ )
+ if (hit) return hit.key
+ }
+
+ if (target.chunkId) {
+ const raw = String(target.chunkId).trim()
+ const hit = items.find(
+ (item) =>
+ item.chunkId === raw ||
+ item.chunkIds?.includes(raw) ||
+ item.key === `doc:${raw}` ||
+ (item.kind === 'web' && (item.chunkId === raw || item.url === raw)),
+ )
+ if (hit) return hit.key
+ }
+
+ return null
+}
diff --git a/frontend/src/views/chat/components/AgentStreamDisplay.vue b/frontend/src/views/chat/components/AgentStreamDisplay.vue
index 0817014b8..f1f80dadc 100644
--- a/frontend/src/views/chat/components/AgentStreamDisplay.vue
+++ b/frontend/src/views/chat/components/AgentStreamDisplay.vue
@@ -102,10 +102,17 @@
<div v-else-if="event.type === 'tool_call'" class="tool-event">
<div class="action-card" :class="{
'action-pending': event.pending,
- 'action-error': event.success === false
- }">
- <div class="action-header" @click="handleActionHeaderClick(event)"
- :class="{ 'no-results': !hasResults(event) }">
+ 'action-error': event.success === false,
+ 'reference-trigger': canOpenToolReferences(event)
+ }"
+ :role="canOpenToolReferences(event) ? 'button' : undefined"
+ :tabindex="canOpenToolReferences(event) ? 0 : undefined"
+ @click="handleActionCardClick(event)"
+ @keydown.enter="handleActionCardClick(event)"
+ @keydown.space.prevent="handleActionCardClick(event)"
+ >
+ <div class="action-header" @click.stop="handleActionHeaderClick(event)"
+ :class="{ 'no-results': !hasActionResult(event) }">
<div class="action-title">
<t-icon v-if="event.tool_name" class="action-title-icon"
:name="getToolIconName(event.tool_name)" />
@@ -153,7 +160,7 @@
<div class="results-summary-text" v-html="getKnowledgeChunksSummary(event.tool_data)"></div>
</div>
- <div v-if="isEventExpanded(event.tool_call_id) && !event.pending && hasResults(event)"
+ <div v-if="isEventExpanded(event.tool_call_id) && !event.pending && hasExpandableResults(event)"
class="action-details">
<div v-if="event.display_type && event.tool_data" class="tool-result-wrapper">
<ToolResultRenderer :display-type="event.display_type" :tool-data="event.tool_data"
@@ -305,10 +312,17 @@
<div v-else-if="event.type === 'tool_call'" class="tool-event">
<div class="action-card" :class="{
'action-pending': event.pending,
- 'action-error': event.success === false
- }">
- <div class="action-header" @click="handleActionHeaderClick(event)"
- :class="{ 'no-results': !hasResults(event) }">
+ 'action-error': event.success === false,
+ 'reference-trigger': canOpenToolReferences(event)
+ }"
+ :role="canOpenToolReferences(event) ? 'button' : undefined"
+ :tabindex="canOpenToolReferences(event) ? 0 : undefined"
+ @click="handleActionCardClick(event)"
+ @keydown.enter="handleActionCardClick(event)"
+ @keydown.space.prevent="handleActionCardClick(event)"
+ >
+ <div class="action-header" @click.stop="handleActionHeaderClick(event)"
+ :class="{ 'no-results': !hasActionResult(event) }">
<div class="action-title">
<t-icon v-if="event.tool_name" class="action-title-icon" :name="getToolIconName(event.tool_name)" />
<t-tooltip v-if="event.tool_name === 'todo_write' && event.tool_data?.steps"
@@ -357,7 +371,7 @@
<div class="results-summary-text" v-html="getKnowledgeChunksSummary(event.tool_data)"></div>
</div>
- <div v-if="isEventExpanded(event.tool_call_id) && !event.pending && hasResults(event)"
+ <div v-if="isEventExpanded(event.tool_call_id) && !event.pending && hasExpandableResults(event)"
class="action-details">
<div v-if="event.display_type && event.tool_data" class="tool-result-wrapper">
<ToolResultRenderer :display-type="event.display_type" :tool-data="event.tool_data"
@@ -442,9 +456,12 @@ import McpOAuthCard from './McpOAuthCard.vue';
import ChatRequestInfoButton from '@/components/ChatRequestInfoButton.vue';
import ChatCitationFloat from '@/components/ChatCitationFloat.vue';
import picturePreview from '@/components/picture-preview.vue';
-import { countGrepDocuments } from '@/utils/grepResultsGroup';
+import { countGrepDocuments, groupGrepChunkResults } from '@/utils/grepResultsGroup';
import { getKnowledgeChunksSummaryHtml } from '@/utils/knowledgeChunksDisplay';
import { useChatCitationPopover } from '@/composables/useChatCitationPopover';
+import { useChatReferencesDrawer } from '@/composables/useChatReferencesDrawer';
+import type { KnowledgeReferenceLike } from '@/utils/referenceSources';
+import { resolveCitationChunkId } from '@/utils/citationMarkdown';
import { getWikiPage, type WikiPage } from '@/api/wiki';
import { MessagePlugin } from 'tdesign-vue-next';
import { useUIStore } from '@/stores/ui';
@@ -757,8 +774,233 @@ const {
getKnowledgeReferences: () => props.session?.knowledge_references,
embedChannelId: () => (props.embeddedMode ? props.embedChannelId : undefined),
embedToken: () => (props.embeddedMode ? props.embedToken : undefined),
+ sessionId: () => props.sessionId,
});
+const referencesDrawer = useChatReferencesDrawer();
+
+const openReferencesDrawer = (
+ highlight?: { url?: string; chunkId?: string },
+ refsOverride?: KnowledgeReferenceLike[] | null,
+) => {
+ const refs = refsOverride?.length ? refsOverride : props.session?.knowledge_references
+ if (!referencesDrawer || !refs?.length) return false
+ referencesDrawer.open({
+ references: refs,
+ highlight: highlight || null,
+ messageId: props.session?.id,
+ })
+ return true
+}
+
+const mergeDocumentReferences = (refs: KnowledgeReferenceLike[]): KnowledgeReferenceLike[] => {
+ const merged = new Map<string, KnowledgeReferenceLike & { contentParts?: string[] }>();
+
+ for (const ref of refs) {
+ if (ref.chunk_type === 'web_search') continue;
+ const key = ref.knowledge_id || ref.knowledge_title || ref.id;
+ if (!key) continue;
+
+ const existing = merged.get(key);
+ const content = String(ref.content || '').trim();
+ if (!existing) {
+ merged.set(key, {
+ ...ref,
+ id: ref.knowledge_id || ref.id || key,
+ content,
+ contentParts: content ? [content] : [],
+ });
+ continue;
+ }
+
+ if (content && !existing.contentParts?.includes(content)) {
+ existing.contentParts = [...(existing.contentParts || []), content];
+ existing.content = existing.contentParts.slice(0, 3).join('\n\n');
+ }
+ }
+
+ return Array.from(merged.values()).map(({ contentParts, ...ref }) => ref);
+};
+
+const cleanToolOutputContent = (output: unknown): string => {
+ const raw = typeof output === 'string' ? output : '';
+ return raw
+ .replace(/<\/?knowledge_chunks[^>]*>/gi, '')
+ .replace(/<\/?chunk[^>]*>/gi, '')
+ .trim();
+};
+
+const getToolKnowledgeBaseId = (toolData: any): string | undefined => {
+ if (typeof toolData?.knowledge_base_id === 'string' && toolData.knowledge_base_id) {
+ return toolData.knowledge_base_id;
+ }
+ const kbIds = Array.isArray(toolData?.knowledge_base_ids) ? toolData.knowledge_base_ids : [];
+ if (kbIds.length === 1 && typeof kbIds[0] === 'string' && kbIds[0]) {
+ return kbIds[0];
+ }
+ return undefined;
+};
+
+const formatToolResultContent = (value: unknown): string => {
+ if (typeof value === 'string') return value.trim();
+ if (value == null) return '';
+ try {
+ return JSON.stringify(value, null, 2);
+ } catch {
+ return String(value);
+ }
+};
+
+const isMcpTool = (toolName?: string | null): boolean => String(toolName || '').startsWith('mcp_');
+
+const getToolReferenceItems = (event: any): KnowledgeReferenceLike[] => {
+ if (!event || event.pending) return [];
+ const toolName = event.tool_name;
+ const toolData = event.tool_data;
+
+ if (isMcpTool(toolName)) {
+ const output = formatToolResultContent(event.output) || formatToolResultContent(toolData);
+ if (!output) return [];
+ return [{
+ id: event.tool_call_id || toolName,
+ chunk_type: 'tool_result',
+ knowledge_title: getToolTitle(event),
+ content: output,
+ metadata: {
+ title: getToolTitle(event),
+ source: getLocalizedToolName(toolName),
+ tool: String(toolName || ''),
+ },
+ }];
+ }
+
+ if (!toolData) return [];
+
+ if (toolName === 'web_search') {
+ const results = Array.isArray(toolData.results) ? toolData.results : [];
+ return results
+ .filter((item: any) => item?.url)
+ .map((item: any, index: number) => ({
+ id: item.url,
+ chunk_type: 'web_search',
+ knowledge_title: item.title || item.source || item.url,
+ content: item.snippet || item.content || '',
+ metadata: {
+ url: item.url,
+ title: item.title || '',
+ snippet: item.snippet || item.content || '',
+ },
+ chunk_index: item.result_index ?? index + 1,
+ }));
+ }
+
+ if (toolName === 'web_fetch') {
+ const results = Array.isArray(toolData.results) ? toolData.results : [];
+ return results
+ .filter((item: any) => item?.url)
+ .map((item: any, index: number) => ({
+ id: item.url,
+ chunk_type: 'web_search',
+ knowledge_title: item.url,
+ content: item.summary || item.raw_content || '',
+ metadata: {
+ url: item.url,
+ title: item.url,
+ snippet: item.summary || item.raw_content || '',
+ },
+ chunk_index: index + 1,
+ }));
+ }
+
+ if (toolName === 'search_knowledge' || toolName === 'knowledge_search') {
+ const results = Array.isArray(toolData.results) ? toolData.results : [];
+ const fallbackKnowledgeBaseId = getToolKnowledgeBaseId(toolData);
+ return mergeDocumentReferences(results
+ .filter((item: any) => item?.chunk_id || item?.knowledge_id)
+ .map((item: any, index: number) => ({
+ id: item.chunk_id || `${item.knowledge_id}-${item.result_index ?? index + 1}`,
+ knowledge_id: item.knowledge_id,
+ knowledge_title: item.faq_standard_question || item.knowledge_title,
+ knowledge_base_id: item.knowledge_base_id || fallbackKnowledgeBaseId,
+ chunk_index: item.result_index ?? index + 1,
+ chunk_type: item.chunk_type,
+ content: item.content || '',
+ })));
+ }
+
+ if (toolName === 'grep_chunks') {
+ const chunkResults = Array.isArray(toolData.chunk_results) ? toolData.chunk_results : [];
+ if (chunkResults.length) {
+ return groupGrepChunkResults(chunkResults)
+ .filter((group) => group.knowledge_id || group.title)
+ .map((group, index) => ({
+ id: group.knowledge_id || group.key,
+ knowledge_id: group.knowledge_id,
+ knowledge_title: group.title,
+ 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 || '',
+ }));
+ }
+
+ const knowledgeResults = Array.isArray(toolData.knowledge_results) ? toolData.knowledge_results : [];
+ return mergeDocumentReferences(knowledgeResults
+ .filter((item: any) => item?.knowledge_id)
+ .map((item: any, index: number) => ({
+ id: item.knowledge_id,
+ knowledge_id: item.knowledge_id,
+ knowledge_title: item.faq_question || item.knowledge_title,
+ knowledge_base_id: item.knowledge_base_id,
+ chunk_index: index + 1,
+ content: item.match_snippet || '',
+ })));
+ }
+
+ if (toolName === 'list_knowledge_chunks') {
+ 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 [];
+};
+
+const canOpenToolReferences = (event: any): boolean => getToolReferenceItems(event).length > 0;
+
+const openToolReferences = (event: any): boolean => {
+ const refs = getToolReferenceItems(event);
+ if (!referencesDrawer || !refs.length) return false;
+ referencesDrawer.toggle({
+ references: refs,
+ highlight: null,
+ messageId: props.session?.id,
+ sourceKey: `tool:${props.session?.id || 'session'}:${event.tool_call_id || event.event_id || event.tool_name || 'references'}`,
+ });
+ return true;
+};
+
configureMarkedForChatMarkdown();
// Event stream
@@ -1462,15 +1704,40 @@ const toggleEvent = (eventId: string) => {
};
const handleActionHeaderClick = (event: any) => {
- if (hasResults(event) && event.tool_call_id) {
+ if (canOpenToolReferences(event)) {
+ openToolReferences(event);
+ return;
+ }
+ if (hasExpandableResults(event) && event.tool_call_id) {
toggleEvent(event.tool_call_id);
}
};
+const handleActionCardClick = (event: any) => {
+ if (!canOpenToolReferences(event)) return;
+ openToolReferences(event);
+};
+
const isEventExpanded = (eventId: string): boolean => {
return expandedEvents.value.has(eventId);
};
+const isReferenceDrawerTool = (toolName?: string | null): boolean =>
+ isMcpTool(toolName) ||
+ toolName === 'search_knowledge' ||
+ toolName === 'knowledge_search' ||
+ toolName === 'web_search' ||
+ toolName === 'web_fetch' ||
+ toolName === 'grep_chunks' ||
+ toolName === 'list_knowledge_chunks';
+
+const hasExpandableResults = (event: any): boolean => {
+ if (isReferenceDrawerTool(event?.tool_name)) return false;
+ return hasResults(event);
+};
+
+const hasActionResult = (event: any): boolean => canOpenToolReferences(event) || hasExpandableResults(event);
+
// Check if search/grep tools have results
const hasResults = (event: any): boolean => {
if (!event || !event.tool_data) return true; // Default to true for other tools
@@ -1508,6 +1775,9 @@ const hasResults = (event: any): boolean => {
// Delegated handlers for span-based citation clicks/keyboard
const handleCitationActivate = (el: HTMLElement) => {
const url = el.getAttribute('data-url');
+ if (url && openReferencesDrawer({ url })) {
+ return;
+ }
if (!url) return;
try {
// @ts-ignore: Wails runtime check
@@ -1594,15 +1864,25 @@ const onRootClick = (e: Event) => {
return;
}
- // Handle KB citation clicks -> navigate to KB detail page
+ // Handle KB citation clicks -> open references drawer when available
const kbEl = target.closest?.('.citation-kb') as HTMLElement | null;
- if (kbEl && kbEl.getAttribute('data-kb-id')) {
+ if (kbEl && kbEl.getAttribute('data-chunk-id')) {
e.preventDefault();
e.stopPropagation();
- const kbId = kbEl.getAttribute('data-kb-id');
+ const rawChunkId = kbEl.getAttribute('data-chunk-id') || '';
+ const title = kbEl.getAttribute('data-doc') || '';
+ const kbId = kbEl.getAttribute('data-kb-id') || '';
+ const chunkId =
+ resolveCitationChunkId(
+ rawChunkId,
+ { doc: title, kbId },
+ props.session?.knowledge_references,
+ ) || rawChunkId;
+ if (openReferencesDrawer({ chunkId })) {
+ return;
+ }
if (kbId) {
try {
- // Navigate to knowledge base detail page
router.push(`/platform/knowledge-bases/${kbId}`);
} catch (error) {
console.error('Failed to navigate to knowledge base:', error);
@@ -1661,7 +1941,18 @@ const onRootKeydown = (e: KeyboardEvent) => {
if (kbEl) {
if (e.key === 'Enter' || e.key === ' ') {
e.preventDefault();
- const kbId = kbEl.getAttribute('data-kb-id');
+ const rawChunkId = kbEl.getAttribute('data-chunk-id') || '';
+ const title = kbEl.getAttribute('data-doc') || '';
+ const kbId = kbEl.getAttribute('data-kb-id') || '';
+ const chunkId =
+ resolveCitationChunkId(
+ rawChunkId,
+ { doc: title, kbId },
+ props.session?.knowledge_references,
+ ) || rawChunkId;
+ if (openReferencesDrawer({ chunkId })) {
+ return;
+ }
if (kbId) {
try {
router.push(`/platform/knowledge-bases/${kbId}`);
@@ -2442,6 +2733,17 @@ const handleAddToKnowledge = (answerEvent: any) => {
background: transparent;
}
+ &.reference-trigger {
+ cursor: pointer;
+
+ &:hover {
+ .action-name,
+ .results-summary-text {
+ color: var(--td-text-color-primary);
+ }
+ }
+ }
+
&.action-error {
color: var(--td-error-color);
}
@@ -2779,6 +3081,10 @@ const handleAddToKnowledge = (answerEvent: any) => {
}
.search-results-summary-fixed {
+ display: flex;
+ align-items: center;
+ gap: 8px;
+ flex-wrap: wrap;
padding: 2px 0 0 0;
background: transparent;
border-top: 0;
diff --git a/frontend/src/views/chat/components/RagPipelineProgress.style.test.mjs b/frontend/src/views/chat/components/RagPipelineProgress.style.test.mjs
index 7fc80f5ab..ee9914182 100644
--- a/frontend/src/views/chat/components/RagPipelineProgress.style.test.mjs
+++ b/frontend/src/views/chat/components/RagPipelineProgress.style.test.mjs
@@ -19,28 +19,32 @@ test('rag pipeline uses agent-style timeline structure', () => {
test('rag pipeline persists and collapses after the answer arrives', () => {
assert.match(source, /showCollapsedRoot/)
- assert.match(source, /tree-root-summary/)
- assert.match(source, /collapsedSummaryHtml/)
+ assert.match(source, /tree-root-status/)
+ assert.match(source, /collapsedStatusText/)
+ assert.match(source, /referenceSummaryText/)
assert.match(source, /hasThinking\.value/)
assert.match(source, /const visible = computed\([\s\S]*showPrePipelineWait\.value/)
})
test('rag pipeline toggles expand and collapse from the root header', () => {
- assert.match(source, /class="action-card tree-root" @click="toggleExpanded"/)
+ assert.match(source, /class="tree-root-expand"/)
+ assert.match(source, /@click="toggleExpanded"/)
assert.match(source, /showExpandedTimeline \? 'chevron-down' : 'chevron-right'/)
assert.doesNotMatch(source, /refsExpanded \? 'chevron/)
assert.doesNotMatch(source, /tree-collapse-bar/)
})
test('only the collapsed root summary shows an expand chevron', () => {
- assert.match(source, /tree-root-summary[\s\S]*class="action-show-icon"/)
- assert.equal((source.match(/class="action-show-icon"/g) || []).length, 1)
+ const template = source.split('<script')[0]
+ assert.match(template, /tree-root-expand__icon/)
+ assert.equal((template.match(/tree-root-expand__icon/g) || []).length, 1)
})
-test('rag pipeline embeds references in the timeline instead of a separate card', () => {
- assert.match(source, /timeline-mode/)
- assert.match(source, /content-only/)
- assert.match(source, /rag-ref-step[\s\S]*name="file-search"/)
+test('rag pipeline opens references from search steps and the drawer composable', () => {
+ assert.match(source, /useChatReferencesDrawer/)
+ assert.match(source, /toggleReferencesDrawer/)
+ assert.match(source, /has-reference-trigger/)
+ assert.match(source, /handleStepClick/)
})
test('rag pipeline keeps loading inside the thinking step instead of orphan dots', () => {
@@ -51,13 +55,6 @@ test('rag pipeline keeps loading inside the thinking step instead of orphan dots
assert.doesNotMatch(source, /showActivityIndicator/)
})
-test('rag pipeline places references before the done row', () => {
- const refsIndex = source.indexOf('class="tree-child rag-ref-step"')
- const doneIndex = source.indexOf('agent-step-done')
- assert.ok(refsIndex > -1 && doneIndex > -1)
- assert.ok(refsIndex < doneIndex)
-})
-
test('done row appears only after the full turn completes', () => {
assert.match(source, /const showDoneRow = computed\(\(\) => \{[\s\S]*hasAnswer\.value/)
})
@@ -75,11 +72,11 @@ test('rag pipeline renders model thinking inside the timeline before the done ro
test('clickable timeline headers use pointer cursor', () => {
assert.match(source, /\.tool-event \{[\s\S]*\.action-header \{[\s\S]*cursor: pointer/)
assert.match(source, /\.action-header \{[\s\S]*&\.no-results \{[\s\S]*cursor: default/)
- assert.match(source, /\.tree-root \{[\s\S]*cursor: pointer/)
+ assert.match(source, /\.has-reference-trigger \{[\s\S]*cursor: pointer/)
})
-test('collapsed summary uses the same title-to-answer spacing as agent', () => {
- assert.match(source, /\.tree-container \{\s*margin: 0 0 16px;/)
+test('collapsed summary uses compact spacing before the answer', () => {
+ assert.match(source, /\.tree-container \{\s*margin: 0 0 8px;/)
assert.match(source, /\.rag-pipeline-progress \{[\s\S]*margin: 0;/)
})
diff --git a/frontend/src/views/chat/components/RagPipelineProgress.vue b/frontend/src/views/chat/components/RagPipelineProgress.vue
index e682c4298..9711c5d7c 100644
--- a/frontend/src/views/chat/components/RagPipelineProgress.vue
+++ b/frontend/src/views/chat/components/RagPipelineProgress.vue
@@ -19,15 +19,25 @@
<div v-for="(step, index) in steps" :key="step.id" class="tree-child" :class="{
'tree-child-last':
!showDoneRow
- && !hasReferences
&& !showThinkingStep
&& index === steps.length - 1,
}">
<div class="tree-branch" />
<div class="tree-child-content">
<div class="tool-event">
- <div class="action-card">
- <div class="action-header no-results">
+ <div
+ class="action-card"
+ :class="{ 'has-reference-trigger': step.canOpenReferences }"
+ :role="step.canOpenReferences ? 'button' : undefined"
+ :tabindex="step.canOpenReferences ? 0 : undefined"
+ @click="handleStepClick(step)"
+ @keydown.enter="handleStepClick(step)"
+ @keydown.space.prevent="handleStepClick(step)"
+ >
+ <div
+ class="action-header"
+ :class="{ 'no-results': !step.canOpenReferences }"
+ >
<div class="action-title">
<t-icon class="action-title-icon" :name="step.iconName" />
<span class="action-name" :class="{ 'is-running': step.pending }">{{ step.title }}</span>
@@ -41,25 +51,6 @@
</div>
</div>
- <div v-if="hasReferences" class="tree-child rag-ref-step"
- :class="{ 'tree-child-last': !showThinkingStep && !showDoneRow }">
- <div class="tree-branch" />
- <div class="tree-child-content">
- <div class="tool-event">
- <div class="action-card">
- <div class="action-header" @click="toggleReferences">
- <div class="action-title">
- <t-icon class="action-title-icon" name="file-search" />
- <span class="action-name">{{ referencesHeaderText }}</span>
- </div>
- </div>
- <DocInfo v-show="refsExpanded" :session="session" :embedded-mode="embeddedMode" timeline-mode
- content-only />
- </div>
- </div>
- </div>
- </div>
-
<div v-if="showThinkingStep" class="tree-child rag-thinking-step"
:class="{ 'tree-child-last': !showDoneRow }">
<div class="tree-branch" />
@@ -106,26 +97,50 @@
<div v-else class="tree-container">
<div class="tool-event">
- <div class="action-card tree-root" @click="toggleExpanded">
- <div class="action-header">
- <div class="action-title">
- <span class="action-name tree-root-summary" v-html="collapsedSummaryHtml" />
- <div class="action-show-icon">
- <t-icon :name="showExpandedTimeline ? 'chevron-down' : 'chevron-right'" />
- </div>
- </div>
+ <div class="action-card tree-root">
+ <div class="tree-root-toolbar">
+ <button
+ type="button"
+ class="tree-root-expand"
+ :aria-expanded="showExpandedTimeline"
+ :aria-label="collapsedStatusText"
+ @click="toggleExpanded"
+ >
+ <span class="tree-root-status">{{ collapsedStatusText }}</span>
+ <span
+ v-if="referenceSummaryText"
+ class="tree-root-reference"
+ >
+ {{ referenceSummaryText }}
+ </span>
+ <t-icon
+ class="tree-root-expand__icon"
+ :name="showExpandedTimeline ? 'chevron-down' : 'chevron-right'"
+ />
+ </button>
</div>
</div>
</div>
<div v-if="showExpandedTimeline" class="tree-children tree-children-expanded">
<div v-for="(step, index) in steps" :key="step.id" class="tree-child"
- :class="{ 'tree-child-last': index === steps.length - 1 && !hasReferences && !showDoneRow && !showThinkingStep }">
+ :class="{ 'tree-child-last': index === steps.length - 1 && !showDoneRow && !showThinkingStep }">
<div class="tree-branch" />
<div class="tree-child-content">
<div class="tool-event">
- <div class="action-card">
- <div class="action-header no-results">
+ <div
+ class="action-card"
+ :class="{ 'has-reference-trigger': step.canOpenReferences }"
+ :role="step.canOpenReferences ? 'button' : undefined"
+ :tabindex="step.canOpenReferences ? 0 : undefined"
+ @click="handleStepClick(step)"
+ @keydown.enter="handleStepClick(step)"
+ @keydown.space.prevent="handleStepClick(step)"
+ >
+ <div
+ class="action-header"
+ :class="{ 'no-results': !step.canOpenReferences }"
+ >
<div class="action-title">
<t-icon class="action-title-icon" :name="step.iconName" />
<span class="action-name" :class="{ 'is-running': step.pending }">{{ step.title }}</span>
@@ -139,25 +154,6 @@
</div>
</div>
- <div v-if="hasReferences" class="tree-child rag-ref-step"
- :class="{ 'tree-child-last': !showThinkingStep && !showDoneRow }">
- <div class="tree-branch" />
- <div class="tree-child-content">
- <div class="tool-event">
- <div class="action-card">
- <div class="action-header" @click="toggleReferences">
- <div class="action-title">
- <t-icon class="action-title-icon" name="file-search" />
- <span class="action-name">{{ referencesHeaderText }}</span>
- </div>
- </div>
- <DocInfo v-show="refsExpanded" :session="session" :embedded-mode="embeddedMode" timeline-mode
- content-only />
- </div>
- </div>
- </div>
- </div>
-
<div v-if="showThinkingStep" class="tree-child rag-thinking-step" :class="{ 'tree-child-last': !showDoneRow }">
<div class="tree-branch" />
<div class="tree-child-content">
@@ -207,7 +203,6 @@
<script setup lang="ts">
import { computed, nextTick, ref, watch } from 'vue'
import { useI18n } from 'vue-i18n'
-import DocInfo from './docInfo.vue'
import { getAgentToolIconName } from '@/utils/agent-tool-icons'
import {
getKnowledgeSearchSummaryHtml,
@@ -215,9 +210,12 @@ import {
getRetrievalSearchSource,
} from '@/utils/agent-tool-display'
import { RAG_PIPELINE_TOOL_NAMES } from '@/utils/rag-pipeline-history'
+import { useChatReferencesDrawer } from '@/composables/useChatReferencesDrawer'
+import { buildReferenceSections } from '@/utils/referenceSources'
const props = defineProps<{
session?: {
+ id?: string | number
agentEventStream?: Array<Record<string, unknown>>
content?: string
knowledge_references?: Array<{ chunk_type?: string; knowledge_id?: string; knowledge_title?: string }>
@@ -227,8 +225,8 @@ const props = defineProps<{
}>()
const { t } = useI18n()
+const referencesDrawer = useChatReferencesDrawer()
const userExpanded = ref(false)
-const refsExpanded = ref(false)
const thinkingExpanded = ref(true)
const rootElement = ref<HTMLElement | null>(null)
@@ -266,6 +264,8 @@ const hasReferences = computed(
() => (props.session?.knowledge_references?.length ?? 0) > 0,
)
+const referenceSections = computed(() => buildReferenceSections(props.session?.knowledge_references))
+
const steps = computed(() => {
const stream = props.session?.agentEventStream
if (!stream?.length) return []
@@ -294,6 +294,7 @@ const steps = computed(() => {
!pending && isSearchTool && toolData
? getKnowledgeSearchSummaryHtml(t, toolData)
: ''
+ const canOpenReferences = !pending && isSearchTool && hasReferences.value
return {
id: String(event.tool_call_id || `${toolName}-${event.timestamp || 0}`),
@@ -307,6 +308,7 @@ const steps = computed(() => {
tool_data: toolData,
}),
summaryHtml,
+ canOpenReferences,
}
})
})
@@ -364,25 +366,16 @@ const visible = computed(
() => steps.value.length > 0 || showPrePipelineWait.value || showThinkingStep.value,
)
-const referenceDocCount = computed(() => {
- const refs = props.session?.knowledge_references ?? []
- const keys = new Set<string>()
- for (const item of refs) {
- if (item.chunk_type === 'web_search') continue
- keys.add(item.knowledge_id || item.knowledge_title || 'doc')
+const collapsedStatusText = computed(() => {
+ if (steps.value.length === 0) {
+ return hasThinking.value ? t('agentStream.toolStatus.thinkingDone') : ''
}
- return keys.size
-})
-
-const referenceWebCount = computed(() => {
- const refs = props.session?.knowledge_references ?? []
- return refs.filter((item) => item.chunk_type === 'web_search').length
+ return t('agentStream.ragPipeline.searchDone')
})
-const referencesHeaderText = computed(() => {
- const docCount = referenceDocCount.value
- const webCount = referenceWebCount.value
- const total = props.session?.knowledge_references?.length ?? 0
+const referenceSummaryText = computed(() => {
+ const docCount = referenceSections.value.find((section) => section.id === 'documents')?.items.length ?? 0
+ const webCount = referenceSections.value.find((section) => section.id === 'web')?.items.length ?? 0
if (docCount > 0 && webCount > 0) {
return t('chat.referencesDocAndWebCount', { docCount, webCount })
@@ -393,50 +386,30 @@ const referencesHeaderText = computed(() => {
if (webCount > 0) {
return t('chat.referencesWebCount', { count: webCount })
}
- return t('chat.referencesTitle', { count: total })
-})
-const collapsedSummaryHtml = computed(() => {
- if (steps.value.length === 0) {
- return hasThinking.value ? t('agentStream.toolStatus.thinkingDone') : ''
- }
-
- const parts: string[] = [t('agentStream.ragPipeline.searchDone')]
- const docCount = referenceDocCount.value
- const webCount = referenceWebCount.value
+ return ''
+})
- if (docCount > 0 && webCount > 0) {
- parts.push(
- t('agentStream.ragPipeline.referencedDocAndWeb', {
- docCount: `<strong>${docCount}</strong>`,
- webCount: `<strong>${webCount}</strong>`,
- }),
- )
- } else if (docCount > 0) {
- parts.push(
- t('agentStream.ragPipeline.referencedDocs', {
- count: `<strong>${docCount}</strong>`,
- }),
- )
- } else if (webCount > 0) {
- parts.push(
- t('agentStream.ragPipeline.referencedWebs', {
- count: `<strong>${webCount}</strong>`,
- }),
- )
- }
+function toggleReferencesDrawer() {
+ const refs = props.session?.knowledge_references
+ if (!referencesDrawer || !refs?.length) return
+ referencesDrawer.toggle({
+ references: refs,
+ highlight: null,
+ messageId: props.session?.id ? String(props.session.id) : '',
+ sourceKey: `rag:${props.session?.id || refs.map((item) => item.knowledge_id || item.knowledge_title).join('|')}`,
+ })
+}
- return parts.join(t('agent.stepSummarySeparator'))
-})
+function handleStepClick(step: { canOpenReferences?: boolean }) {
+ if (!step.canOpenReferences) return
+ toggleReferencesDrawer()
+}
function toggleExpanded() {
userExpanded.value = !userExpanded.value
}
-function toggleReferences() {
- refsExpanded.value = !refsExpanded.value
-}
-
function toggleThinking() {
if (!showThinkingStep.value || !thinkingContent.value) return
thinkingExpanded.value = !thinkingExpanded.value
@@ -488,46 +461,73 @@ watch(thinkingExpanded, (expanded) => {
}
.tree-container {
- margin: 0 0 16px;
+ margin: 0 0 8px;
position: relative;
}
.tree-root {
- cursor: pointer;
- color: var(--td-text-color-secondary);
margin-bottom: 0;
- .action-header {
+ .tree-root-toolbar {
display: flex;
align-items: center;
- min-height: 24px;
- padding: 0;
+ justify-content: flex-start;
+ width: 100%;
+ min-width: 0;
}
- .action-title {
+ .tree-root-expand {
display: inline-flex;
align-items: center;
gap: 6px;
+ margin: 0;
+ padding: 0;
+ border: 0;
+ border-radius: 4px;
+ background: transparent;
+ color: var(--td-text-color-secondary);
+ font-size: 14px;
+ line-height: 22px;
+ cursor: pointer;
flex: 0 1 auto;
min-width: 0;
+ max-width: 100%;
+
+ &:hover {
+ background: transparent;
+ color: var(--td-text-color-primary);
+ }
}
- .tree-root-summary {
- font-size: 14px;
- line-height: 1.55;
- color: var(--td-text-color-secondary);
+ .tree-root-status,
+ .tree-root-reference {
+ flex: 0 1 auto;
+ min-width: 0;
+ white-space: nowrap;
+ }
- :deep(strong) {
- font-weight: 600;
- color: var(--td-text-color-primary);
+ .tree-root-reference {
+ display: inline-flex;
+ align-items: center;
+ gap: 6px;
+
+ &::before {
+ content: '';
+ width: 3px;
+ height: 3px;
+ border-radius: 50%;
+ background: currentColor;
+ opacity: 0.65;
+ flex-shrink: 0;
}
}
- .action-show-icon {
- color: var(--td-text-color-placeholder);
- font-size: 14px;
+ .tree-root-expand__icon {
flex-shrink: 0;
+ font-size: 14px;
+ color: currentColor;
}
+
}
.tree-children {
@@ -570,38 +570,23 @@ watch(thinkingExpanded, (expanded) => {
}
}
-.rag-ref-step {
- .action-header {
- width: 100%;
- gap: 8px;
- }
-
- .action-title {
- gap: 12px;
- }
-
- .action-show-icon {
- color: var(--td-text-color-placeholder);
- font-size: 14px;
- flex-shrink: 0;
- }
-
- :deep(.refer-timeline.refer) {
- margin-top: 4px;
- padding-left: 0;
- }
-
- :deep(.refer-timeline .doc-group-chunks) {
- padding-left: 18px;
- }
-}
-
.tool-event {
.action-card {
position: relative;
background: transparent;
border: 0;
box-shadow: none;
+
+ &.has-reference-trigger {
+ cursor: pointer;
+
+ &:hover {
+ .action-name,
+ .results-summary-text {
+ color: var(--td-text-color-primary);
+ }
+ }
+ }
}
.action-header {
@@ -689,4 +674,16 @@ watch(thinkingExpanded, (expanded) => {
color: var(--td-text-color-secondary);
}
}
+
+@media (max-width: 640px) {
+ .tree-root {
+ .tree-root-toolbar {
+ gap: 8px;
+ }
+
+ .tree-root-expand {
+ max-width: 100%;
+ }
+ }
+}
</style>
diff --git a/frontend/src/views/chat/components/docInfo.vue b/frontend/src/views/chat/components/docInfo.vue
index 4951fd873..d8fc8a8eb 100644
--- a/frontend/src/views/chat/components/docInfo.vue
+++ b/frontend/src/views/chat/components/docInfo.vue
@@ -60,9 +60,11 @@ import { useRouter } from 'vue-router';
import { useI18n } from 'vue-i18n';
import { sanitizeHTML } from '@/utils/security';
import ContentPopup from './tool-results/ContentPopup.vue';
+import { useChatReferencesDrawer } from '@/composables/useChatReferencesDrawer';
const router = useRouter();
const { t } = useI18n();
+const referencesDrawer = useChatReferencesDrawer();
const props = defineProps({
content: {
@@ -91,6 +93,11 @@ const showReferBox = ref(false);
const expandedGroups = reactive({});
const referBoxSwitch = () => {
+ const refs = props.session?.knowledge_references;
+ if (referencesDrawer && refs?.length) {
+ referencesDrawer.open({ references: refs });
+ return;
+ }
showReferBox.value = !showReferBox.value;
};
@@ -139,6 +146,9 @@ const headerText = computed(() => {
if (docCount > 0) {
return t('chat.referencesDocCount', { count: docCount });
}
+ if (webCount > 0) {
+ return t('chat.referencesWebCount', { count: webCount });
+ }
return t('chat.referencesTitle', { count: total });
});
diff --git a/frontend/src/views/chat/index.vue b/frontend/src/views/chat/index.vue
index 0547f4cdb..39e0c028d 100644
--- a/frontend/src/views/chat/index.vue
+++ b/frontend/src/views/chat/index.vue
@@ -1,5 +1,9 @@
<template>
- <div class="chat" :class="{ 'is-embedded': embeddedMode, 'is-sidebar-collapsed': uiStore.sidebarCollapsed }">
+ <div class="chat" :class="{
+ 'is-embedded': embeddedMode,
+ 'is-sidebar-collapsed': uiStore.sidebarCollapsed,
+ 'has-references-panel': referencesDrawerVisible,
+ }">
<div ref="scrollContainer" class="chat_scroll_box" @scroll="handleScroll">
<div class="msg_list" :class="{ 'is-embedded': embeddedMode }">
<!-- 消息列表骨架屏 -->
@@ -107,6 +111,7 @@
<KnowledgeBaseEditorModal :visible="uiStore.showKBEditorModal" :mode="uiStore.kbEditorMode"
:kb-id="uiStore.currentKBId || undefined" :initial-type="uiStore.kbEditorType"
@update:visible="(val) => val ? null : uiStore.closeKBEditor()" @success="handleKBEditorSuccess" />
+ <ChatReferencesDrawer />
</template>
<script setup>
import { storeToRefs } from 'pinia';
@@ -128,6 +133,10 @@ import { useKnowledgeBaseCreationNavigation } from '@/hooks/useKnowledgeBaseCrea
import { useChatStreamHandler } from '@/composables/useChatStreamHandler';
import { useStickyBottomOnResize } from '@/composables/useStickyBottomOnResize';
import { clearCitationChunkCache } from '@/utils/citationChunkCache';
+import ChatReferencesDrawer from '@/components/ChatReferencesDrawer.vue';
+import { provideChatReferencesDrawer } from '@/composables/useChatReferencesDrawer';
+
+const { visible: referencesDrawerVisible } = provideChatReferencesDrawer();
const props = defineProps({
session_id: { type: String, default: '' },
@@ -879,6 +888,19 @@ onBeforeRouteUpdate((to, from, next) => {
overflow-x: hidden;
}
+ &:not(.is-embedded) {
+ @media (min-width: 960px) {
+ transition: padding-right 0.3s cubic-bezier(0.22, 0.61, 0.36, 1);
+ }
+ }
+
+ &.has-references-panel:not(.is-embedded) {
+ @media (min-width: 960px) {
+ padding-right: 420px;
+ box-sizing: border-box;
+ }
+ }
+
&.is-embedded :deep(.answers-input) {
position: relative;
transform: translateX(0);
@@ -1015,13 +1037,12 @@ onBeforeRouteUpdate((to, from, next) => {
.input-container {
min-height: 115px;
- // Keep the input visible when messages overflow: without flex-shrink: 0
- // a tall .chat_scroll_box can squeeze this container down to 0 height.
flex-shrink: 0;
margin: 0 auto;
width: 100%;
max-width: 800px;
box-sizing: border-box;
+ position: relative;
&.is-embedded {
max-width: 100%;
diff --git a/frontend/src/views/embed/EmbedBotMessage.vue b/frontend/src/views/embed/EmbedBotMessage.vue
index 843fe4dc6..07aa17a61 100644
--- a/frontend/src/views/embed/EmbedBotMessage.vue
+++ b/frontend/src/views/embed/EmbedBotMessage.vue
@@ -134,6 +134,9 @@ const { float: citationFloat, rebind: rebindCitations } = useEmbedCitationPopove
parentMd,
embedChannelIdRef,
embedTokenRef,
+ {
+ getKnowledgeReferences: () => props.session?.knowledge_references,
+ },
)
let citationCloseTimer: number | null = null
diff --git a/frontend/src/views/embed/EmbedChatCore.vue b/frontend/src/views/embed/EmbedChatCore.vue
index 96f8d1308..71f55ebc5 100644
--- a/frontend/src/views/embed/EmbedChatCore.vue
+++ b/frontend/src/views/embed/EmbedChatCore.vue
@@ -100,6 +100,7 @@
@stop-generation="handleStopGeneration"
/>
</div>
+ <ChatReferencesDrawer embedded-mode />
</div>
</template>
@@ -110,8 +111,12 @@ import { getEmbedSuggestedQuestions, onEmbedHostOpenWithQuery, type SuggestedQue
import EmbedInputField from '@/components/EmbedInputField.vue'
import EmbedBotMessage from '@/views/embed/EmbedBotMessage.vue'
import EmbedUserMessage from '@/views/embed/EmbedUserMessage.vue'
+import ChatReferencesDrawer from '@/components/ChatReferencesDrawer.vue'
+import { provideChatReferencesDrawer } from '@/composables/useChatReferencesDrawer'
import { useEmbedChatSession } from '@/composables/useEmbedChatSession'
+provideChatReferencesDrawer()
+
type EmbedImage = { url?: string; data?: string }
type EmbedAttachment = { file_name: string; file_size?: number }
diff --git a/internal/agent/tools/knowledge_search.go b/internal/agent/tools/knowledge_search.go
index 26ec71fbc..5f9d16203 100644
--- a/internal/agent/tools/knowledge_search.go
+++ b/internal/agent/tools/knowledge_search.go
@@ -1271,6 +1271,7 @@ func (t *KnowledgeSearchTool) formatOutput(
"result_index": i + 1,
"content": result.Content,
"knowledge_id": result.KnowledgeID,
+ "knowledge_base_id": result.KnowledgeBaseID,
"knowledge_title": result.KnowledgeTitle,
"match_type": result.MatchType,
"source_query": result.SourceQuery,