fix(chat): use refs in stop handler to avoid stale closures

Reads sessionId and subagentSessionKey from refs instead of state so the stop button works even before React re-renders.
This commit is contained in:
kumarabhirup 2026-03-17 14:41:46 -07:00
parent 786a729c83
commit 92b32fdf21
No known key found for this signature in database
GPG Key ID: DB7CA2289CAB0167
2 changed files with 13 additions and 10 deletions

View File

@ -45,5 +45,6 @@ export async function POST(req: Request) {
if (aborted || abortedChildren > 0) {
trackServer("chat_stopped");
}
return Response.json({ aborted, abortedChildren });
}

View File

@ -1849,10 +1849,12 @@ export const ChatPanel = forwardRef<ChatPanelHandle, ChatPanelProps>(
reconnectAbortRef.current?.abort();
setIsReconnecting(false);
// Stop the server-side agent run and wait for confirmation so the
// session is no longer in "running" state before we stop the
// client-side stream (which may trigger queued message flush).
const stopKey = subagentSessionKey || currentSessionId;
// Read from refs to avoid stale closures — sessionIdRef is updated
// synchronously in handleEditorSubmit, so it's always current even
// if React hasn't re-rendered with the new state yet.
const sk = subagentSessionKeyRef.current;
const sid = sessionIdRef.current;
const stopKey = sk || sid;
if (stopKey) {
try {
await fetch("/api/chat/stop", {
@ -1861,17 +1863,17 @@ export const ChatPanel = forwardRef<ChatPanelHandle, ChatPanelProps>(
"Content-Type": "application/json",
},
body: JSON.stringify(
subagentSessionKey
? { sessionKey: subagentSessionKey }
: { sessionId: currentSessionId },
sk
? { sessionKey: sk }
: { sessionId: sid },
),
});
} catch { /* ignore */ }
}
// Stop the useChat transport stream (transitions status → "ready").
void stop();
}, [currentSessionId, subagentSessionKey, stop]);
// Stop the useChat transport stream (transitions status → "ready").
void stop();
}, [stop]);
// ── Queue handlers ──