Open-source LLM knowledge platform: turn raw documents into a queryable RAG, an autonomous reasoning agent, and a self-maintaining Wiki.
Go agentagenticaichatbotdsh-pluginembeddingsevaluationgenerative-aigolangknowledge-basellmmulti-tenantollamaopenaiquestion-answeringragrerankingsemantic-searchvector-searchwiki
fix(chat): smooth streamed citation reveal cadence
wizardchena58fc13206c7
diff --git a/frontend/src/composables/useTypewriter.test.ts b/frontend/src/composables/useTypewriter.test.tsindex b8183119b..81d9b4e43 100644--- a/frontend/src/composables/useTypewriter.test.ts+++ b/frontend/src/composables/useTypewriter.test.ts@@ -4,6 +4,145 @@ import test from 'node:test'import { computed, createRenderer, nextTick, reactive } from 'vue'import { nextTypewriterReveal, useTypewriter } from './useTypewriter.ts'import { applyFinalArtifactContent } from '../utils/finalArtifactContent.ts'+import { KB_WEB_TAG_RE } from '../utils/citationMarkdown.ts'++async function withTypewriter(+ run: (harness: {+ answer: { content: string; done: boolean }+ displayed: ReturnType<typeof useTypewriter>['displayed']+ frame: () => string+ drain: () => string[]+ pending: () => number+ }) => Promise<void>,+ initial = { content: '', done: false },+) {+ const originalRequest = globalThis.requestAnimationFrame+ const originalCancel = globalThis.cancelAnimationFrame+ const frames = new Map<number, FrameRequestCallback>()+ let id = 0+ let time = 0+ globalThis.requestAnimationFrame = (callback) => { frames.set(++id, callback); return id }+ globalThis.cancelAnimationFrame = (frame) => { frames.delete(frame) }+ const answer = reactive(initial)+ let displayed!: ReturnType<typeof useTypewriter>['displayed']+ const renderer = createRenderer<any, any>({+ patchProp() {}, insert() {}, remove() {}, setText() {}, setElementText() {},+ createElement: () => ({}), createText: () => ({}), createComment: () => ({}),+ parentNode: () => null, nextSibling: () => null,+ })+ const app = renderer.createApp({+ setup() {+ displayed = useTypewriter(() => answer.content, () => answer.done).displayed+ return () => null+ },+ })+ const frame = () => {+ time += 16+ const pending = [...frames.values()]+ frames.clear()+ pending.forEach(callback => callback(time))+ return displayed.value+ }+ const drain = () => {+ const values: string[] = []+ for (let count = 0; frames.size && count < 1000; count += 1) values.push(frame())+ assert.equal(frames.size, 0, 'animation should eventually finish')+ return values+ }+ try {+ app.mount({})+ await run({ answer, displayed, frame, drain, pending: () => frames.size })+ } finally {+ app.unmount()+ globalThis.requestAnimationFrame = originalRequest+ globalThis.cancelAnimationFrame = originalCancel+ }+}++test('citations reveal atomically and their hidden attributes do not change the cadence', async () => {+ const kb = '<kb doc="游戏交互设计交底书范例.docx" chunk_id="3c67efd5-f2ff-4e26-9032-9e44e6861178" />'+ const web = `<web title="Reference" url="https://example.com/${'long-path/'.repeat(80)}" />`+ for (const tags of [kb, web, kb + web]) {+ const content = `这是正文🙂。${tags} 接下来继续输出文字。`+ const normalized = content.replace(KB_WEB_TAG_RE, '\uFFFC')+ let expected: string[] = []+ await withTypewriter(async ({ answer, drain }) => {+ answer.content = normalized+ await nextTick()+ expected = drain()+ })+ await withTypewriter(async ({ answer, displayed, drain }) => {+ answer.content = content+ await nextTick()+ const actual = drain().map(value => {+ const visible = value.replace(KB_WEB_TAG_RE, '\uFFFC')+ assert.ok(!visible.includes('<'), 'a partial citation must never be emitted')+ return visible+ })+ assert.deepEqual(actual, expected, 'each badge should cost only one visible unit')+ assert.equal(displayed.value, content, 'source attributes must be preserved exactly')+ })+ }+})++test('split citation tags wait for the closing bracket without spending reveal time on attributes', async () => {+ for (const tag of [+ '<kb doc="文档.docx" chunk_id="123" />',+ '<web url="https://example.com" title="Example">',+ ]) {+ await withTypewriter(async ({ answer, displayed, drain, frame, pending }) => {+ const prefix = '正文。'+ answer.content = prefix+ await nextTick()+ drain()+ for (let n = 1; n < tag.length; n += 1) {+ answer.content = prefix + tag.slice(0, n)+ await nextTick()+ frame()+ assert.equal(displayed.value, prefix)+ assert.equal(pending(), 0, 'hidden attributes should not run the animation loop')+ }+ answer.content = prefix + tag + '后续正文继续。'+ await nextTick()+ for (let n = 0; n < 3; n += 1) frame()+ assert.ok(displayed.value.includes(tag), 'a complete badge should appear within a normal reveal interval')+ drain()+ assert.equal(displayed.value, answer.content)+ })+ }+})++test('completion during a citation still catches up to the raw answer length', async () => {+ await withTypewriter(async ({ answer, displayed, drain }) => {+ answer.content = '回答正文。<kb doc="unfinished'+ answer.done = true+ await nextTick()+ assert.equal(displayed.value, '', 'completion must still drain ordinary text')+ drain()+ assert.equal(displayed.value, answer.content)+ })+})++test('completed history and reconciliation preserve raw citation markup immediately', async () => {+ const content = '历史回答。<kb doc="文档.docx" chunk_id="123" />'+ await withTypewriter(async ({ answer, displayed, pending }) => {+ assert.equal(displayed.value, content)+ assert.equal(pending(), 0)+ answer.content = content + '更新后的正文。'+ await nextTick()+ assert.equal(displayed.value, answer.content)+ assert.equal(pending(), 0)+ }, { content, done: true })+})++test('ordinary angle brackets and surrogate pairs survive citation pacing', async () => {+ await withTypewriter(async ({ answer, displayed, drain }) => {+ answer.content = 'Value < 5 🙂 <kbd>key</kbd> 结束。'+ await nextTick()+ for (const value of drain()) assert.doesNotMatch(value, /[\uD800-\uDBFF]$/u)+ assert.equal(displayed.value, answer.content)+ })+})test('reveals Chinese text in compact phrase groups', () => {const text = '这是一个自然流畅的回答。'diff --git a/frontend/src/composables/useTypewriter.ts b/frontend/src/composables/useTypewriter.tsindex 21e7f08e0..41705014a 100644--- a/frontend/src/composables/useTypewriter.ts+++ b/frontend/src/composables/useTypewriter.ts@@ -1,4 +1,5 @@import { computed, onBeforeUnmount, ref, watch, type ComputedRef } from 'vue';+import { KB_WEB_TAG_RE, stripIncompleteCitationTag } from '../utils/citationMarkdown';export interface TypewriterOptions {/** Comfortable reveal floor in characters per second. */@@ -11,7 +12,7 @@ export interface TypewriterOptions {maxFrameSeconds?: number;}-const NATURAL_BREAK_RE = /[\s,。!?;:、,.!?;:)\]】》」』]/u;+const NATURAL_BREAK_RE = /[\s,。!?;:、,.!?;:)\]】》」』\uFFFC]/u;const CJK_RE = /[\u3400-\u9fff\uf900-\ufaff\u3040-\u30ff\uac00-\ud7af]/u;const WORD_CHARACTER_RE = /[\p{L}\p{N}_]/u;@@ -91,6 +92,21 @@ export function useTypewriter(const maxCps = options.maxCps ?? 240;const maxFrameSeconds = options.maxFrameSeconds ?? 0.05;+ // Pace visible units, not the long IDs/URLs hidden inside citation badges.+ // Keep source offsets so the renderer still receives the original tags intact.+ const pacedTarget = computed(() => {+ const source = stripIncompleteCitationTag(getTarget());+ const citations: { index: number; hiddenLength: number }[] = [];+ let hiddenLength = 0;+ const text = source.replace(KB_WEB_TAG_RE, (tag: string, offset: number) => {+ const index = offset - hiddenLength;+ hiddenLength += tag.length - 1;+ citations.push({ index, hiddenLength });+ return '\uFFFC';+ });+ return { source, text, citations };+ });+const typedLength = ref(0);let revealCredit = 0;let raf: number | null = null;@@ -105,14 +121,22 @@ export function useTypewriter(}const displayed = computed(() => {- const full = getTarget();+ const { source, text: full, citations } = pacedTarget.value;let n = Math.min(typedLength.value, full.length);+ // Preserve the raw completed value, even if generation ended mid-tag. The+ // renderer hides that tail; callers use raw length to detect reveal completion.+ if (getComplete() && n === full.length) return getTarget();// Never cut on a high surrogate, which would render a broken glyph.if (n > 0 && n < full.length) {const code = full.charCodeAt(n - 1);if (code >= 0xd800 && code <= 0xdbff) n -= 1;}- return full.slice(0, n);+ let hiddenLength = 0;+ for (const citation of citations) {+ if (citation.index >= n) break;+ hiddenLength = citation.hiddenLength;+ }+ return source.slice(0, n + hiddenLength);});const stop = () => {@@ -124,7 +148,7 @@ export function useTypewriter(};const tick = (ts: number) => {- const full = getTarget();+ const full = pacedTarget.value.text;const target = full.length;if (typedLength.value > target) {typedLength.value = 0;@@ -160,7 +184,7 @@ export function useTypewriter(const handleMotionChange = (event: MediaQueryListEvent) => {reduceMotion = event.matches;if (reduceMotion) {- typedLength.value = getTarget().length;+ typedLength.value = pacedTarget.value.text.length;revealCredit = 0;stop();}@@ -170,7 +194,7 @@ export function useTypewriter(watch([getTarget, getComplete],([full, complete], [previous, wasComplete]) => {- const target = full.length;+ const target = pacedTarget.value.text.length;if (!initialized) {initialized = true;if (complete || reduceMotion) {