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.
This commit is contained in:
dayuan.jiang
2025-12-05 00:54:35 +09:00
parent d9568562f0
commit 95e8a9c0c0

View File

@@ -176,6 +176,10 @@ Please retry with an adjusted search pattern or use display_diagram if retries a
let chartXml = await onFetchChart(); let chartXml = await onFetchChart();
chartXml = formatXML(chartXml); 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 }]; const parts: any[] = [{ type: "text", text: input }];
if (files.length > 0) { 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 // Restore the diagram to the saved state
onDisplayChart(savedXml); 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) // Clean up snapshots for messages after the user message (they will be removed)
for (const key of xmlSnapshotsRef.current.keys()) { for (const key of xmlSnapshotsRef.current.keys()) {
if (key > userMessageIndex) { 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 // Restore the diagram to the saved state
onDisplayChart(savedXml); 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) // Clean up snapshots for messages after the user message (they will be removed)
for (const key of xmlSnapshotsRef.current.keys()) { for (const key of xmlSnapshotsRef.current.keys()) {
if (key > messageIndex) { if (key > messageIndex) {