Repository navigation
Description
What happened?
Despite the resolution merged in PR #29611 (which fixed LocalAgentExecutor dropping sibling inlineData parts in responseParts), reading image files (e.g. .png, .jpg) using the built-in ReadFile tool in Gemini CLI v0.66.0 continues to encounter an unhandled turn-state desynchronization, triggering:
✓ ReadFile Screenshot (209).png → Read image file: Screenshot (209).png
[System: You successfully executed a tool but returned an empty response. Please analyze the tool output and explain your progress or final answer.]
✕ [API Error: [{
"error": {
"code": 400,
"message": "Requests ending with a model turn are not supported.",
"errors": [
{
"message": "Requests ending with a model turn are not supported.",
"domain": "global",
"reason": "badRequest"
}
],
"status": "INVALID_ARGUMENT"
}
}
]]
ℹ This request failed. Press F12 for diagnostics, or run /settings and change "Error Verbosity" to full for full details.
The session then locks into a broken state where subsequent tool calls fail with the identical HTTP 400 error.
Steps to Reproduce
- Start Gemini CLI (
v0.66.0) withgemini-3.8-flashin any repository containing image assets (e.g.,.pngUI screenshots). - Ask the model to inspect or review an image using the
ReadFile(read_file) tool. - Observe that
ReadFile <path>.pngsuccessfully executes and returns the binary image payload. - On the immediate next turn, the CLI emits:
[System: You successfully executed a tool but returned an empty response. Please analyze the tool output and explain your progress or final answer.] - When the agent attempts to follow up or invoke another tool, the outgoing API request fails with:
400 INVALID_ARGUMENT: Requests ending with a model turn are not supported. - Subsequent retries in the same session fail repeatedly with the identical 400 error.
Root Cause Analysis
While PR #29611 ensured that LocalAgentExecutor preserves responseParts with inlineData, the underlying state-machine flaw exists in the main execution streaming loop (_runLoop in packages/core/src/agent-executor.ts / bundle chunk-HJ5KJXNZ.js):
-
hasVisibleTextEvaluates Only Content Tokens:if (event.type === "content") { if (typeof event.value === "string" && event.value.trim() !== "") { hasVisibleText = true; } }
When
ReadFiledelivers high-resolution image data, models with thinking enabled (gemini-3.8-flash) emit thoughts underevent.type === "thought". If no non-empty text string is emitted underevent.type === "content"before a tool call or turn break,hasVisibleTextremainsfalse. -
False Empty-Response Nudge Trigger:
if (toolCallRequests.length === 0) { if (isAfterToolResponse && !hasVisibleText) { const nudgeMessage = "[System: You successfully executed a tool but returned an empty response. Please analyze the tool output and explain your progress or final answer.]"; currentParts = [{ text: nudgeMessage }]; isAfterToolResponse = false; continue; }
The condition
isAfterToolResponse && !hasVisibleTextfalsely evaluates totrueeven though validinlineDatawas returned and the model generated valid thoughts. -
Violation of the Terminal Turn Invariant:
The Google Gemini API strictly requires that the incomingcontentsarray must never end on arole: "model"turn. It must always terminate on auserturn (containing user prompt, system instructions, orfunctionResponseparts).
When the synthetic nudge is queued viacontinue, the precedingrole: "model"candidate is already appended to the chat history, but the pending user turn buffer is not properly reconciled before the next stream dispatch or retry. As a result, the serialized payload sent togenerateContentStreamterminates withrole: "model", causing the Gemini backend to reject the request with400 Bad Request: Requests ending with a model turn are not supported.
What did you expect to happen?
- Image Read Ingestion:
ReadFileon binary image files should ingestinlineDataseamlessly without being falsely flagged as an empty response. - Thought Stream Awareness: In
_runLoop, generation of thought tokens (event.type === "thought") or active candidate output should count as valid activity so the false nudge is not triggered. - Payload Invariant Guard: The request builder / chat recording service must assert
contents[contents.length - 1].role !== 'model'prior to dispatching any request to the Gemini API. If the last message is amodelturn, the pending user turn or tool response must be reconciled to guarantee payload validity and prevent unhandled HTTP 400 session deadlocks.
Client information
- OS: Windows 11 (MINGW64 / Git Bash) & Ubuntu 24.04 LTS, win32
- Gemini CLI Version:
v0.66.0 - Model:
gemini-3.8-flash - Tool: Built-in
ReadFile(read_file) - Auth: Google OAuth (
oauth-personal/ Workspace)
Activity
gemini-cli commentedon Nov 1, 2026
Effort Analysis:
The root cause lies in how
packages/core/src/agents/local-executor.tsandpackages/core/src/agent/legacy-agent-session.tshandle tool responses with multimodal parts likeinlineData. While PR #29611 attempted to fix dropped sibling parts,LocalAgentExecutorstill processessyncResults.set(call.request.callId, call.response.responseParts[0])(line 1368), which can discardinlineDataifisMultimodalFRSupportedevaluates differently or nesting fails ingenerateContentResponseUtilities.ts. Consequently, the model receives afunctionResponsewithout the image, leading it to return an empty response. This triggers the automatic nudge ([System: You successfully executed a tool but returned an empty response...]) frompackages/cli/src/ui/hooks/useGeminiStream.tsorlegacy-agent-session.ts. This nudge injection desynchronizes the chat history state managed inpackages/core/src/core/geminiChat.tsandhistoryHardening.ts(specifically duringcoalesceandensureTerminalUserTurn), causing the Gemini API to reject subsequent turns with400 INVALID_ARGUMENT: Requests ending with a model turn are not supported. Fixing this requires untangling the state synchronization between the tool response builder, the agent loop, and the API history manager across multiple core architectural files, mapping directly toeffort/medium(Asynchronous Flow & Integration, State Management).anujmishra03 commentedon Nov 2, 2026
hey @ShreyasKashyap357 ,
Thanks for the issue details. I've traced the normal interactive
read_fileexecution path and identified two areas that appear relevant to the reported failure.1. Dotted Gemini 3 model identifiers
In
packages/core/src/config/models.ts,supportsMultimodalFunctionResponse()currently checks:This returns
falsefor dotted model identifiers such asgemini-3.8-flash.As a result,
convertToFunctionResponse()uses the sibling-parts fallback rather than nesting image data insidefunctionResponse.parts.2. Terminal user-turn normalization
In
packages/core/src/core/geminiChat.ts,ensureTerminalUserTurn()runs beforestripToolCallIdPrefixes().The latter can remove empty parts and empty content turns. This means a trailing user turn that passes the initial normalization could subsequently be removed, potentially leaving a model turn at the end of the outbound request and triggering the reported 400 error.
Execution-path clarification
I also verified that the normal interactive CLI path forwards tool response parts through
useGeminiStream.tsusingflatMap().LocalAgentExecutoris used for subagent workflows and does not appear to be responsible for this particular reproduction.The empty-response nudge appears to amplify the failure after the image payload is not handled correctly, rather than being the primary cause.
Proposed direction:
inlineData.generateContentStream()ends with a user turn.I'd be happy to work on this issue. Could a maintainer confirm whether this is the intended fix direction and enable assignment if the issue is available for community contribution?