fix: ensure correct message ordering in agent stream

This commit fixes a bug where model text preceding a tool call would
be displayed after the tool call in the conversation history.

We now explicitly flush any pending agent text to the conversation
history (via 'addItem') immediately before a tool request is tracked.
This ensures the model's intent is rendered above the execution result.
This commit is contained in:
Michael Bleigh
2026-03-24 12:03:02 -07:00
parent 2a8918c72f
commit 87e9491e78
+14 -8
View File
@@ -131,6 +131,17 @@ export const useAgentStream = (
loopDetectionConfirmationRequest,
] = useState<LoopDetectionConfirmationRequest | null>(null);
const flushPendingText = useCallback(() => {
if (pendingHistoryItemRef.current) {
addItem(
pendingHistoryItemRef.current,
userMessageTimestampRef.current,
);
setPendingHistoryItem(null);
geminiMessageBufferRef.current = '';
}
}, [addItem, pendingHistoryItemRef, setPendingHistoryItem]);
const cancelOngoingRequest = useCallback(async () => {
if (sessionRef.current) {
await sessionRef.current.abort();
@@ -156,13 +167,7 @@ export const useAgentStream = (
break;
case 'agent_end':
setStreamingState(StreamingState.Idle);
if (pendingHistoryItemRef.current) {
addItem(
pendingHistoryItemRef.current,
userMessageTimestampRef.current,
);
setPendingHistoryItem(null);
}
flushPendingText();
break;
case 'message':
if (event.role === 'agent') {
@@ -202,6 +207,7 @@ export const useAgentStream = (
}
break;
case 'tool_request':
flushPendingText();
setTrackedTools((prev) => [
...prev,
{
@@ -270,7 +276,7 @@ export const useAgentStream = (
break;
}
},
[addItem, pendingHistoryItemRef, setPendingHistoryItem],
[addItem, flushPendingText, pendingHistoryItemRef, setPendingHistoryItem],
);
useEffect(() => {