From d9568562f0ab531ea542fddd96a0fdbf6e22973f Mon Sep 17 00:00:00 2001 From: "dayuan.jiang" Date: Fri, 5 Dec 2025 00:47:27 +0900 Subject: [PATCH] fix: use ref for chartXML to avoid stale closure in onToolCall The onToolCall callback was capturing stale chartXML value due to JavaScript closure. Using a ref ensures we always get the latest value. --- components/chat-panel.tsx | 14 +++++++++++--- 1 file changed, 11 insertions(+), 3 deletions(-) diff --git a/components/chat-panel.tsx b/components/chat-panel.tsx index b888bc4..b10b9ee 100644 --- a/components/chat-panel.tsx +++ b/components/chat-panel.tsx @@ -68,6 +68,12 @@ export default function ChatPanel({ // Store XML snapshots for each user message (keyed by message index) const xmlSnapshotsRef = useRef>(new Map()); + // Ref to track latest chartXML for use in callbacks (avoids stale closure) + const chartXMLRef = useRef(chartXML); + useEffect(() => { + chartXMLRef.current = chartXML; + }, [chartXML]); + const { messages, sendMessage, addToolResult, status, error, setMessages } = useChat({ transport: new DefaultChatTransport({ @@ -100,10 +106,12 @@ export default function ChatPanel({ let currentXml = ""; try { console.log("[edit_diagram] Starting..."); - // Use chartXML from context directly - more reliable than export + // Use chartXML from ref directly - more reliable than export // especially on Vercel where DrawIO iframe may have latency issues - if (chartXML) { - currentXml = chartXML; + // Using ref to avoid stale closure in callback + const cachedXML = chartXMLRef.current; + if (cachedXML) { + currentXml = cachedXML; console.log("[edit_diagram] Using cached chartXML, length:", currentXml.length); } else { // Fallback to export only if no cached XML