diff --git a/frontend/src/components/ChatReferencesDrawer.vue b/frontend/src/components/ChatReferencesDrawer.vue new file mode 100644 index 00000000..b2f55dbf --- /dev/null +++ b/frontend/src/components/ChatReferencesDrawer.vue @@ -0,0 +1,580 @@ + + + + + + + + + + + + + + + diff --git a/frontend/src/composables/useChatCitationPopover.ts b/frontend/src/composables/useChatCitationPopover.ts index c9ce30c8..b1142ec3 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 00000000..72dab077 --- /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 + references: Ref + highlight: Ref + messageId: Ref + sourceKey: Ref + open: (options: ChatReferencesDrawerOpenOptions) => void + toggle: (options: ChatReferencesDrawerOpenOptions) => boolean + close: () => void + setHighlight: (highlight: ReferenceHighlightTarget | null) => void +} + +const CHAT_REFERENCES_DRAWER_KEY: InjectionKey = Symbol( + 'chatReferencesDrawer', +) + +export function provideChatReferencesDrawer(): ChatReferencesDrawerContext { + const visible = ref(false) + const references = ref([]) + const highlight = ref(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 fd7a7133..28142e08 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, channelId: MaybeRef, token: MaybeRef, + options?: EmbedCitationPopoverOptions, ) { + const referencesDrawer = useChatReferencesDrawer() const float = ref({ 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 d5bc7f16..dc652652 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 1bd9eea3..d207705d 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 42336379..670bef39 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 7775a511..d976bcb7 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 ef1ce948..20d90f57 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; } - diff --git a/frontend/src/utils/referenceSources.test.mjs b/frontend/src/utils/referenceSources.test.mjs new file mode 100644 index 00000000..bcbf151f --- /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 00000000..50e89fe3 --- /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 +} + +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() + + 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() + + 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 0817014b..f1f80dad 100644 --- a/frontend/src/views/chat/components/AgentStreamDisplay.vue +++ b/frontend/src/views/chat/components/AgentStreamDisplay.vue @@ -102,10 +102,17 @@ - + '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)" + > + @@ -153,7 +160,7 @@ - - + '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)" + > + - 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(); + + 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 7fc80f5a..ee991418 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('