From 846967ee997e200d8650317148f73f1419470415 Mon Sep 17 00:00:00 2001 From: Dave Date: Sat, 27 Dec 2025 17:37:25 +0000 Subject: [PATCH] Fix race condition: ignore streaming events from old sessions - Added sessionIdRef to track current session - When clearing session, generate new session ID - Event listeners check if sessionId matches before updating state - Prevents old streaming responses from appearing in new sessions - All quality checks passing --- src/components/Chat.tsx | 17 ++++++++++++++--- 1 file changed, 14 insertions(+), 3 deletions(-) diff --git a/src/components/Chat.tsx b/src/components/Chat.tsx index d6e08b7..bdd436f 100644 --- a/src/components/Chat.tsx +++ b/src/components/Chat.tsx @@ -22,6 +22,7 @@ export function Chat({ projectPath, onCloseProject }: ChatProps) { const [streamingContent, setStreamingContent] = useState(""); const messagesEndRef = useRef(null); const inputRef = useRef(null); + const sessionIdRef = useRef(Date.now()); // Token estimation and context window tracking const estimateTokens = (text: string): number => { @@ -102,13 +103,21 @@ export function Chat({ projectPath, onCloseProject }: ChatProps) { }, [model]); useEffect(() => { + const currentSessionId = sessionIdRef.current; + const unlistenUpdatePromise = listen("chat:update", (event) => { - setMessages(event.payload); - setStreamingContent(""); // Clear streaming content when final update arrives + // Only update if this is still the current session + if (sessionIdRef.current === currentSessionId) { + setMessages(event.payload); + setStreamingContent(""); // Clear streaming content when final update arrives + } }); const unlistenTokenPromise = listen("chat:token", (event) => { - setStreamingContent((prev) => prev + event.payload); + // Only append tokens if this is still the current session + if (sessionIdRef.current === currentSessionId) { + setStreamingContent((prev) => prev + event.payload); + } }); return () => { @@ -174,6 +183,8 @@ export function Chat({ projectPath, onCloseProject }: ChatProps) { ); if (confirmed) { + // Generate new session ID to ignore old streaming events + sessionIdRef.current = Date.now(); setMessages([]); setStreamingContent(""); setLoading(false);