From a2da5f6d038ec84b5b936a61346545bd1dd87e69 Mon Sep 17 00:00:00 2001 From: Michael Zhou Date: Thu, 3 Dec 2026 10:38:05 +0800 Subject: [PATCH] Cancel the in-flight QA request and keep failed turns out of the history Two defects in the QA chat hook: - A second question overwrote the in-flight AbortController instead of cancelling it, so the old stream kept writing into the same state. - The error placeholder written into the message list was replayed to the model as assistant history on the next question. The new question now cancels the previous request, the superseded turn leaves the transcript instead of leaving a question without an answer, and conversationHistory holds only the turns the model actually answered. The request is also aborted on unmount, and the transcript is read from a mirror rather than a stale render closure. Co-Authored-By: Claude Code --- apps/web/src/__tests__/qa-chat-hook.test.tsx | 152 ++++++++++++++++ apps/web/src/hooks/use-qa-chat.ts | 181 +++++++++++++++---- 2 files changed, 298 insertions(+), 35 deletions(-) diff --git a/apps/web/src/__tests__/qa-chat-hook.test.tsx b/apps/web/src/__tests__/qa-chat-hook.test.tsx index 5929e6e2..2489e1ca 100644 --- a/apps/web/src/__tests__/qa-chat-hook.test.tsx +++ b/apps/web/src/__tests__/qa-chat-hook.test.tsx @@ -181,4 +181,156 @@ describe('useQAChat', () => { expect(result.current.messages).toHaveLength(2); expect(result.current.messages[1].content).toContain('something went wrong'); }); + + it('cancels the in-flight request when a new question is sent', async () => { + const signals: AbortSignal[] = []; + let call = 0; + + mockFetch.mockImplementation((_input: unknown, init?: RequestInit) => { + call += 1; + const signal = init?.signal as AbortSignal; + signals.push(signal); + + // The first question never gets an answer: it is still in flight when + // the second one is sent. + if (call === 1) { + return new Promise((_resolve, reject) => { + signal.addEventListener('abort', () => { + const error = new Error('The operation was aborted'); + error.name = 'AbortError'; + reject(error); + }); + }); + } + + return Promise.resolve( + createMockSSEResponse([ + 'data: {"type":"token","text":"Second answer"}', + 'data: {"type":"metadata","confidence":"HIGH","sources":[],"latencyMs":200}', + 'data: [DONE]', + ]), + ); + }); + + const { result } = renderHook(() => useQAChat()); + + await act(async () => { + void result.current.sendMessage('First question'); + }); + + await waitFor(() => { + expect(signals).toHaveLength(1); + }); + + await act(async () => { + void result.current.sendMessage('Second question'); + }); + + await waitFor(() => { + expect(signals).toHaveLength(2); + }); + + // The first request is cancelled, not merely overwritten. + expect(signals[0].aborted).toBe(true); + expect(signals[1].aborted).toBe(false); + + // The cancelled turn leaves the transcript: only the answered one is shown. + await waitFor(() => { + expect(result.current.messages).toHaveLength(2); + expect(result.current.messages[1].content).toBe('Second answer'); + }); + expect(result.current.messages[0].content).toBe('Second question'); + + // The cancelled question is not offered to the model as history. + const secondCallBody = JSON.parse(mockFetch.mock.calls[1][1].body); + expect(secondCallBody.conversationHistory).toEqual([]); + }); + + it('drops the superseded turn even when the cancelled request never settles', async () => { + const signals: AbortSignal[] = []; + + // A fetch that ignores the abort signal: the first request never + // settles, so nothing cleans up after it. + mockFetch.mockImplementationOnce((_input: unknown, init?: RequestInit) => { + signals.push(init?.signal as AbortSignal); + return new Promise(() => {}); + }); + mockFetch.mockImplementationOnce((_input: unknown, init?: RequestInit) => { + signals.push(init?.signal as AbortSignal); + return Promise.resolve( + createMockSSEResponse([ + 'data: {"type":"token","text":"Second answer"}', + 'data: {"type":"metadata","confidence":"HIGH","sources":[],"latencyMs":200}', + 'data: [DONE]', + ]), + ); + }); + + const { result } = renderHook(() => useQAChat()); + + await act(async () => { + void result.current.sendMessage('First question'); + }); + + await waitFor(() => { + expect(signals).toHaveLength(1); + }); + + await act(async () => { + void result.current.sendMessage('Second question'); + }); + + await waitFor(() => { + expect(result.current.messages).toHaveLength(2); + expect(result.current.messages[1].content).toBe('Second answer'); + }); + + // The cancelled question leaves the transcript: no question without an + // answer, and no bubble that streams forever. + expect(signals[0].aborted).toBe(true); + expect(result.current.messages[0].content).toBe('Second question'); + }); + + it('does not replay the error placeholder as conversation history', async () => { + mockFetch.mockResolvedValueOnce( + new Response(JSON.stringify({ error: 'Server error' }), { + status: 500, + }), + ); + mockFetch.mockResolvedValueOnce( + createMockSSEResponse([ + 'data: {"type":"token","text":"Second answer"}', + 'data: {"type":"metadata","confidence":"HIGH","sources":[],"latencyMs":200}', + 'data: [DONE]', + ]), + ); + + const { result } = renderHook(() => useQAChat()); + + await act(async () => { + await result.current.sendMessage('Bad request'); + }); + + await waitFor(() => { + expect(result.current.loading).toBe(false); + }); + + // The failure is visible in the transcript. + expect(result.current.messages).toHaveLength(2); + expect(result.current.messages[1].content).toContain('something went wrong'); + + await act(async () => { + await result.current.sendMessage('Second question'); + }); + + await waitFor(() => { + expect(result.current.messages).toHaveLength(4); + }); + + // The placeholder is not something the model said, so it is not history. + const secondCallBody = JSON.parse(mockFetch.mock.calls[1][1].body); + expect(secondCallBody.conversationHistory).toEqual([]); + // And it never reaches the model, whatever shape the history takes. + expect(mockFetch.mock.calls[1][1].body).not.toContain('something went wrong'); + }); }); diff --git a/apps/web/src/hooks/use-qa-chat.ts b/apps/web/src/hooks/use-qa-chat.ts index 324c6346..5bd0e8ef 100644 --- a/apps/web/src/hooks/use-qa-chat.ts +++ b/apps/web/src/hooks/use-qa-chat.ts @@ -1,6 +1,6 @@ 'use client'; -import { useState, useCallback, useRef } from 'react'; +import { useState, useCallback, useRef, useEffect } from 'react'; import type { ChatMessageData } from '@/components/qa/chat-message'; import type { ConfidenceLevel } from '@/components/qa/confidence-badge'; import type { SourceItem } from '@/components/qa/source-panel'; @@ -20,6 +20,12 @@ interface StreamMetadata { latencyMs?: number; } +/** A question asked, and the answer slot reserved for it. */ +interface QATurn { + userMessageId: string; + assistantMessageId: string; +} + let nextMessageId = 1; function generateMessageId(): string { @@ -33,10 +39,63 @@ export function useQAChat() { streaming: false, error: null, }); + /** + * The transcript, kept beside the state so a send reads the messages as they + * stand now rather than as the last render saw them. Two sends in the same + * tick would otherwise build the second history from a stale closure. + */ + const messagesRef = useRef([]); const abortControllerRef = useRef(null); + /** The turn in flight. A new question supersedes it. */ + const inFlightTurnRef = useRef(null); + /** Monotonic id of the request that owns the transcript. */ + const requestCounterRef = useRef(0); + /** False once the component unmounts, so no state is written after that. */ + const mountedRef = useRef(true); + /** + * Messages of turns the model never answered — a turn that failed. They + * stay in the transcript, where the user needs to see that no answer came, + * but they stay out of the conversation history: the error placeholder is + * not something the model said, and a question without an answer is not a + * completed exchange. + */ + const unansweredIdsRef = useRef>(new Set()); + + useEffect(() => { + mountedRef.current = true; + return () => { + mountedRef.current = false; + abortControllerRef.current?.abort(); + }; + }, []); + + /** Replace the transcript, keeping the mirror and the state in step. */ + const setMessages = useCallback((messages: ChatMessageData[]) => { + messagesRef.current = messages; + setState((prev) => ({ ...prev, messages })); + }, []); const sendMessage = useCallback( async (text: string) => { + const requestId = requestCounterRef.current + 1; + requestCounterRef.current = requestId; + const isCurrentRequest = () => requestCounterRef.current === requestId; + + // A new question supersedes the one in flight: cancel its request so + // the old stream stops writing, and drop its unanswered turn from + // the transcript rather than leave a question without an answer. + const superseded = inFlightTurnRef.current; + if (superseded) { + setMessages( + messagesRef.current.filter( + (m) => + m.id !== superseded.userMessageId && + m.id !== superseded.assistantMessageId, + ), + ); + abortControllerRef.current?.abort(); + } + const userMessage: ChatMessageData = { id: generateMessageId(), role: 'user', @@ -51,24 +110,29 @@ export function useQAChat() { streaming: true, }; + // Build conversation history from previous messages: the exchanges the + // model actually answered, and nothing else. + const conversationHistory = messagesRef.current + .filter((m) => !m.streaming && !unansweredIdsRef.current.has(m.id)) + .map((m) => ({ + role: m.role as 'user' | 'assistant', + content: [m.content, m.details].filter(Boolean).join('\n\n'), + })); + + setMessages([...messagesRef.current, userMessage, assistantMessage]); setState((prev) => ({ ...prev, - messages: [...prev.messages, userMessage, assistantMessage], loading: true, streaming: true, error: null, })); - // Build conversation history from previous messages (exclude the current exchange) - const conversationHistory = state.messages - .filter((m) => !m.streaming) - .map((m) => ({ - role: m.role as 'user' | 'assistant', - content: [m.content, m.details].filter(Boolean).join('\n\n'), - })); - const abortController = new AbortController(); abortControllerRef.current = abortController; + inFlightTurnRef.current = { + userMessageId: userMessage.id, + assistantMessageId, + }; try { const response = await apiFetch('/api/qa', { @@ -115,14 +179,18 @@ export function useQAChat() { const parsed = JSON.parse(data); if (parsed.type === 'token') { fullContent += parsed.text; - setState((prev) => ({ - ...prev, - messages: prev.messages.map((m) => - m.id === assistantMessageId - ? { ...m, content: fullContent } - : m, - ), - })); + if (!mountedRef.current) return; + // A newer request owns the transcript now, so this + // one writes nothing. + if (isCurrentRequest()) { + setMessages( + messagesRef.current.map((m) => + m.id === assistantMessageId + ? { ...m, content: fullContent } + : m, + ), + ); + } } else if (parsed.type === 'metadata') { metadata = { details: parsed.details, @@ -139,10 +207,22 @@ export function useQAChat() { } if (!completed) throw new Error('Response stream ended before completion'); + // A newer request took over while this one was streaming: it owns + // the transcript now, so this one writes nothing. + if (!isCurrentRequest()) { + setMessages( + messagesRef.current.filter( + (m) => m.id !== userMessage.id && m.id !== assistantMessageId, + ), + ); + unansweredIdsRef.current.delete(userMessage.id); + unansweredIdsRef.current.delete(assistantMessageId); + return; + } + // Finalize the message with metadata - setState((prev) => ({ - ...prev, - messages: prev.messages.map((m) => + setMessages( + messagesRef.current.map((m) => m.id === assistantMessageId ? { ...m, @@ -155,26 +235,47 @@ export function useQAChat() { } : m, ), - loading: false, - streaming: false, - })); + ); + setState((prev) => ({ ...prev, loading: false, streaming: false })); + inFlightTurnRef.current = null; } catch (error) { - if (error instanceof Error && error.name === 'AbortError') { - setState((prev) => ({ - ...prev, - messages: prev.messages.filter((m) => m.id !== assistantMessageId), - loading: false, - streaming: false, - })); + const isAbort = + error instanceof Error && + (error.name === 'AbortError' || error.name === 'CanceledError'); + + // The turn produced no answer, so it is not conversation. + unansweredIdsRef.current.add(userMessage.id); + unansweredIdsRef.current.add(assistantMessageId); + + if (!mountedRef.current) return; + + if (isAbort || !isCurrentRequest()) { + // Cancelled or superseded: the turn is dropped from the + // transcript rather than left without an answer. + setMessages( + messagesRef.current.filter( + (m) => m.id !== userMessage.id && m.id !== assistantMessageId, + ), + ); + unansweredIdsRef.current.delete(userMessage.id); + unansweredIdsRef.current.delete(assistantMessageId); + if (isCurrentRequest()) { + // The request was aborted without being superseded — the + // network dropped it. It still owns the transcript, so it + // stops loading. + setState((prev) => ({ ...prev, loading: false, streaming: false })); + inFlightTurnRef.current = null; + } return; } const errorMessage = error instanceof Error ? error.message : 'An unexpected error occurred'; - setState((prev) => ({ - ...prev, - messages: prev.messages.map((m) => + // A failed turn stays visible — the user needs to see that the + // answer never came — but it is not replayed as history. + setMessages( + messagesRef.current.map((m) => m.id === assistantMessageId ? { ...m, @@ -185,17 +286,27 @@ export function useQAChat() { } : m, ), + ); + setState((prev) => ({ + ...prev, loading: false, streaming: false, error: errorMessage, })); + inFlightTurnRef.current = null; } }, - [state.messages], + [setMessages], ); const clearConversation = useCallback(() => { abortControllerRef.current?.abort(); + abortControllerRef.current = null; + // Invalidate the request in flight: its late writes must not land. + requestCounterRef.current += 1; + inFlightTurnRef.current = null; + unansweredIdsRef.current.clear(); + messagesRef.current = []; setState({ messages: [], loading: false,