From 95e8a9c0c03431ac876bad7870e472af2ebba46f Mon Sep 17 00:00:00 2001 From: "dayuan.jiang" Date: Fri, 5 Dec 2025 00:54:35 +0900 Subject: [PATCH] fix: update chartXMLRef directly before sendMessage to avoid race condition The React state update (setChartXML) is async, so chartXMLRef wasn't updated when edit_diagram tool callback checked it. Now we update the ref directly in onFormSubmit, handleRegenerate, and handleEditMessage before sending. --- components/chat-panel.tsx | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/components/chat-panel.tsx b/components/chat-panel.tsx index b10b9ee..0fcd694 100644 --- a/components/chat-panel.tsx +++ b/components/chat-panel.tsx @@ -176,6 +176,10 @@ Please retry with an adjusted search pattern or use display_diagram if retries a let chartXml = await onFetchChart(); chartXml = formatXML(chartXml); + // Update ref directly to avoid race condition with React's async state update + // This ensures edit_diagram has the correct XML before AI responds + chartXMLRef.current = chartXml; + const parts: any[] = [{ type: "text", text: input }]; if (files.length > 0) { @@ -256,6 +260,9 @@ Please retry with an adjusted search pattern or use display_diagram if retries a // Restore the diagram to the saved state onDisplayChart(savedXml); + // Update ref directly to ensure edit_diagram has the correct XML + chartXMLRef.current = savedXml; + // Clean up snapshots for messages after the user message (they will be removed) for (const key of xmlSnapshotsRef.current.keys()) { if (key > userMessageIndex) { @@ -299,6 +306,9 @@ Please retry with an adjusted search pattern or use display_diagram if retries a // Restore the diagram to the saved state onDisplayChart(savedXml); + // Update ref directly to ensure edit_diagram has the correct XML + chartXMLRef.current = savedXml; + // Clean up snapshots for messages after the user message (they will be removed) for (const key of xmlSnapshotsRef.current.keys()) { if (key > messageIndex) {