nanocoder icon indicating copy to clipboard operation
nanocoder copied to clipboard

[Bug] Duplicate React keys due to stale closure in addToChatQueue

Open JimStenstrom opened this issue 11 months ago • 0 comments

Description

React components added to the chat queue can receive duplicate keys, causing React warnings and potential rendering issues including memory exhaustion.

Error observed:

Encountered two children with the same key, `...`. Keys should be unique so that components maintain their identity across updates. Non-unique keys may cause children to be duplicated and/or omitted — the behavior is unsupported and could change in a future version.

This can lead to a JavaScript heap out of memory crash when React tries to reconcile components with duplicate keys.

Environment

  • OS: Any
  • Node version: Any
  • Nanocoder version: Latest
  • Provider: Any

Root Cause Analysis

The addToChatQueue callback in useAppState.tsx has a stale closure problem:

// source/hooks/useAppState.tsx:134-151
const addToChatQueue = useCallback(
    (component: React.ReactNode) => {
        const newCounter = componentKeyCounter + 1;  // ← Reads from stale closure!
        setComponentKeyCounter(newCounter);
        // ...
    },
    [componentKeyCounter],
);

Why this fails:

  1. componentKeyCounter is React state (async updates)
  2. When addToChatQueue is called rapidly (e.g., during tool execution), the closure captures a stale value
  3. React batches state updates, so multiple calls read the same counter value

Example scenario:

  1. Call 1: reads componentKeyCounter=5, sets to 6, creates key with value 6
  2. Call 2 (before re-render): reads componentKeyCounter=5 (stale!), sets to 6, creates key with value 6
  3. Both components now have the same key → DUPLICATE

Affected code paths:

Many callers also pass componentKeyCounter directly in their keys, compounding the issue:

  • useToolHandler.tsx: key={tool-cancelled-${componentKeyCounter}}
  • conversation-loop.tsx: key={assistant-${componentKeyCounter}}
  • useChatHandler.tsx: key={user-${componentKeyCounter}}
  • And many more...

Suggested Fix

Replace the state-based counter with a ref, which provides synchronous updates:

// Before (buggy)
const [componentKeyCounter, setComponentKeyCounter] = useState(0);

const addToChatQueue = useCallback(
    (component: React.ReactNode) => {
        const newCounter = componentKeyCounter + 1;
        setComponentKeyCounter(newCounter);
        // ...
    },
    [componentKeyCounter],
);

// After (fixed)
const componentKeyCounterRef = useRef(0);

const getNextComponentKey = useCallback(() => {
    componentKeyCounterRef.current += 1;
    return componentKeyCounterRef.current;
}, []);

const addToChatQueue = useCallback((component: React.ReactNode) => {
    const newCounter = componentKeyCounterRef.current + 1;
    componentKeyCounterRef.current = newCounter;
    
    let componentWithKey = component;
    if (React.isValidElement(component) && !component.key) {
        componentWithKey = React.cloneElement(component, {
            key: `chat-component-${newCounter}`,
        });
    }
    
    setChatComponents(prev => [...prev, componentWithKey]);
}, []); // No dependencies - ref is always current

For callers that need a key, expose getNextComponentKey() instead of the raw counter value.

Files to Modify

File Change
source/hooks/useAppState.tsx Replace componentKeyCounter state with ref, add getNextComponentKey()
source/hooks/useToolHandler.tsx Use getNextComponentKey() for keys
source/hooks/chat-handler/conversation/conversation-loop.tsx Use getNextComponentKey() for keys
source/hooks/chat-handler/useChatHandler.tsx Use getNextComponentKey() for keys
source/hooks/useAppHandlers.tsx Use getNextComponentKey() for keys
source/hooks/useModeHandlers.tsx Use getNextComponentKey() for keys
source/hooks/useAppInitialization.tsx Use getNextComponentKey() for keys
source/hooks/chat-handler/utils/context-checker.tsx Use getNextComponentKey() for keys

Additional Context

  • [x] I have searched existing issues to ensure this is not a duplicate
  • [x] I can reproduce this issue consistently (rapid tool execution triggers it)
  • [x] This issue occurs with the latest version of nanocoder

JimStenstrom avatar Dec 26 '25 03:12 JimStenstrom