refactor(frontend): share citation popover lifecycle

main
wizardchen 2026-09-17 14:56:51 +08:00 committed by lyingbug
parent 8fbee673e6
commit d645334d08
6 changed files with 574 additions and 459 deletions

View File

@ -75,11 +75,21 @@
- 新增 11 项行为测试,包含真实面板 setup 的配置切换、卸载失败展示、相同 Skill ID 重试、异步请求迟到和卸载清理;替换原有一项订阅源码正则断言。
- `scripts/verify_frontend_pr.sh` 通过:927 项前端测试、类型检查和生产构建。面板 template/style 与本批基线逐字节一致;未做浏览器视觉验收,未修改或测试后端。
## 第四批已实施:聊天引用浮层
基于第三批合入并同步后的 `42e616398`,`useChatCitationPopover` 与 `useEmbedCitationPopover` 改为复用 `useCitationPopover`。计入新增共享实现后,生产源码净减少 174 行。
- 统一浮层状态、定位、悬停延迟、关闭计时、引用抽屉和事件绑定;两个入口保留 API 选择、缓存作用域和错误展示策略。独立嵌入入口即使凭证为空,也继续只调用嵌入接口。
- 保留主聊天的会话缓存、嵌入的 channel/token 缓存隔离、主聊天滚动/缩放关闭逻辑、嵌入 Wiki 点击拦截,以及两种入口原有的悬停引用 ID 解析差异。
- 绑定对象单独记录,节点替换时移除旧节点监听;根节点、作用域或浮层目标变化后,迟到请求不会覆盖当前内容或写回缓存。卸载时清理监听和计时器。
- 嵌入消息组件直接使用共享关闭计时器,修复触发区与浮层之间无法取消彼此关闭任务的问题;相同节点的流式内容更新不会重置浮层。
- 新增 15 项真实 composable 行为测试,覆盖两个入口、接口路由、缓存、引用抽屉、请求竞争、计时和 Vue 挂载/卸载生命周期。
- `scripts/verify_frontend_pr.sh` 通过:948 项测试通过,1 项原有浏览器场景测试跳过,类型检查和生产构建通过。嵌入消息 template/style 与本批基线逐字节一致;未做浏览器视觉验收,未修改或测试后端。
## 后续优先级
| 优先级 | 证据 | 建议边界 | 验证重点 |
| --- | --- | --- | --- |
| P1 | `useChatCitationPopover.ts` 与 `useEmbedCitationPopover.ts` 重复浮层状态、定位、计时和事件绑定 | 共享交互状态;通过参数提供内容加载、缓存作用域和点击行为 | 普通/嵌入鉴权、缓存隔离、根节点替换、悬停竞争与卸载 |
| P2 | `AgentEditorModal.vue` 6,756 行,其中 script 3,023 行;近期变更 9 次 | 按提示词编辑、知识库选择、工具配置分离状态和表单序列化责任 | 编辑回填、模式切换、保存 payload 保持兼容 |
| P2 | `WikiBrowser.vue` 6,592 行,其中 script 4,086 行;`FAQEntryManager.vue` 5,650 行,其中 style 2,780 行 | 分开文档导航/编辑状态、批量动作与可复用展示区域 | 页面切换后的异步结果、选中项、保存与批量操作 |
| P2 | `knowledge_process.go` 4,091 行;`processChunks` 470 行、`ProcessDocument` 441 行 | 先划分分块入库、摘要、问题生成、重解析阶段的输入与输出,再抽函数 | 任务归属、取消、失败回写、重试与索引状态 |
@ -130,4 +140,4 @@
- 构建仍报告大 chunk 提示;本轮未以 bundle 体积为目标,也没有测量构建前后的体积差异。
- 未修改后端,未运行后端测试;未做浏览器视觉验收。
下一批优先处理主聊天与嵌入聊天引用浮层的重复。涉及聊天、任务重试、权限或共享状态的改动应单独成批,以可验证的行为等价为边界。
下一批优先逐包核实并清理未引用 Go 私有函数候选,再处理后端具体重复逻辑。涉及聊天、任务重试、权限或共享状态的改动应单独成批,以可验证的行为等价为边界。

View File

@ -1,29 +1,12 @@
import { onBeforeUnmount, onMounted, ref, watch, type Ref } from 'vue'
import 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'
import { useChatReferencesDrawer } from '@/composables/useChatReferencesDrawer'
import type { CitationKnowledgeRef } from '@/utils/citationMarkdown'
import { useCitationPopover } from './useCitationPopover'
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 { CitationFloatState } from './useCitationPopover'
export type ChatCitationPopoverOptions = {
getKnowledgeReferences?: () => CitationKnowledgeRef[] | null | undefined
@ -32,230 +15,22 @@ export type ChatCitationPopoverOptions = {
sessionId?: () => string | undefined
}
export function useChatCitationPopover(
rootRef: Ref<HTMLElement | null>,
options?: ChatCitationPopoverOptions,
) {
export function useChatCitationPopover(rootRef: Ref<HTMLElement | null>, options?: ChatCitationPopoverOptions) {
const { t } = useI18n()
const referencesDrawer = useChatReferencesDrawer()
const getCacheScope = () => {
const channelId = options?.embedChannelId?.()
const token = options?.embedToken?.()
if (channelId && token) return `embed:${channelId}:${token}`
return options?.sessionId?.() || 'default'
}
const float = ref<FloatState>({
visible: false,
type: 'kb',
top: 0,
left: 0,
title: '',
content: '',
url: '',
loading: false,
error: '',
return useCitationPopover(rootRef, {
mode: 'chat',
getKnowledgeReferences: options?.getKnowledgeReferences,
getCacheScope: () => {
const channel = options?.embedChannelId?.()
const token = options?.embedToken?.()
return channel && token ? `embed:${channel}:${token}` : options?.sessionId?.() || 'default'
},
fetchChunk: (chunkId) => {
const channel = options?.embedChannelId?.()
const token = options?.embedToken?.()
return channel && token ? getEmbedChunkById(channel, token, chunkId) : getChunkByIdOnly(chunkId)
},
notFoundError: () => t('agentStream.citation.notFound'),
loadError: () => t('agentStream.citation.loadFailed'),
})
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 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)
}
}
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 }
}

View File

@ -0,0 +1,279 @@
import assert from 'node:assert/strict'
import { readFileSync } from 'node:fs'
import { runInNewContext } from 'node:vm'
import test from 'node:test'
import ts from 'typescript'
import * as vue from 'vue'
import * as citationMarkdown from '../utils/citationMarkdown.ts'
import type { useChatCitationPopover } from './useChatCitationPopover.ts'
import type { useEmbedCitationPopover } from './useEmbedCitationPopover.ts'
const compiled = new Map<string, string>()
for (const file of ['useCitationPopover', 'useChatCitationPopover', 'useEmbedCitationPopover', '../utils/citationChunkCache']) {
compiled.set(file, ts.transpileModule(readFileSync(new URL(`${file}.ts`, import.meta.url), 'utf8'), {
compilerOptions: { module: ts.ModuleKind.CommonJS, target: ts.ScriptTarget.ES2022 },
}).outputText)
}
const flush = async () => { await new Promise(resolve => setImmediate(resolve)); await vue.nextTick() }
function deferred() {
let resolve!: (value: { data: { content: string } }) => void
let reject!: (reason: Error) => void
const promise = new Promise<{ data: { content: string } }>((yes, no) => { resolve = yes; reject = no })
return { promise, resolve: (content: string) => resolve({ data: { content } }), reject }
}
class Element {
listeners = new Map<string, Set<(event: any) => void>>()
constructor(readonly className = '', readonly attrs: Record<string, string> = {}) {}
addEventListener(name: string, listener: (event: any) => void) {
if (!this.listeners.has(name)) this.listeners.set(name, new Set())
this.listeners.get(name)!.add(listener)
}
removeEventListener(name: string, listener: (event: any) => void) { this.listeners.get(name)?.delete(listener) }
closest(selector: string) { return selector.split(',').some(s => s.trim() === `.${this.className}`) ? this : null }
getAttribute(name: string) { return this.attrs[name] ?? null }
getBoundingClientRect() { return { bottom: 20, left: 900 } }
querySelector(selector: string) { return selector === '.tip-title' ? { textContent: 'Web title' } : null }
fire(name: string, target: Element = this, relatedTarget: Element | null = null) {
const event = { target, relatedTarget, prevented: false, stopped: false,
preventDefault() { this.prevented = true }, stopPropagation() { this.stopped = true } }
for (const listener of this.listeners.get(name) || []) listener(event)
return event
}
get listenerCount() { return [...this.listeners.values()].reduce((n, listeners) => n + listeners.size, 0) }
}
const kb = (id = 'chunk') => new Element('citation-kb', { 'data-chunk-id': id, 'data-doc': 'Document' })
const web = () => new Element('citation-web', { 'data-url': 'https://example.com/source' })
function fixture(mode: 'chat' | 'embed', options: { drawer?: boolean; refs?: citationMarkdown.CitationKnowledgeRef[] } = {}) {
const timers = new Map<number, { at: number; callback: () => void }>()
let now = 0, nextId = 0, hovered = false
const win = Object.assign(new Element(), {
scrollX: 10, scrollY: 30, innerWidth: 1000,
setTimeout(callback: () => void, delay: number) { const id = ++nextId; timers.set(id, { at: now + delay, callback }); return id },
clearTimeout(id: number) { timers.delete(id) },
})
const tick = (ms: number) => {
const end = now + ms
while (true) {
const first = [...timers].filter(([, timer]) => timer.at <= end).sort((a, b) => a[1].at - b[1].at)[0]
if (!first) break
now = first[1].at; timers.delete(first[0]); first[1].callback()
}
now = end
}
const requests: Array<{ route: string; args: string[]; pending: ReturnType<typeof deferred> }> = []
const request = (route: string, ...args: string[]) => {
const pending = deferred(); requests.push({ route, args, pending }); return pending.promise
}
const drawerCalls: any[] = []
const modules: Record<string, any> = {}
const load = (name: string): any => {
if (modules[name]) return modules[name]
const exports = modules[name] = {}
runInNewContext(compiled.get(name)!, {
exports, window: win, document: { querySelector: () => hovered ? {} : null },
require(path: string) {
if (path === 'vue') return vue
if (path === 'vue-i18n') return { useI18n: () => ({ t: (key: string) => key }) }
if (path === '@/utils/citationMarkdown') return citationMarkdown
if (path === '@/utils/citationChunkCache') return load('../utils/citationChunkCache')
if (path === '@/composables/useChatReferencesDrawer') return { useChatReferencesDrawer: () => options.drawer ? { open: (args: any) => drawerCalls.push(args) } : null }
if (path === './useCitationPopover') return load('useCitationPopover')
if (path === '@/api/knowledge-base') return { getChunkByIdOnly: (...args: string[]) => request('chat', ...args) }
if (path === '@/api/embed') return { getEmbedChunkById: (...args: string[]) => request('embed', ...args) }
throw new Error(`Unexpected import: ${path}`)
},
})
return exports
}
const channel = vue.ref(mode === 'embed' ? 'channel' : ''), token = vue.ref(mode === 'embed' ? 'token' : '')
const session = vue.ref('session-a'), refs = vue.ref(options.refs || [])
const root = vue.shallowRef<HTMLElement | null>(new Element() as unknown as HTMLElement)
let state!: ReturnType<typeof useChatCitationPopover>
const renderer = vue.createRenderer<any, any>({
patchProp() {}, insert() {}, remove() {}, setText() {}, setElementText() {},
createElement: () => ({}), createText: () => ({}), createComment: () => ({}), parentNode: () => null, nextSibling: () => null,
})
const app = renderer.createApp({ setup() {
const common = { getKnowledgeReferences: () => refs.value }
state = mode === 'chat'
? (load('useChatCitationPopover').useChatCitationPopover as typeof useChatCitationPopover)(root, {
...common, sessionId: () => session.value, embedChannelId: () => channel.value, embedToken: () => token.value,
})
: (load('useEmbedCitationPopover').useEmbedCitationPopover as typeof useEmbedCitationPopover)(root, channel, token, common)
return () => null
} })
app.mount({})
return {
state, root, channel, token, session, refs, requests, drawerCalls, timers, win, tick,
cache: load('../utils/citationChunkCache'), close: () => app.unmount(),
setHovered: (value: boolean) => { hovered = value },
fire: (name: string, target?: Element, related?: Element | null) => (root.value as unknown as Element).fire(name, target, related),
}
}
for (const mode of ['chat', 'embed'] as const) {
test(`${mode}: hover delay, positioning, cancellation and popup close share one timer`, async t => {
const f = fixture(mode); t.after(f.close)
f.fire('mouseover', kb()); f.tick(79)
assert.equal(f.requests.length, 0)
f.fire('mouseout', kb()); f.tick(200)
assert.equal(f.requests.length, 0)
f.fire('mouseover', kb()); f.tick(80)
assert.equal(f.requests.length, 1)
assert.equal(f.state.float.value.top, 60)
assert.equal(f.state.float.value.left, 680)
f.requests[0]!.pending.resolve(' body '); await flush()
assert.equal(f.state.float.value.content, 'body')
f.fire('mouseout', kb()); f.state.cancelClose(); f.tick(120)
assert.equal(f.state.float.value.visible, true, 'entering the popup cancels the trigger close')
f.state.scheduleClose(); f.fire('mouseover', kb()); f.tick(120)
assert.equal(f.state.float.value.visible, true, 'returning to a citation cancels the popup close')
assert.equal(f.requests.length, 1, 'repeated hover reuses cache')
f.fire('mouseout', kb(), new Element(`${mode}-citation-float`)); f.tick(120)
assert.equal(f.state.float.value.visible, true)
f.state.scheduleClose(); f.tick(120)
assert.equal(f.state.float.value.visible, false)
f.fire('mouseover', web()); f.tick(39)
assert.equal(f.state.float.value.visible, false)
f.tick(1)
assert.equal(f.state.float.value.top, 56)
assert.equal(f.state.float.value.title, 'Web title')
assert.equal(f.state.float.value.url, 'https://example.com/source')
})
test(`${mode}: late responses cannot overwrite newer citations or cached results`, async t => {
const f = fixture(mode); t.after(f.close)
f.fire('click', kb('a')); f.fire('click', kb('b'))
f.requests[0]!.pending.resolve('old'); await flush()
assert.equal(f.state.float.value.loading, true)
assert.equal(f.state.float.value.content, '')
f.requests[1]!.pending.resolve('new'); await flush()
assert.equal(f.state.float.value.content, 'new')
f.fire('click', kb('c')); f.fire('click', web())
f.requests[2]!.pending.reject(new Error('late failure')); await flush()
assert.equal(f.state.float.value.type, 'web')
assert.equal(f.state.float.value.error, '')
assert.equal(f.state.float.value.loading, false)
f.fire('click', kb('d')); f.fire('click', kb('b'))
f.requests[3]!.pending.resolve('late success'); await flush()
assert.equal(f.state.float.value.content, 'new')
})
test(`${mode}: root replacement detaches listeners and discards pending hovers and loads`, async t => {
const f = fixture(mode); t.after(f.close)
const oldRoot = f.root.value as unknown as Element
f.fire('click', kb()); f.fire('mouseover', web())
f.root.value = new Element() as unknown as HTMLElement
await vue.nextTick()
assert.equal(oldRoot.listenerCount, 0)
assert.equal(f.state.float.value.visible, false)
f.tick(200); f.requests[0]!.pending.resolve('old root'); await flush()
assert.equal(f.state.float.value.content, '')
oldRoot.fire('click', kb('old'))
assert.equal(f.requests.length, 1)
f.state.rebind(); f.state.rebind(); f.fire('click', web())
assert.equal((f.root.value as unknown as Element).listenerCount, 3)
f.state.rebind()
assert.equal(f.state.float.value.visible, true, 'streaming rebind preserves the popup')
f.root.value = null; await vue.nextTick()
assert.equal(f.win.listenerCount, 0)
})
test(`${mode}: unmount clears timers and listeners and ignores late responses`, async () => {
const f = fixture(mode), root = f.root.value as unknown as Element
f.fire('click', kb()); f.fire('mouseover', web()); f.state.scheduleClose(); f.close()
assert.equal(f.timers.size, 0)
assert.equal(root.listenerCount, 0)
assert.equal(f.win.listenerCount, 0)
f.requests[0]!.pending.resolve('late'); await flush()
assert.equal(f.state.float.value.content, '')
assert.equal(f.state.float.value.visible, false)
f.state.rebind()
assert.equal(root.listenerCount, 0)
})
test(`${mode}: drawer resolves aliases and web highlights while preserving wiki policy`, t => {
const f = fixture(mode, { drawer: true, refs: [{ id: 'resolved-chunk', knowledge_title: 'Document' }] }); t.after(f.close)
const event = f.fire('click', kb('DOC-1'))
assert.equal(event.prevented && event.stopped, true)
assert.equal(f.drawerCalls[0].highlight.chunkId, 'resolved-chunk')
assert.equal(f.drawerCalls[0].references[0].id, 'resolved-chunk')
f.fire('click', web())
assert.equal(f.drawerCalls[1].highlight.url, 'https://example.com/source')
assert.equal(f.requests.length, 0)
const wiki = f.fire('click', new Element('citation-wiki'))
assert.equal(wiki.prevented, mode === 'embed')
assert.equal(wiki.stopped, mode === 'embed')
f.refs.value = []; f.fire('click', kb())
assert.equal(f.requests.length, 1, 'empty reference lists fall back to the popup')
})
test(`${mode}: hover ID resolution and empty/error cache policies remain compatible`, async t => {
const f = fixture(mode, { refs: [{ id: 'resolved-chunk', knowledge_title: 'Document' }] }); t.after(f.close)
f.fire('mouseover', kb('DOC-1')); f.tick(80)
assert.equal(f.requests[0]!.args.at(-1), mode === 'chat' ? 'resolved-chunk' : 'DOC-1')
f.requests[0]!.pending.resolve(' '); await flush()
assert.equal(f.state.float.value.error, mode === 'chat' ? 'agentStream.citation.notFound' : '')
f.fire('click', kb('DOC-1'))
assert.equal(f.requests.length, 1, 'empty results are cached')
f.refs.value = []; f.fire('click', kb('failed'))
f.requests[1]!.pending.reject(new Error('failure')); await flush()
assert.equal(f.state.float.value.error, mode === 'chat' ? 'agentStream.citation.loadFailed' : 'Failed to load')
f.fire('click', kb('failed'))
assert.equal(f.requests.length, 2, 'failures remain cached')
})
}
test('chat sessions isolate cached content and invalidate in-flight requests on scope change', async t => {
const f = fixture('chat'); t.after(f.close)
f.fire('click', kb()); f.requests[0]!.pending.resolve('session a'); await flush()
assert.deepEqual(f.requests[0]!.args, ['chunk'])
assert.equal(f.requests[0]!.route, 'chat')
f.session.value = 'session-b'
assert.equal(f.state.float.value.visible, false)
assert.equal(f.state.float.value.content, '')
f.fire('click', kb()); f.session.value = 'session-a'
f.requests[1]!.pending.resolve('stale session b'); await flush()
assert.equal(f.cache.getCitationChunkCache('session-b', 'chunk'), undefined)
f.fire('click', kb())
assert.equal(f.requests.length, 2)
assert.equal(f.state.float.value.content, 'session a')
f.session.value = ''; f.fire('click', kb()); f.requests[2]!.pending.resolve('default'); await flush()
assert.equal(f.cache.getCitationChunkCache('default', 'chunk').content, 'default')
})
test('embed scopes include channel and token for both entry points and preserve API routing', async t => {
for (const mode of ['chat', 'embed'] as const) {
const f = fixture(mode); t.after(f.close)
f.channel.value = 'channel-a'; f.token.value = 'token-a'
f.fire('click', kb()); f.requests[0]!.pending.resolve('a'); await flush()
assert.equal(f.requests[0]!.route, 'embed')
assert.deepEqual(f.requests[0]!.args, ['channel-a', 'token-a', 'chunk'])
f.token.value = 'token-b'; f.fire('click', kb())
f.channel.value = 'channel-b'; f.fire('click', kb())
f.requests[1]!.pending.resolve('old token'); await flush()
assert.equal(f.state.float.value.loading, true)
f.requests[2]!.pending.resolve('b'); await flush()
assert.equal(f.cache.getCitationChunkCache('embed:channel-b:token-b', 'chunk').content, 'b')
f.channel.value = 'channel-a'; f.token.value = 'token-a'; f.fire('click', kb())
assert.equal(f.requests.length, 3)
assert.equal(f.state.float.value.content, 'a')
f.token.value = ''; f.fire('click', kb())
assert.equal(f.requests[3]!.route, mode, 'standalone embed never falls back to the normal API')
if (mode === 'embed') assert.deepEqual(f.requests[3]!.args, ['channel-a', '', 'chunk'])
}
})
test('only chat observes viewport changes and keeps hovered popups open', t => {
for (const mode of ['chat', 'embed'] as const) {
const f = fixture(mode); t.after(f.close)
f.fire('click', web()); f.win.fire('scroll'); f.tick(120)
assert.equal(f.state.float.value.visible, mode === 'embed')
f.fire('click', web()); f.setHovered(true); f.state.scheduleClose(); f.tick(120)
assert.equal(f.state.float.value.visible, mode === 'chat')
f.setHovered(false); f.win.fire('resize'); f.tick(120)
assert.equal(f.state.float.value.visible, false)
}
})

View File

@ -0,0 +1,248 @@
import { onBeforeUnmount, onMounted, ref, watch, type Ref } from 'vue'
import { resolveCitationChunkId, type CitationKnowledgeRef } from '@/utils/citationMarkdown'
import {
getCitationChunkCache,
setCitationChunkCache,
} from '@/utils/citationChunkCache'
import { useChatReferencesDrawer } from '@/composables/useChatReferencesDrawer'
export type CitationFloatState = {
visible: boolean
type: 'kb' | 'web'
top: number
left: number
title: string
content: string
url: string
loading: boolean
error: string
}
type CitationPopoverOptions = {
mode: 'chat' | 'embed'
getKnowledgeReferences?: () => CitationKnowledgeRef[] | null | undefined
getCacheScope: () => string
fetchChunk: (chunkId: string) => Promise<{ data?: { content?: unknown } } | undefined>
notFoundError?: () => string
loadError: () => string
}
/** Shared interaction lifecycle; entry points retain their access and error policies. */
export function useCitationPopover(rootRef: Ref<HTMLElement | null>, options: CitationPopoverOptions) {
const referencesDrawer = useChatReferencesDrawer()
const isChat = options.mode === 'chat'
const popupSelector = `.${options.mode}-citation-float`
const float = ref<CitationFloatState>({
visible: false,
type: 'kb',
top: 0,
left: 0,
title: '',
content: '',
url: '',
loading: false,
error: '',
})
let hoverTimer: number | null = null
let closeTimer: number | null = null
let requestVersion = 0
let boundRoot: HTMLElement | null = null
let disposed = false
const cancelHover = () => {
if (hoverTimer !== null) window.clearTimeout(hoverTimer)
hoverTimer = null
}
const reset = () => {
requestVersion++
cancelHover()
cancelClose()
float.value.visible = false
float.value.loading = false
float.value.content = ''
float.value.error = ''
}
const resolveChunkId = (el: HTMLElement) => {
const raw = el.getAttribute('data-chunk-id') || ''
return resolveCitationChunkId(raw, {
doc: el.getAttribute('data-doc') || '',
kbId: el.getAttribute('data-kb-id') || '',
}, options.getKnowledgeReferences?.()) || raw
}
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) => {
requestVersion++
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 openKb = async (el: HTMLElement) => {
// Embedded hover historically loads the raw ID; drawer highlights resolve aliases.
const chunkId = isChat ? resolveChunkId(el) : el.getAttribute('data-chunk-id') || ''
const title = el.getAttribute('data-doc') || ''
if (!chunkId) return
const version = ++requestVersion
float.value.type = 'kb'
float.value.title = title
float.value.url = ''
float.value.visible = true
positionFor(el, 4)
const scope = options.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 = ''
let result: { content: string; error?: string }
try {
const res = await options.fetchChunk(chunkId)
const content = String(res?.data?.content || '').trim()
result = { content, ...(!content && options.notFoundError ? { error: options.notFoundError() } : {}) }
} catch {
result = { content: '', error: options.loadError() }
}
// Replaced hovers, roots and access scopes must not receive late responses.
if (disposed || version !== requestVersion || scope !== options.getCacheScope()) return
setCitationChunkCache(scope, chunkId, result)
float.value.content = result.content
float.value.error = result.error || ''
float.value.loading = false
}
const scheduleClose = () => {
cancelClose()
closeTimer = window.setTimeout(() => {
closeTimer = null
if (isChat && document.querySelector(`.citation-kb:hover, .citation-web:hover, ${popupSelector}:hover`)) return
float.value.visible = false
}, 120)
}
const cancelClose = () => {
if (closeTimer !== null) {
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()
cancelHover()
hoverTimer = window.setTimeout(() => {
hoverTimer = null
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, ${popupSelector}`)) return
cancelHover()
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 chunkId = resolveChunkId(kbEl)
if (openDrawerForCitation({ chunkId })) return
void openKb(kbEl)
return
}
if (!isChat && target.closest?.('.citation-wiki')) {
e.preventDefault()
e.stopPropagation()
}
}
const onViewportChange = () => {
if (float.value.visible) scheduleClose()
}
const unbind = () => {
boundRoot?.removeEventListener('mouseover', onMouseOver, true)
boundRoot?.removeEventListener('mouseout', onMouseOut, true)
boundRoot?.removeEventListener('click', onClick, true)
window.removeEventListener('scroll', onViewportChange, true)
window.removeEventListener('resize', onViewportChange, true)
boundRoot = null
}
const rebind = () => {
if (disposed || boundRoot === rootRef.value) return
unbind()
reset()
boundRoot = rootRef.value
if (!boundRoot) return
boundRoot.addEventListener('mouseover', onMouseOver, true)
boundRoot.addEventListener('mouseout', onMouseOut, true)
boundRoot.addEventListener('click', onClick, true)
if (isChat) {
window.addEventListener('scroll', onViewportChange, true)
window.addEventListener('resize', onViewportChange, true)
}
}
watch(rootRef, rebind, { flush: 'post' })
watch(options.getCacheScope, reset, { flush: 'sync' })
onMounted(rebind)
onBeforeUnmount(() => {
disposed = true
unbind()
reset()
})
return { float, rebind, cancelClose, scheduleClose }
}

View File

@ -1,211 +1,23 @@
import { onBeforeUnmount, ref, unref, watch, type MaybeRef, type Ref } from 'vue'
import { unref, type MaybeRef, type Ref } from 'vue'
import { getEmbedChunkById } from '@/api/embed'
import {
getCitationChunkCache,
setCitationChunkCache,
} from '@/utils/citationChunkCache'
import { resolveCitationChunkId, type CitationKnowledgeRef } from '@/utils/citationMarkdown'
import { useChatReferencesDrawer } from '@/composables/useChatReferencesDrawer'
import type { CitationKnowledgeRef } from '@/utils/citationMarkdown'
import { useCitationPopover } from './useCitationPopover'
type EmbedCitationPopoverOptions = {
getKnowledgeReferences?: () => CitationKnowledgeRef[] | null | undefined
}
type FloatState = {
visible: boolean
type: 'kb' | 'web'
top: number
left: number
title: string
content: string
url: string
loading: boolean
error: string
}
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',
top: 0,
left: 0,
title: '',
content: '',
url: '',
loading: false,
error: '',
return useCitationPopover(rootRef, {
mode: 'embed',
getKnowledgeReferences: options?.getKnowledgeReferences,
getCacheScope: () => `embed:${unref(channelId)}:${unref(token)}`,
fetchChunk: (chunkId) => getEmbedChunkById(unref(channelId), unref(token), chunkId),
loadError: () => 'Failed to load',
})
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
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 openKb = async (el: HTMLElement) => {
const chunkId = el.getAttribute('data-chunk-id') || ''
const title = el.getAttribute('data-doc') || ''
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 getEmbedChunkById(unref(channelId), unref(token), chunkId)
const content = String(res?.data?.content || '').trim()
setCitationChunkCache(scope, chunkId, { content })
float.value.content = content
} catch {
const msg = 'Failed to load'
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(() => {
float.value.visible = false
}, 120)
}
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
if (closeTimer) {
window.clearTimeout(closeTimer)
closeTimer = null
}
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, .embed-citation-float')) return
if (hoverTimer) {
window.clearTimeout(hoverTimer)
hoverTimer = null
}
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
}
const wikiEl = target.closest?.('.citation-wiki') as HTMLElement | null
if (wikiEl) {
e.preventDefault()
e.stopPropagation()
}
}
const bind = () => {
const root = rootRef.value
if (!root) return
root.addEventListener('mouseover', onMouseOver, true)
root.addEventListener('mouseout', onMouseOut, true)
root.addEventListener('click', onClick, true)
}
const unbind = () => {
const root = rootRef.value
if (!root) return
root.removeEventListener('mouseover', onMouseOver, true)
root.removeEventListener('mouseout', onMouseOut, true)
root.removeEventListener('click', onClick, true)
}
watch(rootRef, () => {
unbind()
bind()
}, { flush: 'post' })
onBeforeUnmount(() => {
unbind()
if (hoverTimer) window.clearTimeout(hoverTimer)
if (closeTimer) window.clearTimeout(closeTimer)
})
return { float, rebind: () => { unbind(); bind() } }
}

View File

@ -124,7 +124,12 @@ const parentMd = ref<HTMLElement | null>(null)
const embedChannelIdRef = computed(() => props.embedChannelId)
const embedTokenRef = computed(() => props.embedToken)
const { float: citationFloat, rebind: rebindCitations } = useEmbedCitationPopover(
const {
float: citationFloat,
rebind: rebindCitations,
cancelClose: cancelCitationClose,
scheduleClose: scheduleCitationClose,
} = useEmbedCitationPopover(
parentMd,
embedChannelIdRef,
embedTokenRef,
@ -133,20 +138,6 @@ const { float: citationFloat, rebind: rebindCitations } = useEmbedCitationPopove
},
)
let citationCloseTimer: number | null = null
const cancelCitationClose = () => {
if (citationCloseTimer) {
window.clearTimeout(citationCloseTimer)
citationCloseTimer = null
}
}
const scheduleCitationClose = () => {
cancelCitationClose()
citationCloseTimer = window.setTimeout(() => {
citationFloat.value.visible = false
}, 120)
}
// Smooth the streamed answer into a steady typewriter cadence (shared with the
// Agent path). History reloads arrive complete and snap to full.
const answerText = computed(() => String(props.content || props.session?.content || ''))