diff --git a/frontend/src/components/ChatCitationFloat.vue b/frontend/src/components/ChatCitationFloat.vue new file mode 100644 index 00000000..b2a42b84 --- /dev/null +++ b/frontend/src/components/ChatCitationFloat.vue @@ -0,0 +1,36 @@ + + + + + diff --git a/frontend/src/components/css/chat-citations.less b/frontend/src/components/css/chat-citations.less new file mode 100644 index 00000000..ba942992 --- /dev/null +++ b/frontend/src/components/css/chat-citations.less @@ -0,0 +1,152 @@ +.chat-citation-pills() { + :deep(.citation) { + display: inline-flex; + align-items: center; + gap: 2px; + vertical-align: baseline; + box-sizing: border-box; + border-radius: 999px; + padding: 0 5px; + font-size: 0.72em; + line-height: 1.45; + margin: 0 0.06em; + background-clip: padding-box; + transform: translateY(-0.04em); + } + + :deep(.citation-icon) { + display: inline-block; + width: 1em; + height: 1em; + flex-shrink: 0; + background-color: currentColor; + opacity: 0.68; + mask-size: contain; + mask-repeat: no-repeat; + mask-position: center; + -webkit-mask-size: contain; + -webkit-mask-repeat: no-repeat; + -webkit-mask-position: center; + } + + :deep(.citation-icon--book) { + mask-image: url('@/assets/img/ziliao.svg'); + -webkit-mask-image: url('@/assets/img/ziliao.svg'); + } + + :deep(.citation-icon--web) { + mask-image: url('@/assets/img/websearch-globe.svg'); + -webkit-mask-image: url('@/assets/img/websearch-globe.svg'); + } + + :deep(.citation-text), + :deep(.citation-domain) { + line-height: 1.45; + max-width: 180px; + overflow: hidden; + text-overflow: ellipsis; + } + + :deep(.citation-kb) { + background: color-mix(in srgb, var(--td-text-color-primary) 4%, transparent); + color: color-mix(in srgb, var(--td-text-color-secondary) 86%, var(--td-text-color-primary)); + border: 0; + box-shadow: inset 0 0 0 1px color-mix(in srgb, var(--td-text-color-primary) 10%, transparent); + cursor: pointer; + white-space: nowrap; + position: relative; + transition: background 0.15s ease, box-shadow 0.15s ease, color 0.15s ease; + } + + :deep(.citation-kb:hover) { + background: color-mix(in srgb, var(--td-text-color-primary) 7%, transparent); + box-shadow: inset 0 0 0 1px color-mix(in srgb, var(--td-text-color-primary) 18%, transparent); + color: var(--td-text-color-primary); + } + + :deep(.citation-web) { + background: color-mix(in srgb, var(--td-brand-color) 6%, transparent); + color: color-mix(in srgb, var(--td-brand-color) 72%, var(--td-text-color-secondary)); + border: 0; + box-shadow: inset 0 0 0 1px color-mix(in srgb, var(--td-brand-color) 17%, transparent); + cursor: pointer; + white-space: nowrap; + position: relative; + text-decoration: none; + transition: background 0.15s ease, box-shadow 0.15s ease, color 0.15s ease; + } + + :deep(.citation-web:hover) { + background: color-mix(in srgb, var(--td-brand-color) 10%, transparent); + box-shadow: inset 0 0 0 1px color-mix(in srgb, var(--td-brand-color) 28%, transparent); + color: color-mix(in srgb, var(--td-brand-color) 82%, var(--td-text-color-primary)); + } + + :deep(.citation-web:focus-visible), + :deep(.citation-kb:focus-visible) { + outline: 2px solid var(--td-component-border); + outline-offset: 2px; + } + + :deep(.citation-tip) { + display: none; + } + + :deep(a.wiki-content-link) { + color: var(--td-brand-color); + border-bottom: 1px dashed var(--td-brand-color); + text-decoration: none; + font-weight: 500; + transition: border-bottom-style 0.15s ease; + + &:hover { + border-bottom-style: solid; + text-decoration: none !important; + } + + &:focus-visible { + outline: 2px solid var(--td-brand-color); + outline-offset: 2px; + border-radius: 2px; + } + } +} + +.chat-citation-float { + position: absolute; + z-index: 10000; + max-width: 320px; + padding: 10px 12px; + border-radius: 8px; + background: var(--td-bg-color-container); + box-shadow: 0 6px 18px rgba(0, 0, 0, 0.18); + font-size: 12px; + line-height: 1.5; + color: var(--td-text-color-primary); + + &__title { + font-weight: 600; + color: var(--td-brand-color); + margin-bottom: 4px; + } + + &__link { + color: var(--td-brand-color); + word-break: break-all; + } + + &__body { + max-height: 200px; + overflow-y: auto; + white-space: pre-wrap; + } + + &__muted, + &__error { + color: var(--td-text-color-secondary); + } + + &__error { + color: var(--td-error-color); + } +} diff --git a/frontend/src/components/css/chat-citations.test.mjs b/frontend/src/components/css/chat-citations.test.mjs new file mode 100644 index 00000000..0da9af39 --- /dev/null +++ b/frontend/src/components/css/chat-citations.test.mjs @@ -0,0 +1,14 @@ +import assert from 'node:assert/strict' +import { readFileSync } from 'node:fs' +import { fileURLToPath } from 'node:url' +import { dirname, join } from 'node:path' +import test from 'node:test' + +const here = dirname(fileURLToPath(import.meta.url)) +const css = readFileSync(join(here, 'chat-citations.less'), 'utf8') + +test('citation pills use compact baseline-aligned source styling', () => { + assert.match(css, /border-radius:\s*999px/) + assert.match(css, /font-size:\s*0\.72em/) + assert.match(css, /box-shadow:\s*inset 0 0 0 1px/) +}) diff --git a/frontend/src/composables/useChatCitationPopover.ts b/frontend/src/composables/useChatCitationPopover.ts new file mode 100644 index 00000000..c9ce30c8 --- /dev/null +++ b/frontend/src/composables/useChatCitationPopover.ts @@ -0,0 +1,229 @@ +import { onBeforeUnmount, onMounted, ref, watch, type Ref } from 'vue' +import { useI18n } from 'vue-i18n' +import { getChunkByIdOnly } from '@/api/knowledge-base' +import { getEmbedChunkById } from '@/api/embed' +import { resolveCitationChunkId, type CitationKnowledgeRef } from '@/utils/citationMarkdown' +import { + getCitationChunkCache, + setCitationChunkCache, +} from '@/utils/citationChunkCache' + +export { clearCitationChunkCache } from '@/utils/citationChunkCache' + +type FloatState = { + visible: boolean + type: 'kb' | 'web' + top: number + left: number + title: string + content: string + url: string + loading: boolean + error: string +} + +export type CitationFloatState = FloatState + +export type ChatCitationPopoverOptions = { + getKnowledgeReferences?: () => CitationKnowledgeRef[] | null | undefined + embedChannelId?: () => string | undefined + embedToken?: () => string | undefined + sessionId?: () => string | undefined +} + +export function useChatCitationPopover( + rootRef: Ref, + options?: ChatCitationPopoverOptions, +) { + const { t } = useI18n() + + const getCacheScope = () => { + const channelId = options?.embedChannelId?.() + const token = options?.embedToken?.() + if (channelId && token) return `embed:${channelId}:${token}` + return options?.sessionId?.() || 'default' + } + + const float = ref({ + visible: false, + type: 'kb', + top: 0, + left: 0, + title: '', + content: '', + url: '', + loading: false, + error: '', + }) + + let hoverTimer: number | null = null + let closeTimer: number | null = null + + const positionFor = (el: HTMLElement, offsetY = 0) => { + const rect = el.getBoundingClientRect() + float.value.top = rect.bottom + window.scrollY + 6 + offsetY + float.value.left = Math.min(rect.left + window.scrollX, window.innerWidth - 320) + } + + const openWeb = (el: HTMLElement) => { + const url = el.getAttribute('data-url') || '' + float.value.type = 'web' + float.value.url = url + float.value.title = el.querySelector('.tip-title')?.textContent || '' + float.value.content = '' + float.value.loading = false + float.value.error = '' + float.value.visible = true + positionFor(el) + } + + const fetchChunkContent = async (chunkId: string) => { + const channelId = options?.embedChannelId?.() + const token = options?.embedToken?.() + if (channelId && token) { + return getEmbedChunkById(channelId, token, chunkId) + } + return getChunkByIdOnly(chunkId) + } + + const openKb = async (el: HTMLElement) => { + const rawChunkId = el.getAttribute('data-chunk-id') || '' + const title = el.getAttribute('data-doc') || '' + const kbId = el.getAttribute('data-kb-id') || '' + const chunkId = resolveCitationChunkId( + rawChunkId, + { doc: title, kbId }, + options?.getKnowledgeReferences?.(), + ) || rawChunkId + if (!chunkId) return + float.value.type = 'kb' + float.value.title = title + float.value.url = '' + float.value.visible = true + positionFor(el, 4) + + const scope = getCacheScope() + const cached = getCitationChunkCache(scope, chunkId) + if (cached) { + float.value.content = cached.content + float.value.error = cached.error || '' + float.value.loading = false + return + } + + float.value.loading = true + float.value.error = '' + float.value.content = '' + try { + const res = await fetchChunkContent(chunkId) + const content = String(res?.data?.content || '').trim() + if (!content) { + const msg = t('agentStream.citation.notFound') + setCitationChunkCache(scope, chunkId, { content: '', error: msg }) + float.value.error = msg + return + } + setCitationChunkCache(scope, chunkId, { content }) + float.value.content = content + } catch { + const msg = t('agentStream.citation.loadFailed') + setCitationChunkCache(scope, chunkId, { content: '', error: msg }) + float.value.error = msg + } finally { + float.value.loading = false + } + } + + const scheduleClose = () => { + if (closeTimer) window.clearTimeout(closeTimer) + closeTimer = window.setTimeout(() => { + const hoveredCitation = document.querySelector('.citation-kb:hover, .citation-web:hover') + const hoveredPopup = document.querySelector('.chat-citation-float:hover') + if (!hoveredCitation && !hoveredPopup) { + float.value.visible = false + } + }, 120) + } + + const cancelClose = () => { + if (closeTimer) { + window.clearTimeout(closeTimer) + closeTimer = null + } + } + + const onMouseOver = (e: Event) => { + const target = e.target as HTMLElement + const kbEl = target.closest?.('.citation-kb') as HTMLElement | null + const webEl = target.closest?.('.citation-web') as HTMLElement | null + if (!kbEl && !webEl) return + cancelClose() + if (hoverTimer) window.clearTimeout(hoverTimer) + hoverTimer = window.setTimeout(() => { + if (kbEl) void openKb(kbEl) + else if (webEl) openWeb(webEl) + }, kbEl ? 80 : 40) + } + + const onMouseOut = (e: Event) => { + const rt = (e as MouseEvent).relatedTarget as HTMLElement | null + if (rt?.closest?.('.citation-kb, .citation-web, .chat-citation-float')) return + if (hoverTimer) { + window.clearTimeout(hoverTimer) + hoverTimer = null + } + scheduleClose() + } + + const onClick = (e: Event) => { + const target = e.target as HTMLElement + const kbEl = target.closest?.('.citation-kb') as HTMLElement | null + if (kbEl) { + e.preventDefault() + e.stopPropagation() + void openKb(kbEl) + } + } + + const onViewportChange = () => { + if (float.value.visible) scheduleClose() + } + + const bind = () => { + const root = rootRef.value + if (!root) return + root.addEventListener('mouseover', onMouseOver, true) + root.addEventListener('mouseout', onMouseOut, true) + root.addEventListener('click', onClick, true) + window.addEventListener('scroll', onViewportChange, true) + window.addEventListener('resize', onViewportChange, true) + } + + const unbind = () => { + const root = rootRef.value + if (root) { + root.removeEventListener('mouseover', onMouseOver, true) + root.removeEventListener('mouseout', onMouseOut, true) + root.removeEventListener('click', onClick, true) + } + window.removeEventListener('scroll', onViewportChange, true) + window.removeEventListener('resize', onViewportChange, true) + } + + watch(rootRef, () => { + unbind() + bind() + }, { flush: 'post' }) + + onMounted(() => { + bind() + }) + + onBeforeUnmount(() => { + unbind() + if (hoverTimer) window.clearTimeout(hoverTimer) + if (closeTimer) window.clearTimeout(closeTimer) + }) + + return { float, rebind: () => { unbind(); bind() }, cancelClose, scheduleClose } +} diff --git a/frontend/src/composables/useEmbedCitationPopover.ts b/frontend/src/composables/useEmbedCitationPopover.ts index 604986be..fd7a7133 100644 --- a/frontend/src/composables/useEmbedCitationPopover.ts +++ b/frontend/src/composables/useEmbedCitationPopover.ts @@ -1,5 +1,9 @@ import { onBeforeUnmount, ref, unref, watch, type MaybeRef, type Ref } from 'vue' import { getEmbedChunkById } from '@/api/embed' +import { + getCitationChunkCache, + setCitationChunkCache, +} from '@/utils/citationChunkCache' type FloatState = { visible: boolean @@ -13,8 +17,6 @@ type FloatState = { error: string } -const chunkCache = new Map() - export function useEmbedCitationPopover( rootRef: Ref, channelId: MaybeRef, @@ -35,6 +37,8 @@ export function useEmbedCitationPopover( let hoverTimer: number | null = null let closeTimer: number | null = null + const getCacheScope = () => `embed:${unref(channelId)}:${unref(token)}` + const positionFor = (el: HTMLElement, offsetY = 0) => { const rect = el.getBoundingClientRect() float.value.top = rect.bottom + window.scrollY + 6 + offsetY @@ -63,7 +67,8 @@ export function useEmbedCitationPopover( float.value.visible = true positionFor(el, 4) - const cached = chunkCache.get(chunkId) + const scope = getCacheScope() + const cached = getCitationChunkCache(scope, chunkId) if (cached) { float.value.content = cached.content float.value.error = cached.error || '' @@ -77,11 +82,11 @@ export function useEmbedCitationPopover( try { const res = await getEmbedChunkById(unref(channelId), unref(token), chunkId) const content = String(res?.data?.content || '').trim() - chunkCache.set(chunkId, { content }) + setCitationChunkCache(scope, chunkId, { content }) float.value.content = content } catch { const msg = 'Failed to load' - chunkCache.set(chunkId, { content: '', error: msg }) + setCitationChunkCache(scope, chunkId, { content: '', error: msg }) float.value.error = msg } finally { float.value.loading = false diff --git a/frontend/src/utils/chatMessageShared.ts b/frontend/src/utils/chatMessageShared.ts index fedf938e..f4aad38e 100644 --- a/frontend/src/utils/chatMessageShared.ts +++ b/frontend/src/utils/chatMessageShared.ts @@ -1,6 +1,9 @@ import i18n from '@/i18n'; +import { buildMermaidBlockHtml, buildMermaidLoadingHtml } from '@/utils/markdownEnhancements'; const STREAMING_IMAGE_PLACEHOLDER = ''; +const STREAMING_MERMAID_PLACEHOLDER = buildMermaidLoadingHtml(); +const MERMAID_FENCE_START = '```mermaid'; export const replaceIncompleteImageWithPlaceholder = (content: string): string => { if (!content) return ''; @@ -23,6 +26,65 @@ export const replaceIncompleteImageWithPlaceholder = (content: string): string = return content; }; +/** Hide an unclosed trailing ```mermaid fence while streaming to avoid layout jitter. */ +export const replaceIncompleteMermaidWithPlaceholder = (content: string): string => { + if (!content) return ''; + + const start = content.lastIndexOf(MERMAID_FENCE_START); + if (start < 0) return content; + + const tail = content.slice(start + MERMAID_FENCE_START.length); + if (tail.includes('```')) return content; + + return content.slice(0, start) + STREAMING_MERMAID_PLACEHOLDER; +}; + +const MERMAID_BLOCK_RE = /```mermaid[\s\S]*?```/; + +/** Keep mermaid as a stable placeholder for the whole stream; render once at the end. */ +export const maskMermaidBlocksForStreaming = (content: string): string => { + if (!content) return ''; + const masked = content.replace(MERMAID_BLOCK_RE, STREAMING_MERMAID_PLACEHOLDER); + return replaceIncompleteMermaidWithPlaceholder(masked); +}; + +export const hasCompleteMermaidBlock = (content: string): boolean => { + return MERMAID_BLOCK_RE.test(content); +}; + +/** While streaming: loading placeholder for mermaid; swap to cached SVG after sanitize. */ +export const prepareStreamingMermaidMarkdown = ( + content: string, + _cachedSvgHtml?: string | null, +): string => { + if (!content) return ''; + + if (hasCompleteMermaidBlock(content)) { + return maskMermaidBlocksForStreaming(content); + } + + return replaceIncompleteMermaidWithPlaceholder(content); +}; + +export const extractFirstMermaidCode = (content: string): string | null => { + const match = content.match(/```mermaid([\s\S]*?)```/); + return match?.[1]?.trim() || null; +}; + +const STREAMING_MERMAID_LOADING_RE = /
]*>[\s\S]*?
]*>[\s\S]*?<\/div>[\s\S]*?<\/div>/g; + +/** Inject trusted Mermaid SVG after DOMPurify, replacing the streaming loading shell. */ +export const injectCachedMermaidSvg = ( + html: string, + cachedSvgHtml: string | null | undefined, +): string => { + if (!html || !cachedSvgHtml) return html; + return html.replace( + STREAMING_MERMAID_LOADING_RE, + buildMermaidBlockHtml(cachedSvgHtml, 'data-mermaid="cached"'), + ); +}; + export const formatManualTitle = (question?: string): string => { if (!question) { return i18n.global.t('chat.sessionExcerpt'); diff --git a/frontend/src/utils/citationChunkCache.test.mjs b/frontend/src/utils/citationChunkCache.test.mjs new file mode 100644 index 00000000..b8ed94ae --- /dev/null +++ b/frontend/src/utils/citationChunkCache.test.mjs @@ -0,0 +1,38 @@ +import assert from 'node:assert/strict' +import test from 'node:test' +import { + clearCitationChunkCache, + getCitationChunkCache, + makeCitationCacheKey, + setCitationChunkCache, +} from './citationChunkCache.ts' + +test('makeCitationCacheKey combines scope and chunkId', () => { + assert.equal(makeCitationCacheKey('session-1', 'chunk-a'), 'session-1::chunk-a') + assert.equal( + makeCitationCacheKey('embed:ch:tok', 'chunk-b'), + 'embed:ch:tok::chunk-b', + ) +}) + +test('get/set are isolated per scope', () => { + clearCitationChunkCache() + setCitationChunkCache('session-1', 'chunk-a', { content: 'one' }) + setCitationChunkCache('session-2', 'chunk-a', { content: 'two' }) + + assert.equal(getCitationChunkCache('session-1', 'chunk-a')?.content, 'one') + assert.equal(getCitationChunkCache('session-2', 'chunk-a')?.content, 'two') +}) + +test('clearCitationChunkCache clears one scope or all', () => { + clearCitationChunkCache() + setCitationChunkCache('session-1', 'chunk-a', { content: 'one' }) + setCitationChunkCache('session-2', 'chunk-a', { content: 'two' }) + + clearCitationChunkCache('session-1') + assert.equal(getCitationChunkCache('session-1', 'chunk-a'), undefined) + assert.equal(getCitationChunkCache('session-2', 'chunk-a')?.content, 'two') + + clearCitationChunkCache() + assert.equal(getCitationChunkCache('session-2', 'chunk-a'), undefined) +}) diff --git a/frontend/src/utils/citationChunkCache.ts b/frontend/src/utils/citationChunkCache.ts new file mode 100644 index 00000000..1a847d60 --- /dev/null +++ b/frontend/src/utils/citationChunkCache.ts @@ -0,0 +1,35 @@ +export type CitationChunkCacheValue = { content: string; error?: string } + +const chunkCache = new Map() + +export function makeCitationCacheKey(scope: string, chunkId: string): string { + return `${scope}::${chunkId}` +} + +export function getCitationChunkCache( + scope: string, + chunkId: string, +): CitationChunkCacheValue | undefined { + return chunkCache.get(makeCitationCacheKey(scope, chunkId)) +} + +export function setCitationChunkCache( + scope: string, + chunkId: string, + value: CitationChunkCacheValue, +): void { + chunkCache.set(makeCitationCacheKey(scope, chunkId), value) +} + +export function clearCitationChunkCache(scope?: string): void { + if (scope === undefined) { + chunkCache.clear() + return + } + const prefix = `${scope}::` + for (const key of chunkCache.keys()) { + if (key.startsWith(prefix)) { + chunkCache.delete(key) + } + } +} diff --git a/frontend/src/utils/citationMarkdown.ts b/frontend/src/utils/citationMarkdown.ts index 8678a985..acf23e06 100644 --- a/frontend/src/utils/citationMarkdown.ts +++ b/frontend/src/utils/citationMarkdown.ts @@ -1,6 +1,22 @@ /** Shared citation tag preprocessing for chat markdown (QA + agent). */ +/** Self-closing or unclosed `` / `` tags from model output. */ +export const KB_WEB_TAG_RE = /<(?:kb|web)\b[^>]*?\s*\/?>/g +const KB_TAG_ATTR_RE = /]*?)\s*\/?>/g +const WEB_TAG_ATTR_RE = /]*?)\s*\/?>/g + const ATTRIBUTE_REGEX = /([\w-]+)\s*=\s*"([^"]*)"/g +const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i + +export type CitationKnowledgeRef = { + id?: string + knowledge_id?: string + knowledge_title?: string + knowledge_filename?: string + chunk_index?: number + chunk_type?: string + knowledge_base_id?: string +} function parseTagAttributes(attrString: string): Record { const attributes: Record = {} @@ -30,12 +46,88 @@ function truncateMiddle(text: string, maxLength = 13): string { return `${start}...${end}` } +function normalizeDocTitle(title: string): string { + return title.trim().toLowerCase() +} + +function docTitlesMatch(a: string, b: string): boolean { + if (!a || !b) return false + const na = normalizeDocTitle(a) + const nb = normalizeDocTitle(b) + return na === nb || na.includes(nb) || nb.includes(na) +} + +/** Map model context index (1, FAQ-1, DOC-2) to the real chunk UUID from retrieval results. */ +export function resolveCitationChunkId( + rawChunkId: string, + attrs: { doc?: string; kbId?: string }, + refs?: CitationKnowledgeRef[] | null, +): string { + const raw = String(rawChunkId || '').trim() + if (!raw || UUID_RE.test(raw)) return raw + + const list = (refs || []).filter((r) => r && r.chunk_type !== 'web_search') + if (!list.length) return raw + + const doc = (attrs.doc || '').trim() + const kbId = (attrs.kbId || '').trim() + + if (doc) { + const byDoc = list.find( + (r) => + docTitlesMatch(doc, r.knowledge_title || '') || + docTitlesMatch(doc, r.knowledge_filename || ''), + ) + if (byDoc?.id) return byDoc.id + } + + const faqMatch = raw.match(/^FAQ-(\d+)$/i) + if (faqMatch) { + const faqRefs = list.filter((r) => r.chunk_type === 'faq') + const hit = faqRefs[parseInt(faqMatch[1], 10) - 1] + if (hit?.id) return hit.id + } + + const docMatch = raw.match(/^DOC-(\d+)$/i) + if (docMatch) { + const docRefs = list.filter((r) => r.chunk_type !== 'faq') + const hit = docRefs[parseInt(docMatch[1], 10) - 1] + if (hit?.id) return hit.id + } + + const num = parseInt(raw, 10) + if (!Number.isNaN(num) && String(num) === raw) { + const byPos = list[num - 1] + if (byPos?.id) return byPos.id + const byChunkIndex = list.find((r) => r.chunk_index === num || r.chunk_index === num - 1) + if (byChunkIndex?.id) return byChunkIndex.id + } + + if (kbId) { + const scoped = list.filter((r) => r.knowledge_base_id === kbId) + if (doc) { + const byDoc = scoped.find( + (r) => + docTitlesMatch(doc, r.knowledge_title || '') || + docTitlesMatch(doc, r.knowledge_filename || ''), + ) + if (byDoc?.id) return byDoc.id + } + if (scoped.length === 1 && scoped[0].id) return scoped[0].id + } + + return raw +} + /** Convert / / [[wiki]] tags into inline citation HTML. */ -export function preprocessCitationTags(contentStr: string): string { +export function preprocessCitationTags( + contentStr: string, + refs?: CitationKnowledgeRef[] | null, +): string { if (!contentStr.trim()) return '' return contentStr - .replace(/]*)\/>/g, (_m, attrString: string) => { + .replace(WEB_TAG_ATTR_RE, (_m, attrString: string) => { const attrs = parseTagAttributes(attrString) const url = attrs.url || '' const title = attrs.title || '' @@ -52,20 +144,21 @@ export function preprocessCitationTags(contentStr: string): string { } const safeTitle = escapeHtml(title) const safeUrl = escapeHtml(url) - return `${domain}${safeTitle}${safeUrl}` + return `${domain}${safeTitle}${safeUrl}` }) - .replace(/]*)\/>/g, (_m, attrString: string) => { + .replace(KB_TAG_ATTR_RE, (_m, attrString: string) => { const attrs = parseTagAttributes(attrString) const doc = attrs.doc || '' - const chunkId = attrs.chunk_id || attrs.chunkId || '' + const rawChunkId = attrs.chunk_id || attrs.chunkId || '' const kbId = attrs.kb_id || attrs.kbId || '' + const chunkId = resolveCitationChunkId(rawChunkId, { doc, kbId }, refs) if (!doc || !chunkId) return '' const safeDoc = escapeHtml(doc) const safeKbId = escapeHtml(kbId) const safeChunkId = escapeHtml(chunkId) const displayDoc = escapeHtml(truncateMiddle(doc)) - return `${displayDoc}…` + return `${displayDoc}…` }) .replace(/\[\[([^\]]+)\]\]/g, (match, inner: string) => { const pipeIdx = inner.indexOf('|') @@ -85,7 +178,10 @@ export function preprocessCitationTags(contentStr: string): string { const HTML_PLACEHOLDER_RE = /@@WEKNORA_HTML_PLACEHOLDER_(\d+)@@/g /** Protect citation HTML from markdown parser; restore after marked.parse. */ -export function extractCitationHtmlPlaceholders(contentStr: string): { content: string; htmlSnippets: string[] } { +export function extractCitationHtmlPlaceholders( + contentStr: string, + refs?: CitationKnowledgeRef[] | null, +): { content: string; htmlSnippets: string[] } { const htmlSnippets: string[] = [] const storeHtml = (html: string): string => { const idx = htmlSnippets.length @@ -94,8 +190,8 @@ export function extractCitationHtmlPlaceholders(contentStr: string): { content: } const content = contentStr - .replace(/<(?:kb|web)\b[^>]*\/>/g, (match) => storeHtml(preprocessCitationTags(match))) - .replace(/\[\[([^\]]+)\]\]/g, (match) => storeHtml(preprocessCitationTags(match))) + .replace(KB_WEB_TAG_RE, (match) => storeHtml(preprocessCitationTags(match, refs))) + .replace(/\[\[([^\]]+)\]\]/g, (match) => storeHtml(preprocessCitationTags(match, refs))) return { content, htmlSnippets } } @@ -105,10 +201,67 @@ export function restoreCitationHtmlPlaceholders(html: string, htmlSnippets: stri return html.replace(HTML_PLACEHOLDER_RE, (_match, idx) => htmlSnippets[Number(idx)] || '') } +/** Collapse newlines around / so marked keeps citations inline. */ +export function joinCitationTagsToPreviousLine(content: string): string { + if (!content) return content + + let result = content + + // Newlines between consecutive citation tags + let prev = '' + while (result !== prev) { + prev = result + result = result.replace( + /(<(?:kb|web)\b[^>]*?\s*\/?>)\s*\n+\s*(<(?:kb|web)\b)/gi, + '$1 $2', + ) + } + + // Blank lines before citations: join to previous prose, but keep a break after lists + result = result.replace(/\n[ \t]*\n+([ \t]*<(?:kb|web)\b)/gi, (match, kbStart, offset, full) => { + const before = full.slice(0, offset) + const lastLine = before.split('\n').filter((line) => line.trim()).pop() || '' + const isListItem = /^\s*(\d+\.|[-*+])\s+\S/.test(lastLine) + return isListItem ? `\n\n${kbStart}` : ` ${kbStart}` + }) + + // Single newline before citation when it follows text or another citation (not after a blank line) + result = result.replace( + /(?]*?\s*\/?>|[ \t]*\S[^\n]*?)\n([ \t]*<(?:kb|web)\b)/g, + '$1 $2', + ) + + return result +} + +const CITATION_HTML_FRAGMENT = + '(?:)' + +/** Merge citation-only

blocks into the preceding paragraph (marked splits on newlines). */ +export function collapseStandaloneCitationParagraphs(html: string): string { + if (!html || !html.includes('citation')) return html + + const mergePattern = new RegExp( + `(<\\/(?:p|li)>)\\s*(?:

\\s*<\\/p>\\s*)*

\\s*(${CITATION_HTML_FRAGMENT})\\s*<\\/p>`, + 'g', + ) + + let result = html + let prev = '' + while (result !== prev) { + prev = result + result = result.replace(mergePattern, (_match, closeTag: string, citation: string) => { + return ` ${citation}${closeTag}` + }) + } + + return result +} + /** Preserve raw / tags before sanitizers that would strip them. */ export function preserveCitationTags(contentStr: string): { text: string; tags: string[] } { const tags: string[] = [] - const text = contentStr.replace(/<(?:kb|web)\b[^>]*\/>/g, (match) => { + const text = contentStr.replace(KB_WEB_TAG_RE, (match) => { const idx = tags.length tags.push(match) return `\x00TAG${idx}\x00` diff --git a/frontend/src/views/chat/components/botmsg.vue b/frontend/src/views/chat/components/botmsg.vue index 2092a6c2..7bc9bf94 100644 --- a/frontend/src/views/chat/components/botmsg.vue +++ b/frontend/src/views/chat/components/botmsg.vue @@ -3,23 +3,27 @@

- + - + {{ item.name }}
- - +
+ + +
+
@@ -40,10 +44,12 @@
- + - + @@ -52,28 +58,29 @@ - +
-
{{ $t('common.loading') }}
+
{{ + $t('common.loading') }}
+ + +