You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
Fix: User input message sometimes appears twice in chat interface #170
Users sometimes see their input message displayed twice in the chat interface. This is a UI rendering race condition related to the optimistic update pattern and its synchronization with server-confirmed messages.
Reproduction: Intermittent but occurs with noticeable frequency when sending plain text messages.
Current State
The chat interface uses an optimistic update pattern:
User sends message → optimistic message is displayed immediately
Server saves message → message arrives via Convex subscription
Frontend clears optimistic message when server message is detected
The issue is that both the optimistic message and server message can render simultaneously during a brief timing window.
Proposed Solution
Add a synchronous check during render to prevent displaying the optimistic message if a matching server message already exists. This eliminates the race condition by checking during render rather than relying on useEffect (which runs after render).
The message duplication occurs due to a timing window in React's render cycle:
Server message arrives in uiMessages via Convex subscription
threadMessages is recomputed via useMemo (depends on uiMessages)
React re-renders - at this point, BOTH messages are visible:
Server message in mergedChatItems (from threadMessages)
Optimistic message via userDraftMessage (still set)
useEffect runs to clear optimistic message (depends on threadMessages)
Another re-render - now only server message is visible
The key issue is that React renders before the clearing useEffect runs. This is expected React behavior - effects run after render.
Step 1: Add hasMatchingServerMessage computed value
In chat-interface.tsx, add a useMemo after threadMessages (around line 358):
// Check if a server message matching the optimistic message already exists// This prevents showing duplicates during the brief window between// server message arrival and useEffect clearing the optimistic stateconsthasMatchingServerMessage=useMemo(()=>{if(!optimisticMessage?.content||!optimisticMessageTimestampRef.current){returnfalse;}constsearchStartTime=optimisticMessageTimestampRef.current-500;returnthreadMessages?.some((m)=>{if(m.role!=='user')returnfalse;constmessageTime=m._creationTime||m.timestamp.getTime();if(messageTime<searchStartTime)returnfalse;return(m.content===optimisticMessage.content||m.content.startsWith(optimisticMessage.content));});},[threadMessages,optimisticMessage?.content]);
Step 2: Update rendering condition
Change the optimistic message rendering (around line 808) from:
{userDraftMessage&&(
To:
{userDraftMessage&&!hasMatchingServerMessage&&(
Step 3: Keep existing useEffect as fallback
The existing useEffect (lines 499-532) should remain unchanged. It will still clear optimisticMessage state, which is needed for:
Cleaning up the state properly
Edge cases where the matching logic might differ slightly
Navigate to chat page (new thread, no existing messages)
Send "hello" as the first message
Result: The message appears twice in the UI
After refreshing the page or opening a new thread, the issue doesn't occur again in that session.
Root Cause: UI Rendering Race Condition
The issue occurs when React Strict Mode (or HMR during initial dev startup) causes the component to double-mount. This triggers a timing issue where both the optimistic message and server-confirmed message are rendered simultaneously.
Key observation: The database records show messages are NOT duplicated - each "hello" is followed by an assistant response. The backend deduplication logic is working correctly. This is purely a UI rendering issue.
Why It Happens on First Startup
During the first npm run dev, React Strict Mode double-mounts components to detect side effects. This can cause timing issues with the optimistic update cleanup logic in useEffect, which runs after render rather than during render.
Why It Works After Refresh
After refresh, the initial HMR/Strict Mode double-mounting phase has passed, and the timing between optimistic message display and server message arrival is more predictable.
The original proposed solution is correct: Add a synchronous check during render to prevent displaying the optimistic message if a matching server message already exists. This eliminates the race condition by checking during render rather than relying on useEffect.
Server message arrives with earlier timestamp (from step 1)
The server message predates the newly-set timestamp, so the check failed.
Fix
Store timestamp with the optimistic message in the layout context, set synchronously when user clicks send:
// layout.tsxinterfaceOptimisticMessage{content: string;threadId?: string;attachments?: FileAttachment[];timestamp: number;// Added}// chat-interface.tsx - set timestamp when sendingconstoptimisticTimestamp=Date.now();setOptimisticMessage({content: sanitizedContent,
threadId,
attachments,timestamp: optimisticTimestamp,});
Now the timestamp persists across route changes and the matching works:
consthasMatchingServerMessage=useMemo(()=>{if(!optimisticMessage?.content)returnfalse;returnthreadMessages?.some((m)=>{if(m.role!=='user')returnfalse;// Only match messages created after user clicked sendconstmessageTime=m._creationTime||m.timestamp.getTime();if(messageTime<optimisticMessage.timestamp)returnfalse;return(m.content===optimisticMessage.content||m.content.startsWith(optimisticMessage.content));});},[threadMessages,optimisticMessage?.content,optimisticMessage?.timestamp]);
Also added user message deduplication by id since useUIMessages can return multiple entries with different keys for the same message.
Activity
larryro commentedon Jan 11, 2026
Implementation Plan
Root Cause Analysis
The message duplication occurs due to a timing window in React's render cycle:
uiMessagesvia Convex subscriptionthreadMessagesis recomputed viauseMemo(depends onuiMessages)mergedChatItems(fromthreadMessages)userDraftMessage(still set)useEffectruns to clear optimistic message (depends onthreadMessages)The key issue is that React renders before the clearing
useEffectruns. This is expected React behavior - effects run after render.Step 1: Add
hasMatchingServerMessagecomputed valueIn
chat-interface.tsx, add auseMemoafterthreadMessages(around line 358):Step 2: Update rendering condition
Change the optimistic message rendering (around line 808) from:
To:
Step 3: Keep existing
useEffectas fallbackThe existing
useEffect(lines 499-532) should remain unchanged. It will still clearoptimisticMessagestate, which is needed for:Files to Modify
services/platform/app/(app)/dashboard/[id]/chat/components/chat-interface.tsxhasMatchingServerMessageuseMemo; update rendering conditionPotential Risks
Performance: Additional
useMemowithsome()iterationthreadMessagesis already filtered and typically small;some()short-circuits on first matchFalse positives: If user sends same message twice quickly, the second might not show optimistically
Testing Strategy
🤖 Generated with Claude Code
larryro commentedon Jan 11, 2026
larryro commentedon Jan 12, 2026
Additional Investigation Findings
Reproduction Steps (100% reproducible)
npm run devAfter refreshing the page or opening a new thread, the issue doesn't occur again in that session.
Root Cause: UI Rendering Race Condition
The issue occurs when React Strict Mode (or HMR during initial dev startup) causes the component to double-mount. This triggers a timing issue where both the optimistic message and server-confirmed message are rendered simultaneously.
Key observation: The database records show messages are NOT duplicated - each "hello" is followed by an assistant response. The backend deduplication logic is working correctly. This is purely a UI rendering issue.
Why It Happens on First Startup
During the first
npm run dev, React Strict Mode double-mounts components to detect side effects. This can cause timing issues with the optimistic update cleanup logic inuseEffect, which runs after render rather than during render.Why It Works After Refresh
After refresh, the initial HMR/Strict Mode double-mounting phase has passed, and the timing between optimistic message display and server message arrival is more predictable.
Affected Components
services/platform/app/(app)/dashboard/[id]/chat/components/chat-interface.tsx- Optimistic message cleanup logicConfirmation of Proposed Fix
The original proposed solution is correct: Add a synchronous check during render to prevent displaying the optimistic message if a matching server message already exists. This eliminates the race condition by checking during render rather than relying on
useEffect.🔍 Investigated with Claude Code
Israeltheminer commentedon Jan 12, 2026
Root Cause & Fix
The proposed solution was correct: add a synchronous check during render.
Why Timestamp Matching Failed
The original timestamp was set via
useEffect, which runs after render. On new thread creation:/chat/[threadId]useEffectsets fresh timestampThe server message predates the newly-set timestamp, so the check failed.
Fix
Store timestamp with the optimistic message in the layout context, set synchronously when user clicks send:
Now the timestamp persists across route changes and the matching works:
Also added user message deduplication by
idsinceuseUIMessagescan return multiple entries with different keys for the same message.fix(chat): prevent duplicate message rendering during optimistic update
fix(chat): store optimistic message timestamp in context to fix dupli…