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
This commit is contained in:
@@ -22,6 +22,7 @@ export function Chat({ projectPath, onCloseProject }: ChatProps) {
|
||||
const [streamingContent, setStreamingContent] = useState("");
|
||||
const messagesEndRef = useRef<HTMLDivElement>(null);
|
||||
const inputRef = useRef<HTMLInputElement>(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<Message[]>("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<string>("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);
|
||||
|
||||
Reference in New Issue
Block a user