Skip to content

Fix: User input message sometimes appears twice in chat interface #170

Closed

Description

@larryro

Problem Statement

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:

  1. User sends message → optimistic message is displayed immediately
  2. Server saves message → message arrives via Convex subscription
  3. 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).

Affected Components

  • services/platform/app/(app)/dashboard/[id]/chat/components/chat-interface.tsx

Acceptance Criteria

  • User messages appear exactly once, never duplicated
  • Optimistic update still provides immediate feedback
  • No visual flicker or delay when sending messages
  • Works correctly with plain text messages
  • Works correctly with attachments (images, documents)

🤖 Generated with Claude Code

Activity

  1. larryro commented on Jan 11, 2026

    @larryro
    ContributorAuthor

    Implementation Plan

    Root Cause Analysis

    The message duplication occurs due to a timing window in React's render cycle:

    1. Server message arrives in uiMessages via Convex subscription
    2. threadMessages is recomputed via useMemo (depends on uiMessages)
    3. React re-renders - at this point, BOTH messages are visible:
      • Server message in mergedChatItems (from threadMessages)
      • Optimistic message via userDraftMessage (still set)
    4. useEffect runs to clear optimistic message (depends on threadMessages)
    5. 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 state
    const hasMatchingServerMessage = useMemo(() => {
      if (!optimisticMessage?.content || !optimisticMessageTimestampRef.current) {
        return false;
      }
      const searchStartTime = optimisticMessageTimestampRef.current - 500;
      return threadMessages?.some((m) => {
        if (m.role !== 'user') return false;
        const messageTime = m._creationTime || m.timestamp.getTime();
        if (messageTime < searchStartTime) return false;
        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

    Files to Modify

    File Changes
    services/platform/app/(app)/dashboard/[id]/chat/components/chat-interface.tsx Add hasMatchingServerMessage useMemo; update rendering condition

    Potential Risks

    1. Performance: Additional useMemo with some() iteration

      • Mitigation: threadMessages is already filtered and typically small; some() short-circuits on first match
    2. False positives: If user sends same message twice quickly, the second might not show optimistically

      • Mitigation: The 500ms time window and timestamp check minimize this; also rare edge case

    Testing Strategy

    1. Send regular text messages - verify no duplication
    2. Send multiple messages rapidly - verify no duplicates
    3. Create new thread with first message - verify no duplication
    4. Use browser DevTools to throttle network (Slow 3G) - verify no duplication even with latency

    🤖 Generated with Claude Code

  2. larryro commented on Jan 11, 2026

    @larryro
    ContributorAuthor
    Image
  3. larryro commented on Jan 12, 2026

    @larryro
    ContributorAuthor

    Additional Investigation Findings

    Reproduction Steps (100% reproducible)

    1. Start fresh dev server: npm run dev
    2. Navigate to chat page (new thread, no existing messages)
    3. Send "hello" as the first message
    4. 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.

    Affected Components

    • services/platform/app/(app)/dashboard/[id]/chat/components/chat-interface.tsx - Optimistic message cleanup logic

    Confirmation 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

  4. Israeltheminer commented on Jan 12, 2026

    @Israeltheminer
    Contributor

    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:

    1. User sends message → server saves it
    2. Router navigates to /chat/[threadId]
    3. Component remounts → useEffect sets fresh timestamp
    4. 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.tsx
    interface OptimisticMessage {
      content: string;
      threadId?: string;
      attachments?: FileAttachment[];
      timestamp: number;  // Added
    }
    
    // chat-interface.tsx - set timestamp when sending
    const optimisticTimestamp = Date.now();
    setOptimisticMessage({
      content: sanitizedContent,
      threadId,
      attachments,
      timestamp: optimisticTimestamp,
    });

    Now the timestamp persists across route changes and the matching works:

    const hasMatchingServerMessage = useMemo(() => {
      if (!optimisticMessage?.content) return false;
    
      return threadMessages?.some((m) => {
        if (m.role !== 'user') return false;
        
        // Only match messages created after user clicked send
        const messageTime = m._creationTime || m.timestamp.getTime();
        if (messageTime < optimisticMessage.timestamp) return false;
    
        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.

  5. added 2 commits that reference this issue on Jan 12, 2026
    66148ab
    f26dc63
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    priority: medium

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions