Skip to content

fix(google): never emit empty or malformed content parts (#420) - #430

Closed
snowyukitty wants to merge 2 commits into
lidge-jun:devfrom
snowyukitty:fix/gemini-empty-content-parts
Closed

snowyukitty wants to merge 2 commits into
lidge-jun:devfrom
snowyukitty:fix/gemini-empty-content-parts

Conversation

@snowyukitty

@snowyukitty snowyukitty commented Jul 25, 2026 •

Copy link
Copy Markdown
Contributor

Closes #420.

Problem

google-antigravity is registered with adapter: "google" (src/providers/registry.ts), so
opencodex sends Gemini contents and Antigravity translates them into Anthropic messages for
Claude models. The req_vrtx_... id in the report is a Vertex Anthropic request, so the 400 is
raised after that translation — the issue attributes the block to messagesToAnthropicFormat, but
the producer is the Google serializer.

messagesToGeminiFormat (src/adapters/google.ts) had no empty-content guard, so four shapes could
reach the wire:

Source Emitted part After translation
content: "" { text: "" } {"type":"text"} → content.N.text.text: Field required
a part with text: "" { text: "" } same
a part with a missing/non-string text {} (bare part) same
a thinking-only assistant turn { role: "model", parts: [] } empty content array → 400

The bare {} is reachable from ordinary input: src/responses/parser.ts builds
{ type: "text", text: (block as { text: string }).text } without validating the cast, so a
Responses input_text block with no text key becomes { text: undefined }, which
JSON.stringify drops entirely.

That Anthropic rejects empty text blocks is already established in this repo by 7ff4c7c
("guard against empty text content blocks (400 rejection)"). Gemini accepts all four shapes,
which is why this only surfaces on Claude-on-Antigravity, and why the reproduction needs a long
tool-heavy session — more turns, more chances for one empty part.

Fix

All in messagesToGeminiFormat (src/adapters/google.ts). Every emitted turn now has at least one
part, and every text part a non-empty string text:

  • Empty string content → "(empty)" placeholder.
  • Empty or non-string text parts → dropped via a small geminiTextPart() helper; a user turn
    left with nothing falls back to the "(empty)" placeholder.
  • Assistant turns with nothing representable (e.g. thinking-only) → skipped instead of sent as
    parts: [], matching what the Anthropic adapter already does for its own empty assistant content
    (src/adapters/anthropic.ts).
  • Empty tool-result text → "(empty tool output)" placeholder.

Placeholder strings are reused from the Anthropic adapter so the two adapters stay symmetric. Image
parts, functionCall / functionResponse parts, thought signatures, and tool-call id pairing are
untouched.

The guard applies to every Google provider, not only Antigravity: an empty part carries no
information for Gemini either, and one code path keeps the same bug from reappearing on Vertex.

Tests

  • tests/google-empty-content.test.ts (new, 12 cases): one per malformed shape above, an
    assertNoEmptyTextParts invariant applied across the whole contents array, the empty
    tool-result-array cases from review, and unchanged-passthrough controls. All 10 guard cases fail
    without the source change
    ; the controls pass either way.
  • Google suites green — adapter, antigravity-wire, antigravity-replay, hardening, wire-compiler,
    vertex-stream, tool-schema, plus the new file: 118 passed across 8 files.
  • bun run typecheck and bun run privacy:scan pass.
  • Full suite: 4,048 passed, 4 failed, 4 skipped across 323 files. All 4 failures are
    pre-existing on this Windows machine and reproduce on a clean dev checkout:
    • ci-workflows (2) — Bun.spawnSync(["bun", …]) resolves bun from PATH, which this machine
      does not have; the file passes 10/10 once bun is on PATH.
    • codex-catalog routed-normalization (1) — cross-file state pollution; the identical 12-file
      group produces the identical failures on clean dev (222 pass / 3 fail both sides).
    • openai-provider-option-e2e spine (1) — same cross-file effect; the identical file set gives
      137 pass / 1 fail on clean dev too, and the file passes 1/1 alone.

No test makes a live provider request.

A note on how the full suite was run: a single bun test process hangs on this machine partway
through the anthropic e2e files, and that hang reproduces on a clean dev checkout with no
changes applied
, so it is environmental rather than something this PR introduces. To get real
coverage anyway I ran the suite in 27 batches; the one batch that hit the hang was then re-run
file-by-file (120 passed, 0 failed). The batched run was performed at the pre-rebase commit; the
rebase since then only pulled in the CI/issue-bot commits (#423), which touch no src/ path in
this diff's neighbourhood, and the Google suites, typecheck, and privacy scan were re-run after the
rebase. CI remains the authority here.

Notes

  • I considered validating the cast in src/responses/parser.ts instead. The serializer is the right
    place: it is the last point that knows what the wire accepts, it has to hold for content arriving
    from the Claude ingress, sidecars, and replayed history too, and it keeps the Google and Anthropic
    adapters symmetric. Happy to send parser-side hardening separately if you want it.
  • Skipping an empty model turn can leave two consecutive user turns. The previous parts: []
    shape was itself rejected upstream, so this is not a regression, and the Anthropic adapter already
    skips empty assistant content the same way — flagging it as the one behavioral change beyond
    dropping empties.
  • No authentication, credential, logging, or workflow path is touched.

Review follow-up (CodeRabbit, #430)

contentPartsToText collapses an empty array — or one holding only empty text — to its "[image]"
marker, so the first commit's || placeholder was unreachable for array content and the tool result
claimed an image the turn does not carry (toolResultImageParts contributes none). Fixed in
8704ab7b with a geminiToolResultText() helper gated on representable text or image content, plus
three cases: empty array, all-empty-text array, and an image-only control that must still report
[image]. The two guard cases fail against the pre-fix source; the control passes either way.

Summary by CodeRabbit

  • Bug Fixes
    • Improved Google (Gemini) request formatting to avoid sending invalid empty text blocks.
    • Added placeholder text handling for empty/malformed user messages and tool outputs.
    • Filtered assistant messages so empty/non-emittable content is not sent, and tool results now always include a safe, non-empty result when applicable.
  • Tests
    • Added coverage to verify empty, malformed, and valid content cases for user, assistant, and tool messages are translated into correct Gemini request payloads.

Antigravity translates Gemini contents into Anthropic messages for Claude
models, and Anthropic rejects text blocks whose text is empty or absent.
messagesToGeminiFormat could emit an empty text part, a bare {} part from a
missing/non-string text, or a parts: [] model turn, each of which 400s with
messages.N.content.M.text.text: Field required.

Guarantee every turn has at least one part and every text part a non-empty
string, mirroring the Anthropic adapter's existing empty-block guard.
@github-actions github-actions Bot added the bug Something isn't working label Jul 25, 2026
@coderabbitai

coderabbitai Bot commented Jul 25, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

The Google adapter now filters empty or malformed Gemini content, inserts placeholders for empty user and tool results, omits assistant turns without representable parts, and adds comprehensive serialization tests.

Changes

Google content serialization

Layer / File(s) Summary
Adapter content guards
src/adapters/google.ts
Adds non-empty text-part filtering, image handling, (empty) and (empty tool output) fallbacks, omission of empty assistant turns, and guarded tool-result serialization.
Serialization guard coverage
tests/google-empty-content.test.ts
Tests malformed and empty user content, assistant filtering, empty and image-only tool results, request validity, and preservation of non-empty content.

Estimated code review effort: 2 (Simple) | ~10 minutes

Suggested reviewers: ingwannu, lidge-jun

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 50.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Linked Issues check ✅ Passed The code changes directly address #420 by filtering invalid text parts, inserting placeholders, and omitting empty assistant turns before Anthropic serialization.
Out of Scope Changes check ✅ Passed The changes stay focused on Google adapter serialization and targeted tests, with no unrelated functionality or workflow changes.
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly matches the main change: Google adapter serialization now avoids empty or malformed content parts.
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

Comment @coderabbitai help to get the list of available commands.

@coderabbitai coderabbitai 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.

Actionable comments posted: 1

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@src/adapters/google.ts`:
- Line 181: Update the functionResponse construction in src/adapters/google.ts
at lines 181-181 to call contentPartsToText only when msg.content contains
non-empty text or image content; otherwise use
GEMINI_EMPTY_TOOL_OUTPUT_PLACEHOLDER. Add coverage in
tests/google-empty-content.test.ts at lines 107-117 for an empty content array
and arrays containing only empty text parts.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro Plus

Run ID: 9de3e692-3e47-496e-92a6-619424f0a58b

📥 Commits

Reviewing files that changed from the base of the PR and between 3fac781 and 5f9fcb9.

📒 Files selected for processing (2)
  • src/adapters/google.ts
  • tests/google-empty-content.test.ts

Comment thread src/adapters/google.ts Resolved
contentPartsToText collapses an empty array, or one holding only empty
text, to its "[image]" marker, so the previous guard never reached the
placeholder for array content and claimed an image the turn does not
carry (toolResultImageParts adds none).

Gate the conversion on representable text or image content. Addresses
CodeRabbit review feedback on lidge-jun#430.

@coderabbitai coderabbitai 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.

Actionable comments posted: 1

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@src/adapters/google.ts`:
- Around line 113-116: Update geminiToolResultText to count an image only when
toolResultImageParts can emit it, excluding malformed or remote image URLs from
hasContent and allowing GEMINI_EMPTY_TOOL_OUTPUT_PLACEHOLDER when no text or
supported images remain. Add a regression test covering an invalid or remote
image URL and verify the result uses the placeholder without an emitted image
part.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro Plus

Run ID: d315fd31-7b4c-4f38-9751-32c5a9f7d072

📥 Commits

Reviewing files that changed from the base of the PR and between 5f9fcb9 and 8704ab7.

📒 Files selected for processing (2)
  • src/adapters/google.ts
  • tests/google-empty-content.test.ts

Comment thread src/adapters/google.ts Resolved
@lidge-jun

Copy link
Copy Markdown
Owner

🔒 Maintainer integration in progress — please hold off on merging

@lidge-jun (maintainer) is actively integrating this PR into dev as part of a coordinated
integration pass. Please do not merge, rebase, force-push, or close this PR until this
marker is removed.

What is happening

This PR is being integrated on the maintainer branch codex/260725-pr-rework, which is
based on dev. The pass applies the contributed change, adds any missing regression
coverage, and repairs review-identified defects before a single verified merge into dev.
Every integrated change goes through bun run typecheck, the full bun run test suite,
bun run privacy:scan, and bun run lint:gui, followed by exact-SHA hosted
Cross-platform CI and Service lifecycle runs.

What this means for you

  • Your authorship and commits are preserved. Nothing is being rewritten under your name.
  • No action is needed from you right now. If a defect repair changes your intended
    behavior, it will be described explicitly in a follow-up comment before the merge.
  • If you have work in flight on this branch, please comment here instead of pushing, so we
    do not race each other.

This PR will be closed with a merge receipt (integration commit SHA, verification output,
and hosted CI links) once the pass lands on dev. Thanks for the contribution.

Integration tracker: devlog/_plan/260725_pr_issue_rework · marker posted by the maintainer integration pass

lidge-jun added a commit that referenced this pull request Jul 25, 2026
PR #430 (head 8704ab7, author snowyukitty)을 통합하고 회귀 테스트 2건을 추가한다.

Antigravity가 Gemini contents를 Anthropic messages로 변환할 때 빈 text 블록은
messages.N.content.M.text.text: Field required 400을 유발한다. user/developer의 빈
문자열과 빈 파트 배열은 placeholder로, assistant의 빈 text 파트는 drop하고 방출할
파트가 없는 turn은 생략하며, 빈 tool result는 전용 placeholder를 쓴다.

추가한 회귀 2건:
- 빈 developer message가 user role로 변환되며 동일 placeholder를 방출
- assistant text 배열이 전부 빈 경우 turn 자체가 생략됨

Co-authored-by: snowyukitty <[email protected]>
@lidge-jun

Copy link
Copy Markdown
Owner

✅ Integrated into dev

Thank you for this fix. It has been integrated into dev as part of a verified integration pass.

Integration commit: 74795ad6 — fix(google): never emit empty or malformed content parts (#420)
Merged into dev at: ebc62d1f
Your authorship is preserved via Co-authored-by.

What was added on top

Two regressions that the original test file did not yet cover:

  • an empty developer message converts to the user role and emits the same non-empty placeholder
  • an assistant text array whose parts are all empty skips the turn entirely

Verification

  • bun test tests/google-empty-content.test.ts: 14 pass / 0 fail
  • Activation proof: reverting the guard makes 12 of those 14 fail, so the fix is demonstrably the thing doing the work
  • Full suite at merge: 4222 pass / 0 fail (327 files)
  • bun run typecheck, bun run privacy:scan, bun run lint:gui: all clean

Issue #420 is closed by this change. Thanks again for tracking down the Antigravity/Anthropic translation edge — the empty-parts case in particular was easy to miss.

@lidge-jun

Copy link
Copy Markdown
Owner

Closing: integrated into dev at ebc62d1f with authorship preserved. See the receipt comment above for the integration commit, the changes made on top, and the verification evidence.

@lidge-jun lidge-jun closed this Jul 25, 2026
agentHits pushed a commit to agentHits/opencodex that referenced this pull request Sep 17, 2026
PR lidge-jun#430 (head 8704ab7, author snowyukitty)을 통합하고 회귀 테스트 2건을 추가한다.

Antigravity가 Gemini contents를 Anthropic messages로 변환할 때 빈 text 블록은
messages.N.content.M.text.text: Field required 400을 유발한다. user/developer의 빈
문자열과 빈 파트 배열은 placeholder로, assistant의 빈 text 파트는 drop하고 방출할
파트가 없는 turn은 생략하며, 빈 tool result는 전용 placeholder를 쓴다.

추가한 회귀 2건:
- 빈 developer message가 user role로 변환되며 동일 placeholder를 방출
- assistant text 배열이 전부 빈 경우 turn 자체가 생략됨

Co-authored-by: snowyukitty <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

bug Something isn't working

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants