From 87e9491e78ecdebeb5f20bd07257e56f1f422f8b Mon Sep 17 00:00:00 2001 From: Michael Bleigh Date: Tue, 24 Mar 2026 12:03:02 -0700 Subject: [PATCH] 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. --- packages/cli/src/ui/hooks/useAgentStream.ts | 22 +++++++++++++-------- 1 file changed, 14 insertions(+), 8 deletions(-) diff --git a/packages/cli/src/ui/hooks/useAgentStream.ts b/packages/cli/src/ui/hooks/useAgentStream.ts index 14e816021a..9400651653 100644 --- a/packages/cli/src/ui/hooks/useAgentStream.ts +++ b/packages/cli/src/ui/hooks/useAgentStream.ts @@ -131,6 +131,17 @@ export const useAgentStream = ( loopDetectionConfirmationRequest, ] = useState(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(() => {