Gemini SSE heartbeat ("\n") breaks google.golang.org/genai streaming (+ suggestion to add Antigravity CLI setup)
Transparency note: This issue report was drafted with the assistance of an LLM after auditing the codebase, investigating the failure logs, reproducing the bug deterministically in a Go integration test, and verifying the fix on a locally compiled Linux binary in a real long-context Antigravity CLI (
agy) session.
This issue covers two related items from running Antigravity CLI (agy) against AIStudio2API's Gemini SSE endpoint:
- Bug Report & Fix: Why
geminiHeartbeat = "\n"causes intermittentiterateResponseStream: invalid stream chunk+HTTP 499failures ingoogle.golang.org/genaiclients, and the one-line fix ("\n\n"). - Feature / Docs Suggestion: Adding Antigravity CLI (
agy) to Connect → Clients (web/src/access/clients.ts) and the README client examples.
1. Bug: geminiHeartbeat = "\n" breaks google.golang.org/genai SSE streaming after odd keepalives
Summary
When using Gemini SSE streaming (POST /v1beta/models/{model}:streamGenerateContent?alt=sse) with clients built on the official Go SDK googleapis/go-genai — such as Antigravity CLI (agy) configured with a custom Gemini API endpoint — long-context or slow-thinking requests intermittently abort mid-stream with:
iterateResponseStream: invalid stream chunk: \ndata: {"candidates":[...]}
(Note: terminal/TUI error banners may collapse the newline after chunk:, displaying invalid stream chunk: data: {"candidates":...}.)
At the exact moment the next upstream event arrives, AIStudio2API logs HTTP 499 context canceled because the client immediately closes the response body upon rejecting the chunk.
Root Cause
In internal/api/keepalive.go:
const (
sseHeartbeat = ": ping\n\n"
anthropicHeartbeat = "event: ping\ndata: {\"type\":\"ping\"}\n\n"
geminiHeartbeat = "\n"
)
For POST .../models/{model}:streamGenerateContent?alt=sse:
handleGeminiGenerate(internal/api/gemini.go) callsstartChatChoices(internal/api/chat_choices.go), which waits up tostreamHeartbeatInterval(10s,internal/api/generate.go) inawaitStreamStartbefore returning if no upstream event has arrived yet.streamGeminithen callsopenGeminiStream(w, r), which callsopenStream(w, geminiHeartbeat), writing HTTP200SSE headers and starting a10skeepalive timer (streamKeepalive).- Unlike
sseHeartbeatandanthropicHeartbeat(both terminated with\n\n),geminiHeartbeatwrites a single"\n".
Meanwhile, googleapis/go-genai (api_client.go) parses SSE streams using bufio.Scanner with custom scan():
scan()splits frames on"\n\n"(or"\r\n\r\n"), not on single"\n"lines (bytes.Index(data, []byte("\n\n"))).iterateResponseStream()skips empty tokens (if len(line) == 0 { continue }).- Otherwise, it runs
prefix, data, _ := bytes.Cut(line, []byte(":"))and switches onstring(prefix):case "data":unmarshals the JSON chunk.default:attempts error JSON unmarshaling (respWithError) and otherwise aborts withfmt.Errorf("iterateResponseStream: invalid stream chunk: %s:%s", string(prefix), string(data)). (This is also why: ping\n\ncannot be used for Gemini —go-genairejects:comment lines withinvalid stream chunk: : ping.)
Because every data chunk from writeSSE (internal/api/errors.go) ends with "\n\n", scan() leaves an empty buffer after each valid chunk. Once idle heartbeats begin firing every 10s:
- 0 heartbeats (
< 10sidle afteropenStream): buffer stays clean; works normally. - Even number of heartbeats (
2, 4, ...→"\n\n","\n\n\n\n"): pairs of"\n"form"\n\n", whichscan()emits as empty tokens (len(line) == 0) and skips cleanly. - Odd number of heartbeats (
1, 3, 5, ...→"\n","\n\n\n"): one unpaired"\n"stays buffered and gets prepended to the very nextwriteSSEframe ("data: {...}\n\n"):- Wire bytes since the previous
"\n\n"delimiter:"\ndata: {...}\n\n" scan()returns token:"\ndata: {...}"bytes.Cutyieldsprefix = "\ndata"(!= "data"), falling intodefault:and aborting the stream.
- Wire bytes since the previous
Observed Behavior & Logs (Real Session)
This occurred repeatedly in longer-context conversations (e.g., 63k–242k prompt tokens) regardless of WAA backend (observed identically with both SpiderMonkey and Camoufox, since the bug is in the HTTP SSE keepalive layer):
-
Slow initial response (
Wait=21.066sbefore first chunk):18:54:21request starts → after10s(~18:54:31),awaitStreamStarttimes out andopenGeminiStreamopens the SSE stream with a10stimer → at~18:54:41(+10s), 1"\n"heartbeat fires → at18:54:43(21.066s), upstream headers arrive and the firstthoughtchunk is written ("\ndata: {...}\n\n"):499 gemini-4-hydrogen Playground 21.12 s context canceled 18:54:21 Request started 18:54:21 Waiting for upstream response 18:54:21 Upstream call | Channel=playground | Mode=stream | RPC=GenerateContent 18:54:36 Request preparation waiting | waited=15s | current=Waiting for upstream response headers 18:54:43 Request preparation ended | Wait=21.066s | WAA=16ms | Response headers=21.05s 18:54:43 Request canceledClient error:
iterateResponseStream: invalid stream chunkon the firstthoughtchunk. -
Mid-stream pause (
pause=33.39sbeforetool_call): Initial reasoning events streamed normally (ending around19:51:58, resettingstreamKeepalive's timer). During the subsequent33.39spause beforetool_call, 3"\n"heartbeats (+10s,+20s,+30s) fired ("\n\n\n"). The first two paired into"\n\n", and the 3rd"\n"corrupted thewrite_filefunctionCallchunk at19:52:32:499 gemini-4-hydrogen Playground 53.67 s Tool calls 1 context canceled 19:51:38 Request started 19:51:38 Waiting for upstream response 19:51:38 Upstream call | Channel=playground | Mode=stream | RPC=GenerateContent 19:52:13 Event stream paused | Model=gemini-4-hydrogen | waited=15s | recent_events=reasoning | reasoning=5 | Bodies=0 | Network bytes=3310 | recent_network=15.002s 19:52:32 Event stream resumed | Model=gemini-4-hydrogen | pause=33.39s | current_event=tool_call 19:52:32 Request canceledClient error:
iterateResponseStream: invalid stream chunkon thewrite_filefunctionCallchunk.
Notes on Reproduction
- In live AI Studio usage: It is difficult to reproduce deterministically on demand because it depends on upstream latency/pauses landing on an odd multiple of
streamHeartbeatInterval(10s) — specifically10–20s,30–40s,50–60sbetween writes (or20–30s,40–50sbefore the first chunk whenawaitStreamStarttakes the first10s), whereas even multiples (20–30smid-stream, etc.) accidentally succeed due to\npairing. - In a controlled Go test: It reproduces 100% deterministically by wiring
api.NewHandleroverhttptest.NewServerwith a mockaistudio.Serviceand callingModels.GenerateContentStreamfromgoogle.golang.org/genai:21sdelay before the first event (awaitStreamStart10s+1heartbeat): fails withiterateResponseStream: invalid stream chunk: \ndata: ...(chunks=0).11spause betweenEventReasoningandEventToolCall(1heartbeat): fails withiterateResponseStream: invalid stream chunk: \ndata: ...(chunks=1).21spause betweenEventReasoningandEventToolCall(2heartbeats ="\n\n"): succeeds (chunks=3,err=<nil>).
Suggested Fix
In internal/api/keepalive.go, change geminiHeartbeat from "\n" to "\n\n" so every heartbeat emits a complete empty SSE frame delimiter:
const (
sseHeartbeat = ": ping\n\n"
anthropicHeartbeat = "event: ping\ndata: {\"type\":\"ping\"}\n\n"
geminiHeartbeat = "\n\n"
)
(Note: streamKeepalive already serializes beat() and Write() with writer.mu, nonstreamKeepalive (keepaliveWriter) only affects non-SSE JSON responses, and alt != "sse" JSON array streaming does not use geminiHeartbeat. Adding a unit test in internal/api/ covering openGeminiStream (alt=sse) with odd heartbeats would also prevent regressions.)
Verification & Compatibility
- Why
\n\nis safe for all Gemini SSE clients: Under the WHATWG SSE specification (used by JS@google/genaiviaeventsource-parser, Pythongoogle-genai,EventSource, andcurl), blank lines with an empty event data buffer are a spec-compliant no-op and dispatch no event. Ingo-genai, each"\n\n"heartbeat is immediately consumed as an empty token and skipped (len(line) == 0), leaving the scanner buffer completely clean before the nextwriteSSEframe (orgeminiStream.failerror frame). - Test & real-world verification:
- Re-ran the
google.golang.org/genaiGo integration test above withgeminiHeartbeat = "\n\n": all three timing scenarios (21sinitial delay,11spause,21spause) passed witherr=<nil>. - Ran the existing Go test suite (
go test -mod=readonly -trimpath -vet=off -tags netgo,osusergo ./cmd/... ./internal/...) with Zig + SpiderMonkey/libwebp static libraries: all packages passed. - Compiled a static Linux
amd64binary with the fix and tested it on the exact same long-context Antigravity CLI conversation that previously failed repeatedly — streaming and tool calls completed cleanly with noinvalid stream chunkor499 context canceled.
- Re-ran the
2. Suggestion: Add Antigravity CLI (agy) to Connect > Clients & Client Docs
Since AIStudio2API already provides guided agent setup both in the Web UI (Connect → Clients in web/src/components/AccessPanel.vue / web/src/access/clients.ts) and in README.md / README_en.md (Client Configuration Example), it would be great to add Antigravity CLI (agy) alongside Claude Code, Codex, OpenCode, pi, omp, etc.
Unlike the Antigravity desktop IDE, the standalone Antigravity CLI (agy) officially supports authenticating with a Gemini API key and pointing GOOGLE_GEMINI_BASE_URL to a custom Gemini-compatible endpoint, as documented in the official Antigravity CLI install guide:
- https://antigravity.google/docs/install/?tab=cli
Per that guide, connecting agy to AIStudio2API takes two steps:
- Enable Gemini API-key mode in
~/.gemini/antigravity-cli/settings.json:{ "modelProvider": "gemini" } - Set
GEMINI_API_KEY(PROXY_API_KEYfrom.env) andGOOGLE_GEMINI_BASE_URL(the service roothttp://127.0.0.1:2048/input.originwithout/v1beta, matching the existing Gemini base URL inAccessPanel.vueandREADME_en.md) and startagy:
(Plusexport GEMINI_API_KEY="<PROXY_API_KEY>" export GOOGLE_GEMINI_BASE_URL="http://127.0.0.1:2048" agy$env:...PowerShell syntax on Windows.)
Suggested placement
- Web UI (
web/src/access/clients.ts+web/src/locales/*.ts): Add an entry undergroup: 'agent'withprotocols: ['gemini'],shell: true, andnoModel: true, using:access.step.configFilefor~/.gemini/antigravity-cli/settings.json({"modelProvider": "gemini"}), andenvStep(access.step.envRun) settingGEMINI_API_KEYandGOOGLE_GEMINI_BASE_URL(input.origin) and launchingagy. (Optionally noteMODEL_MAPPINGif model aliases are needed.)
- Documentation (
README.md/README_en.md): Add the same short snippet under Client Configuration Example with a reference tohttps://antigravity.google/docs/install/?tab=cliso users know they can useagydirectly withAIStudio2APIvia custom API key + endpoint.
fixed in v0.3.10, heartbeat is now an empty frame so genai skips it, and agy setup is added to the access page and README.
Thank you for resolving the streaming issue and adding Antigravity CLI to Connect → Clients and the documentation.
One small note regarding the Antigravity CLI link used for Homepage in Connect → Clients and in the README (README.md / README_en.md): it currently points to https://antigravity.google/docs/install?tab=cli, which was included in the issue only as a reference for API-key authentication rather than the repository, product page, or CLI installation overview.
For those links, one of the following would be a better fit (especially the GitHub repository for consistency with the other agent links like Claude Code and Codex, keeping /docs/install/?tab=cli only if linking specifically to the API-key auth instructions):
- GitHub repository: https://github.com/google-antigravity/antigravity-cli
- Product page: https://antigravity.google/product/antigravity-cli
- CLI installation / getting-started docs: https://antigravity.google/docs/getting-started/?tab=cli