RAGFlow is an agent-native database: a Retrieval-Augmented Generation (RAG) engine that grew into context infrastructure.
Go agent-harnessagent-native-databaseagentic-aiagentic-retrievalagentic-searchaiai-agentscontext-enginecontext-engineeringcontext-managementharness-engineeringknowledge-compilationragretrieval-augmented-generationretrieval-harnesssearch-harness
fix(web): agent explore streaming answer leaking into the switched-to session (#18686)
euvrec7dec3b9123c
diff --git a/web/src/pages/agent/chat/use-send-agent-message.test.tsx b/web/src/pages/agent/chat/use-send-agent-message.test.tsxnew file mode 100644index 0000000000..f125d56042--- /dev/null+++ b/web/src/pages/agent/chat/use-send-agent-message.test.tsx@@ -0,0 +1,169 @@+import { act, renderHook } from '@testing-library/react';+import { MessageEventType } from '@/hooks/use-send-message';+import { MessageType } from '@/constants/chat';+import { useSendAgentMessage } from './use-send-agent-message';++let mockAnswerList: any[] = [];+let mockDone = true;+const mockSend = jest.fn();+const mockAddNewestOneAnswer = jest.fn();++jest.mock('@/hooks/use-send-message', () => ({+ // Mirrors the real MessageEventType enum; the real module cannot be+ // requireActual'd here because it pulls in eventsource-parser's+ // TransformStream, which jsdom does not provide.+ MessageEventType: {+ WorkflowStarted: 'workflow_started',+ NodeStarted: 'node_started',+ NodeFinished: 'node_finished',+ Message: 'message',+ MessageEnd: 'message_end',+ WorkflowFinished: 'workflow_finished',+ UserInputs: 'user_inputs',+ WaitingForUser: 'waiting_for_user',+ NodeLogs: 'node_logs',+ },+ useSendMessageBySSE: () => ({+ send: mockSend,+ answerList: mockAnswerList,+ done: mockDone,+ setDone: jest.fn(),+ resetAnswerList: jest.fn(),+ stopOutputMessage: jest.fn(),+ }),+}));++jest.mock('@/hooks/logic-hooks', () => ({+ // Fully mocked: the real module imports eventsource-parser, which needs+ // TransformStream (unavailable in jsdom).+ useHandleMessageInputChange: () => ({+ handleInputChange: jest.fn(),+ value: '',+ setValue: jest.fn(),+ }),+ useSelectDerivedMessages: () => ({+ derivedMessages: [],+ setDerivedMessages: jest.fn(),+ scrollRef: { current: null },+ messageContainerRef: { current: null },+ removeLatestMessage: jest.fn(),+ removeMessageById: jest.fn(),+ addNewestOneQuestion: jest.fn(),+ addNewestOneAnswer: mockAddNewestOneAnswer,+ removeAllMessages: jest.fn(),+ removeAllMessagesExceptFirst: jest.fn(),+ scrollToBottom: jest.fn(),+ addPrologue: jest.fn(),+ }),+}));++jest.mock('react-router', () => ({+ useParams: () => ({}),+ useSearchParams: () => [new URLSearchParams(), jest.fn()],+}));++jest.mock('../hooks/use-get-begin-query', () => ({+ useIsTaskMode: () => false,+ useSelectBeginNodeDataInputs: () => [],+}));++const messageFrame = (sessionId: string, content: string) => ({+ event: MessageEventType.Message,+ data: { content, session_id: sessionId },+ message_id: 'message-1',+ session_id: sessionId,+});++const renderSendAgentMessage = (activeSessionId: string | undefined) =>+ renderHook(+ (props: { activeSessionId: string | undefined }) =>+ useSendAgentMessage({ activeSessionId: props.activeSessionId }),+ { initialProps: { activeSessionId } },+ );++describe('useSendAgentMessage session-scoped stream gating', () => {+ beforeEach(() => {+ jest.clearAllMocks();+ mockAnswerList = [];+ mockDone = true;+ });++ it('does not apply frames whose session_id differs from activeSessionId', () => {+ const { rerender } = renderSendAgentMessage('session-b');+ mockAnswerList = [messageFrame('session-a', 'hello')];+ rerender({ activeSessionId: 'session-b' });+ expect(mockAddNewestOneAnswer).not.toHaveBeenCalled();+ });++ it('applies frames whose session_id matches activeSessionId', () => {+ const { rerender } = renderSendAgentMessage('session-a');+ mockAnswerList = [messageFrame('session-a', 'hello')];+ rerender({ activeSessionId: 'session-a' });+ expect(mockAddNewestOneAnswer).toHaveBeenCalledTimes(1);+ expect(mockAddNewestOneAnswer).toHaveBeenCalledWith(+ expect.objectContaining({ id: 'message-1', answer: 'hello' }),+ );+ });++ it('keeps applying frames that carry no session id', () => {+ const { rerender } = renderSendAgentMessage('');+ mockAnswerList = [+ {+ event: MessageEventType.Message,+ data: { content: 'legacy frame' },+ message_id: 'message-2',+ },+ ];+ rerender({ activeSessionId: '' });+ expect(mockAddNewestOneAnswer).toHaveBeenCalledTimes(1);+ expect(mockAddNewestOneAnswer).toHaveBeenCalledWith(+ expect.objectContaining({ id: 'message-2', answer: 'legacy frame' }),+ );+ });++ it('replays the streamed answer when switching back to the stream session', () => {+ const { rerender } = renderSendAgentMessage('session-b');+ mockAnswerList = [messageFrame('session-a', 'hello')];+ rerender({ activeSessionId: 'session-b' });+ expect(mockAddNewestOneAnswer).not.toHaveBeenCalled();++ // A -> B -> A: the accumulated answer is re-applied without a new frame.+ rerender({ activeSessionId: 'session-a' });+ expect(mockAddNewestOneAnswer).toHaveBeenCalledTimes(1);+ });++ it('re-applies the streamed answer after external hydration replaced the list', async () => {+ const { result, rerender } = renderSendAgentMessage('session-a');+ mockAnswerList = [messageFrame('session-a', 'hello')];+ rerender({ activeSessionId: 'session-a' });+ expect(mockAddNewestOneAnswer).toHaveBeenCalledTimes(1);++ // SessionChat hydrates persisted messages and asks for a re-apply.+ await act(async () => {+ result.current.reapplyStreamedAnswer();+ });+ expect(mockAddNewestOneAnswer).toHaveBeenCalledTimes(2);+ });++ it('still applies frames when no activeSessionId is provided', () => {+ const { rerender } = renderSendAgentMessage(undefined);+ mockAnswerList = [messageFrame('session-a', 'hello')];+ rerender({ activeSessionId: undefined });+ expect(mockAddNewestOneAnswer).toHaveBeenCalledTimes(1);+ });++ it('records the session a request is sent to before the first frame', async () => {+ mockSend.mockResolvedValue({+ response: { ok: true, status: 200 },+ data: { code: 0 },+ });+ const { result } = renderSendAgentMessage('session-new');+ await act(async () => {+ await result.current.sendMessage({+ message: { id: 'q1', content: 'hi', role: MessageType.User },+ exploreSessionId: 'session-new',+ });+ });+ expect(result.current.requestedSessionId).toBe('session-new');+ });+});diff --git a/web/src/pages/agent/chat/use-send-agent-message.ts b/web/src/pages/agent/chat/use-send-agent-message.tsindex cc7624017b..c93e31b5f1 100644--- a/web/src/pages/agent/chat/use-send-agent-message.ts+++ b/web/src/pages/agent/chat/use-send-agent-message.ts@@ -236,6 +236,7 @@ export const useSendAgentMessage = ({refetch,isTaskMode: isTask,releaseMode,+ activeSessionId,}: {url?: string;addEventList?: (data: IEventList, messageId: string) => void;@@ -244,6 +245,13 @@ export const useSendAgentMessage = ({refetch?: () => void;isTaskMode?: boolean;releaseMode?: string | null;+ /**+ * Session the page is currently displaying. When provided, streamed+ * frames that belong to another session are not written into the+ * displayed message list (the user may switch sessions in Explore+ * while an answer is still streaming).+ */+ activeSessionId?: string;}) => {const { id: agentId } = useParams();const { handleInputChange, value, setValue } = useHandleMessageInputChange();@@ -252,6 +260,25 @@ export const useSendAgentMessage = ({const { send, answerList, done, stopOutputMessage, resetAnswerList } =useSendMessageBySSE(url || api.agentChatCompletion);const firstAnswer = answerList[0];+ // Session that owns the in-flight stream; every SSE frame carries the+ // session_id it belongs to.+ const streamSessionId = firstAnswer?.session_id;+ // Session the pending request was sent to. It is known before the first+ // SSE frame arrives, so the stream can already be attributed to its+ // session during connection setup.+ const [requestedSessionId, setRequestedSessionId] = useState<+ string | null | undefined+ >();+ // Bumped when derivedMessages is replaced externally (Explore hydrates+ // persisted messages when a session is re-selected) while a stream+ // owned by the displayed session is in flight, so the streamed answer+ // is re-applied on top of the hydrated history — the effect below+ // otherwise only re-runs when a new frame arrives.+ const [streamReplayToken, setStreamReplayToken] = useState(0);+ const reapplyStreamedAnswer = useCallback(+ () => setStreamReplayToken((token) => token + 1),+ [],+ );const messageId = useMemo(() => {return firstAnswer?.message_id;}, [firstAnswer]);@@ -326,6 +353,10 @@ export const useSendAgentMessage = ({// The hook keeps its own session cache for streamed replies, but that cache// can lag behind when the user switches sessions in Explore.params.session_id = exploreSessionId || sessionId;+ // Remember the owner before the first frame arrives so+ // connection-setup loading states are attributed to the right+ // session.+ setRequestedSessionId((exploreSessionId || sessionId) ?? null);if (releaseMode) {params.release = releaseMode;}@@ -377,6 +408,7 @@ export const useSendAgentMessage = ({.join('<br/>'),role: MessageType.User,});+ setRequestedSessionId(sessionId ?? null);await send({...body,...(isShared ? {} : { agent_id: agentId }),@@ -461,6 +493,16 @@ export const useSendAgentMessage = ({}, [sendMessageInTaskMode]);useEffect(() => {+ // The stream belongs to the session it was started in. If the user has+ // switched to a different session while the answer is streaming, do not+ // write the incoming frames into the message list being displayed.+ if (+ activeSessionId !== undefined &&+ streamSessionId !== undefined &&+ streamSessionId !== activeSessionId+ ) {+ return;+ }const { content, id, attachment, audio_binary, downloads } =findMessageFromList(answerList);const inputAnswer = findInputFromList(answerList);@@ -493,7 +535,13 @@ export const useSendAgentMessage = ({});}}- }, [answerList, addNewestOneAnswer]);+ }, [+ activeSessionId,+ answerList,+ addNewestOneAnswer,+ streamSessionId,+ streamReplayToken,+ ]);useEffect(() => {if (isTaskMode) {@@ -546,5 +594,8 @@ export const useSendAgentMessage = ({removeFile,setDerivedMessages,addPrologue,+ streamSessionId,+ requestedSessionId,+ reapplyStreamedAnswer,};};diff --git a/web/src/pages/agent/explore/components/session-chat.tsx b/web/src/pages/agent/explore/components/session-chat.tsxindex f5a72b0dcc..250699075d 100644--- a/web/src/pages/agent/explore/components/session-chat.tsx+++ b/web/src/pages/agent/explore/components/session-chat.tsx@@ -50,12 +50,24 @@ export function SessionChat({ session }: SessionChatProps) {beginInputs,shouldShowParameterDialog,setDerivedMessages,+ streamSessionId,+ requestedSessionId,+ reapplyStreamedAnswer,} = useSendSessionMessage();const { buildInputList, handleOk, isWaiting } = useAwaitComponentData({derivedMessages,sendFormMessage,});+ // An in-flight stream only renders a loading state on the session it+ // belongs to, not on whichever session the user switched to. Before the+ // first SSE frame arrives the frame-carried session id is unknown, so+ // fall back to the session the request was sent to; only when neither+ // is known is the stream treated as belonging to the displayed session.+ const streamOwnerSessionId = streamSessionId ?? requestedSessionId;+ const isStreamingActiveSession =+ sendLoading &&+ (streamOwnerSessionId ? streamOwnerSessionId === sessionId : true);const hasActiveSession = Boolean(sessionId || isNew || hasLocalMessageRef.current,);@@ -94,6 +106,24 @@ export function SessionChat({ session }: SessionChatProps) {}}, [session?.id, session?.message, sessionId, setDerivedMessages]);+ // Hydrating persisted messages replaces the streamed view, and the+ // persisted list cannot contain the answer that is still being+ // generated. When a stream owned by this session is in flight, ask the+ // send-message hook to re-apply the streamed answer on top of the+ // hydrated history — its replay effect only re-runs when a new frame+ // arrives, which can take a long time or never happen (the stream may+ // have finished while another session was displayed).+ useEffect(() => {+ if (isStreamingActiveSession) {+ reapplyStreamedAnswer();+ }+ }, [+ session?.message,+ sessionId,+ isStreamingActiveSession,+ reapplyStreamedAnswer,+ ]);+useEffect(() => {if (!sessionId && !isNew && !hasLocalMessageRef.current && !sendLoading) {setDerivedMessages([]);@@ -141,7 +171,7 @@ export function SessionChat({ session }: SessionChatProps) {<MessageItemloading={message.role === MessageType.Assistant &&- sendLoading &&+ isStreamingActiveSession &&derivedMessages.length - 1 === i}key={buildMessageUuidWithRole(message)}@@ -159,7 +189,7 @@ export function SessionChat({ session }: SessionChatProps) {clickDocumentButton={clickDocumentButton}index={i}showLikeButton={false}- sendLoading={sendLoading}+ sendLoading={isStreamingActiveSession}showLog={false}>{hasUserFillUpInputs &&@@ -195,6 +225,10 @@ export function SessionChat({ session }: SessionChatProps) {</div>)}<section className="p-4">+ {/* The SSE stream and its message state are shared by every+ session of this canvas, so the input stays disabled while any+ session is streaming: a second concurrent stream would+ interleave its frames into the same answer list. */}<NextMessageInputvalue={value}sendLoading={sendLoading}diff --git a/web/src/pages/agent/explore/hooks/use-send-session-message.ts b/web/src/pages/agent/explore/hooks/use-send-session-message.tsindex 0aa7cfaa2d..e8f0d710e2 100644--- a/web/src/pages/agent/explore/hooks/use-send-session-message.ts+++ b/web/src/pages/agent/explore/hooks/use-send-session-message.ts@@ -63,6 +63,9 @@ export const useSendSessionMessage = () => {...chatLogic} = useSendAgentMessage({beginParams,+ // Gate streamed output so a stream started in another session never+ // renders into the session the user switched to.+ activeSessionId: sessionId ?? '',});const handleParametersOk = useCallback(