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): retry history loading after transient failures (#4186)
hahahahahayesyeseyseca7ffd4bbb5
diff --git a/frontend/src/composables/useEmbedChatSession.test.ts b/frontend/src/composables/useEmbedChatSession.test.tsnew file mode 100644index 000000000..435efd3f0--- /dev/null+++ b/frontend/src/composables/useEmbedChatSession.test.ts@@ -0,0 +1,122 @@+import assert from 'node:assert/strict'+import { readFileSync } from 'node:fs'+import { createRequire } from 'node:module'+import test from 'node:test'+import vm from 'node:vm'+import ts from 'typescript'+import * as vue from 'vue'+import * as historyPagination from '../utils/historyPagination.ts'+import * as suspendedRun from '../utils/suspendedRun.ts'+import type { useEmbedChatSession as EmbedChatSession } from './useEmbedChatSession.ts'++const require = createRequire(import.meta.url)+const source = readFileSync(new URL('./useEmbedChatSession.ts', import.meta.url), 'utf8')+const compiled = ts.transpileModule(source, {+ compilerOptions: { module: ts.ModuleKind.CommonJS, target: ts.ScriptTarget.ES2022 },+}).outputText++const flush = async () => {+ await Promise.resolve()+ await Promise.resolve()+ await new Promise<void>((resolve) => setImmediate(resolve))+}++test('embedded history remains retryable after a transient page failure', async (t) => {+ const requests: string[] = []+ const page = (count: number, prefix: string) => Array.from({ length: count }, (_, index) => ({+ id: `${prefix}-${index}`,+ role: index % 2 === 0 ? 'user' : 'assistant',+ content: `${prefix} message ${index}`,+ created_at: `2026-10-12T04:${String(index).padStart(2, '0')}:00Z`,+ }))+ const responses = [+ () => Promise.resolve({ data: page(20, 'latest') }),+ () => Promise.reject(new Error('temporary network failure')),+ () => Promise.resolve({ data: page(19, 'older') }),+ ]++ const exports: { useEmbedChatSession?: typeof EmbedChatSession } = {}+ vm.runInNewContext(compiled, {+ exports,+ console,+ queueMicrotask,+ setTimeout: (callback: () => void) => {+ queueMicrotask(callback)+ return 1+ },+ clearTimeout: () => {},+ require: (id: string) => {+ if (id === 'vue') return { ...vue, onMounted: (callback: () => void) => callback(), onUnmounted: () => {} }+ if (id === 'vue-i18n') return { useI18n: () => ({ t: (key: string) => key }) }+ if (id === '@/utils/historyPagination') return historyPagination+ if (id === '@/utils/suspendedRun') return suspendedRun+ if (id === '@/utils/embedToast') return { embedToast: () => {} }+ if (id === '@/utils/embedContext') return { buildQueryWithHostContext: (value: string) => value }+ if (id === '@/utils/embedFile') return { fileToDataURI: async () => '' }+ if (id === '@/composables/useStickyBottomOnResize') return { useStickyBottomOnResize: () => {} }+ if (id === '@/api/chat/streame') {+ return {+ useStream: () => ({+ onChunk: () => {},+ error: vue.ref(''),+ startStream: async () => {},+ stopStream: () => {},+ }),+ }+ }+ if (id === '@/api/embed') {+ return {+ getEmbedMessageList: (_channel: string, _token: string, sessionId: string) => {+ requests.push(sessionId)+ return responses[requests.length - 1]()+ },+ postEmbedMessageSent: () => {},+ postEmbedMessageReceived: () => {},+ relayEmbedWebhookEvent: () => {},+ stopEmbedSession: async () => {},+ }+ }+ if (id === '@/composables/useChatStreamHandler') {+ return {+ useChatStreamHandler: () => ({+ shouldRenderAssistantMessage: () => true,+ shouldShowGlobalTypingIndicator: vue.computed(() => false),+ handleMsgList: async () => {},+ processStreamChunk: () => {},+ prepareForNewOutgoingMessage: () => {},+ markInFlightAssistantStopped: () => {},+ }),+ }+ }+ throw new Error(`Unexpected import: ${id}`)+ },+ })++ const effects = vue.effectScope()+ t.after(() => effects.stop())+ const session = effects.run(() => exports.useEmbedChatSession!({+ sessionId: vue.ref('session-1'),+ sessionSig: vue.ref('signature'),+ visitorId: vue.ref('visitor'),+ channelId: 'channel',+ token: 'token',+ agentId: 'agent',+ kbIds: [],+ }))!+ session.scrollContainer.value = {+ scrollTop: 0,+ scrollHeight: 400,+ clientHeight: 200,+ } as HTMLElement++ await flush()+ assert.equal(requests.length, 1, 'initial history page should load')++ session.handleScroll()+ await flush()+ assert.equal(requests.length, 2, 'first top-scroll should reach the failed request')++ session.handleScroll()+ await flush()+ assert.equal(requests.length, 3, 'next top-scroll should retry after connectivity recovers')+})diff --git a/frontend/src/composables/useEmbedChatSession.ts b/frontend/src/composables/useEmbedChatSession.tsindex 213ec93ca..b1802ac91 100644--- a/frontend/src/composables/useEmbedChatSession.ts+++ b/frontend/src/composables/useEmbedChatSession.ts@@ -19,6 +19,7 @@ import {import { embedToast } from '@/utils/embedToast'import { buildQueryWithHostContext } from '@/utils/embedContext'import { fileToDataURI } from '@/utils/embedFile'+import { historyHasMoreAfterAttempt } from '@/utils/historyPagination'import { useI18n } from 'vue-i18n'import { useChatStreamHandler, isPromptCard } from '@/composables/useChatStreamHandler'import { resumeSuspendedRunKey } from '@/utils/suspendedRun'@@ -207,21 +208,35 @@ export function useEmbedChatSession(options: {// load of a brand-new session: leaving hasMoreHistory true here would// let a later scroll-to-top re-fetch with an empty cursor (= "latest"),// pulling back the just-sent messages and duplicating them.- hasMoreHistory.value = false+ hasMoreHistory.value = historyHasMoreAfterAttempt(hasMoreHistory.value, {+ status: 'loaded',+ itemCount: 0,+ pageSize: limit.value,+ cursorAdvanced: false,+ })return}const nextCursor = String(batch[0].created_at)- if (isScrollType && created_at.value && nextCursor === created_at.value) {- hasMoreHistory.value = false+ const cursorAdvanced = !(isScrollType && created_at.value && nextCursor === created_at.value)+ hasMoreHistory.value = historyHasMoreAfterAttempt(hasMoreHistory.value, {+ status: 'loaded',+ itemCount: batch.length,+ pageSize: limit.value,+ cursorAdvanced,+ })+ if (!cursorAdvanced) {return}- if (batch.length < limit.value) hasMoreHistory.value = falsecreated_at.value = nextCursorawait handleMsgList(batch, isScrollType, scrollHeight)}).catch((err) => {console.error('Failed to load messages:', err)- if (isScrollType) hasMoreHistory.value = false+ if (isScrollType) {+ hasMoreHistory.value = historyHasMoreAfterAttempt(hasMoreHistory.value, {+ status: 'failed',+ })+ }}).finally(() => {historyLoading.value = falsediff --git a/frontend/src/utils/historyPagination.test.ts b/frontend/src/utils/historyPagination.test.tsnew file mode 100644index 000000000..b7ec3f6a1--- /dev/null+++ b/frontend/src/utils/historyPagination.test.ts@@ -0,0 +1,47 @@+import assert from 'node:assert/strict'+import test from 'node:test'+import { historyHasMoreAfterAttempt } from './historyPagination'++test('a failed page request preserves the existing retry state', () => {+ assert.equal(historyHasMoreAfterAttempt(true, { status: 'failed' }), true)+ assert.equal(historyHasMoreAfterAttempt(false, { status: 'failed' }), false)+})++test('successful pages exhaust history only at a real pagination boundary', () => {+ assert.equal(+ historyHasMoreAfterAttempt(true, {+ status: 'loaded',+ itemCount: 20,+ pageSize: 20,+ cursorAdvanced: true,+ }),+ true,+ )+ assert.equal(+ historyHasMoreAfterAttempt(true, {+ status: 'loaded',+ itemCount: 19,+ pageSize: 20,+ cursorAdvanced: true,+ }),+ false,+ )+ assert.equal(+ historyHasMoreAfterAttempt(true, {+ status: 'loaded',+ itemCount: 20,+ pageSize: 20,+ cursorAdvanced: false,+ }),+ false,+ )+ assert.equal(+ historyHasMoreAfterAttempt(false, {+ status: 'loaded',+ itemCount: 20,+ pageSize: 20,+ cursorAdvanced: true,+ }),+ false,+ )+})diff --git a/frontend/src/utils/historyPagination.ts b/frontend/src/utils/historyPagination.tsnew file mode 100644index 000000000..39756133e--- /dev/null+++ b/frontend/src/utils/historyPagination.ts@@ -0,0 +1,16 @@+export type HistoryPageAttempt =+ | { status: 'failed' }+ | {+ status: 'loaded'+ itemCount: number+ pageSize: number+ cursorAdvanced: boolean+ }++export function historyHasMoreAfterAttempt(+ previousHasMore: boolean,+ attempt: HistoryPageAttempt,+): boolean {+ if (attempt.status === 'failed') return previousHasMore+ return previousHasMore && attempt.cursorAdvanced && attempt.itemCount >= attempt.pageSize+}diff --git a/frontend/src/views/chat/index.vue b/frontend/src/views/chat/index.vueindex 73fa06a29..b0d73c910 100644--- a/frontend/src/views/chat/index.vue+++ b/frontend/src/views/chat/index.vue@@ -258,6 +258,7 @@ import FollowUpSuggestions from '@/components/chat/FollowUpSuggestions.vue';import MessageTimestamp from '@/components/chat/MessageTimestamp.vue';import ChatQuestionMinimap from '@/components/chat/ChatQuestionMinimap.vue';import { shouldShowConversationTimestamp } from '@/utils/messageTimestamp';+import { historyHasMoreAfterAttempt } from '@/utils/historyPagination';import ChatHeader from '@/components/ChatHeader.vue';import {notifySessionMutation,@@ -1175,7 +1176,12 @@ const getmsgList = (data, isScrollType = false, scrollHeight) => {const batch = res?.data;if (!batch?.length) {if (isScrollType) {- hasMoreHistory.value = false;+ hasMoreHistory.value = historyHasMoreAfterAttempt(hasMoreHistory.value, {+ status: 'loaded',+ itemCount: 0,+ pageSize: limit.value,+ cursorAdvanced: false,+ });}return;}@@ -1183,19 +1189,24 @@ const getmsgList = (data, isScrollType = false, scrollHeight) => {cancelSuggestedQuestionsFetch();}const nextCursor = batch[0].created_at;- if (isScrollType && created_at.value && nextCursor === created_at.value) {- hasMoreHistory.value = false;+ const cursorAdvanced = !(isScrollType && created_at.value && nextCursor === created_at.value);+ hasMoreHistory.value = historyHasMoreAfterAttempt(hasMoreHistory.value, {+ status: 'loaded',+ itemCount: batch.length,+ pageSize: limit.value,+ cursorAdvanced,+ });+ if (!cursorAdvanced) {return;}- if (batch.length < limit.value) {- hasMoreHistory.value = false;- }created_at.value = nextCursor;await handleMsgList(batch, isScrollType, scrollHeight);}).catch((err) => {console.error('Failed to load messages:', err);if (isScrollType) {- hasMoreHistory.value = false;+ hasMoreHistory.value = historyHasMoreAfterAttempt(hasMoreHistory.value, {+ status: 'failed',+ });}}).finally(() => {historyLoading.value = false;