Skip to content

fix(core): ensure request contents do not end with a model turn - #29527

Open
asieveking wants to merge 2 commits into
google-gemini:mainfrom
asieveking:fix/history-terminal-model-turn-and-rewind
Open

asieveking wants to merge 2 commits into
google-gemini:mainfrom
asieveking:fix/history-terminal-model-turn-and-rewind

Conversation

@asieveking

@asieveking asieveking commented Sep 27, 2026 •

Copy link
Copy Markdown

Summary

Fixes a 400 Bad Request error (Requests ending with a model turn are not supported) when sending requests where history ends with a model turn (e.g., following a /rewind operation, stream interruption, or when trailing user turns are empty/stripped).

Related Issues

Fixes #29530

Scope & Non-Goals

In-Scope (What this PR solves)

  • Terminal Role Invariant: Guarantees that request contents sent to generateContentStream never terminate on a model turn by injecting a continuation user turn (Please continue.).
  • Non-Mutating Pipeline: Ensures caller immutability by cloning the content array via structuredClone before appending, eliminating unexpected side-effects on shared/read-only arrays.
  • Resilience Across Edge Workflows: Protects sessions against 400 Bad Request failures following /rewind, mid-stream aborts/cancellations, or cases where user prompts are stripped by upstream filters.

Non-Goals (Out of Scope)

  • Tool Call / Response Imbalances: Does not handle mismatched counts between functionCall and functionResponse (which is governed by separate mechanisms in historyHardening.ts).
  • Thought Signatures: Does not modify thoughtSignature generation, preservation, or validation for reasoning models (Gemini 2.0 / 3.0).
  • Tool Schema Validation: Does not inspect or validate MCP/tool JSON schemas.
  • Persistent History Alteration: Does not mutate durable chat history on disk; this is strictly a network-boundary normalization prior to API dispatch.

Details

The Gemini API strictly requires that multi-turn request contents alternate between user and model roles, with the terminal turn always belonging to user. In GeminiChat.makeApiCallAndProcessStream, contentsToUse could terminate with a model turn under several real-world conditions (such as rewinding the chat state or aborting an in-flight tool call).

This patch enforces the invariant directly before dispatching to generateContentStream: if the payload ends with a model turn, a continuation user turn (Please continue.) is appended, guaranteeing API compliance without disrupting conversation semantics or mutating input references.

How to Validate

  1. Run unit test suite:
    npm test -w @google/gemini-cli-core -- packages/core/src/core/geminiChat.test.ts --run
  2. Verify all 113 tests pass, specifically:
    GeminiChat > sendMessageStream > should append a continuation user turn if contents ends with a model turn before calling generateContentStream

Pre-Merge Checklist

  • Updated relevant documentation and README (if needed)
  • Added/updated tests (if needed)
  • Noted breaking changes (if any)
  • Validated on required platforms/methods:
    • MacOS
      • npm run
      • npx
      • Docker
      • Podman
      • Seatbelt
    • Windows
      • npm run
      • npx
      • Docker
    • Linux
      • npm run
      • npx
      • Docker

@asieveking
asieveking requested a review from a team as a code owner September 27, 2026 23:07
@gemini-code-assist

Copy link
Copy Markdown
Contributor

Summary of Changes

Hello, I'm Gemini Code Assist1! I'm currently reviewing this pull request and will post my feedback shortly. In the meantime, here's a summary to help you and other reviewers quickly get up to speed!

This pull request addresses a recurring 400 Bad Request error occurring when the Gemini API receives a request ending in a model turn. By enforcing an invariant that requires the terminal turn to be a user role, the system now automatically injects a continuation prompt when necessary. This ensures stability for operations like chat rewinds or interrupted streams without requiring manual user intervention.

Highlights

  • API Compliance: Implemented a check to ensure chat history does not end with a model turn, preventing 400 Bad Request errors from the Gemini API.
  • Continuation Logic: Automatically appends a 'Please continue.' user turn when the payload ends with a model turn, maintaining conversation flow and API requirements.
  • Testing: Added a new unit test case to verify that the continuation turn is correctly injected before the API call is dispatched.
Using Gemini Code Assist

The full guide for Gemini Code Assist can be found on our documentation page, here are some quick tips.

Invoking Gemini

You can request assistance from Gemini at any point by creating a comment using either /gemini <command> or @gemini-code-assist <command>. Below is a summary of the supported commands on the current page.

Feature Command Description
Code Review /gemini review Performs a code review for the current pull request in its current state.
Pull Request Summary /gemini summary Provides a summary of the current pull request in its current state.
Comment @gemini-code-assist Responds in comments when explicitly tagged, both in pull request comments and review comments.
Help /gemini help Displays a list of available commands.

Customization

To customize the Gemini Code Assist for GitHub experience, repository maintainers can create a configuration file and/or provide a custom code review style guide (such as PEP-8 for Python) by creating and adding files to a .gemini/ folder in the base of the repository. Detailed instructions can be found here.

Limitations & Feedback

Gemini Code Assist may make mistakes. Please leave feedback on any instances where its feedback is incorrect or counterproductive. You can react with 👍 and 👎 on @gemini-code-assist comments. If you're interested in giving your feedback about your experience with Gemini Code Assist for GitHub and other Google products, sign up here.

Footnotes

  1. Review the Privacy Notices, Generative AI Prohibited Use Policy, Terms of Service, and learn how to configure Gemini Code Assist in GitHub here. Gemini can make mistakes, so double check it and use code with caution. ↩

@google-cla

google-cla Bot commented Sep 27, 2026

Copy link
Copy Markdown

Thanks for your pull request! It looks like this may be your first contribution to a Google open source project. Before we can look at your pull request, you'll need to sign a Contributor License Agreement (CLA).

View this failed invocation of the CLA check for more information.

For the most up to date status, view the checks section at the bottom of the pull request.

@github-actions github-actions Bot added the size/m A medium sized PR label Sep 27, 2026
@github-actions

github-actions Bot commented Sep 27, 2026 •

Copy link
Copy Markdown

📊 PR Size: size/M

  • Lines changed: 80
  • Additions: +80
  • Deletions: -0
  • Files changed: 2

@gemini-code-assist gemini-code-assist Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Code Review

This pull request ensures that requests to the Gemini API do not end with a model turn by appending a continuation user turn ("Please continue.") if the last turn in the chat history is from the model, preventing potential 400 Bad Request errors. A unit test has been added to verify this behavior. The reviewer recommends cloning the contentsToUse array before mutating it with .push() to avoid unexpected side effects on shared or read-only arrays.

Comment thread packages/core/src/core/geminiChat.ts Outdated
Comment on lines +1086 to +1089
contentsToUse.push({
role: 'user',
parts: [{ text: 'Please continue.' }],
});

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

high

Directly mutating contentsToUse using .push() can lead to unexpected side effects if it is a shared or read-only array. However, using the spread operator (...) to append to arrays can lead to potential stack overflow errors if the array grows very large (e.g., long chat histories). To safely append to the array without mutating the original or risking stack overflow, clone the array elements and use .push() on the new array.

        const updatedContents = contentsToUse.map(item => structuredClone(item));
        updatedContents.push({
          role: 'user',
          parts: [{ text: 'Please continue.' }],
        });
        contentsToUse = updatedContents;
References
  1. When appending to arrays, using a loop with push and structuredClone can be a safer alternative to using the spread operator (...) to avoid potential stack overflow errors when dealing with very large arrays.

@gemini-cli gemini-cli Bot added priority/p1 Important and should be addressed in the near term. area/agent Issues related to Core Agent, Tools, Memory, Sub-Agents, Hooks, Agent Quality labels Sep 27, 2026
@asieveking

Copy link
Copy Markdown
Author

@google-cla I signed it!

@gemini-cli gemini-cli Bot added status/need-issue Pull requests that need to have an associated issue. and removed status/need-issue Pull requests that need to have an associated issue. labels Sep 27, 2026
@gemini-cli

gemini-cli Bot commented Oct 5, 2026

Copy link
Copy Markdown
Contributor

Hi there! Thank you for your interest in contributing to Gemini CLI.

To ensure we maintain high code quality and focus on our prioritized roadmap, we only guarantee review and consideration of pull requests for issues that are explicitly labeled as 'help wanted'.

This PR will be closed in 7 days if it remains without that designation. We encourage you to find and contribute to existing 'help wanted' issues in our backlog! Thank you for your understanding.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area/agent Issues related to Core Agent, Tools, Memory, Sub-Agents, Hooks, Agent Quality priority/p1 Important and should be addressed in the near term. size/m A medium sized PR status/pr-nudge-sent

Projects

None yet

Development

Successfully merging this pull request may close these issues.

bug(core): 400 Bad Request "Requests ending with a model turn are not supported" after /rewind or interrupted stream

1 participant